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-release/src/test/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/test/java/org/apache/maven/continuum/release/phase/UpdateWorkingCopyPhaseTest.java
package org.apache.maven.continuum.release.phase; /* * 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.release.config.ContinuumReleaseDescriptor; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.PlexusSpringTestCase; import org.apache.maven.settings.Settings; import org.apache.maven.shared.release.phase.ReleasePhase; import org.junit.Before; import org.junit.Test; import java.io.File; import static org.junit.Assert.*; public class UpdateWorkingCopyPhaseTest extends PlexusSpringTestCase { private FileSystemManager fsManager; private UpdateWorkingCopyPhase phase; private ContinuumReleaseDescriptor releaseDescriptor; private File workingDirectory; @Before public void setUp() throws Exception { fsManager = lookup( FileSystemManager.class ); phase = (UpdateWorkingCopyPhase) lookup( ReleasePhase.class, "update-working-copy" ); assertNotNull( phase ); releaseDescriptor = createReleaseDescriptor(); workingDirectory = new File( releaseDescriptor.getWorkingDirectory() ); // Ensure every test method starts with no working dir fsManager.removeDir( workingDirectory ); assertFalse( workingDirectory.exists() ); // set up project scm File scmPathFile = new File( getBasedir(), "target/scm-src" ).getAbsoluteFile(); File scmTargetPathFile = new File( getBasedir(), "/target/scm-test" ).getAbsoluteFile(); fsManager.copyDir( scmPathFile, scmTargetPathFile ); } @Test public void testWorkingDirDoesNotExist() throws Exception { phase.execute( releaseDescriptor, new Settings(), null ); assertPopulatedWorkingDirectory(); } @Test public void testWorkingDirAlreadyExistsWithProjectCheckout() throws Exception { // Run the update once, should checkout out the project into working dir phase.execute( releaseDescriptor, new Settings(), null ); assertPopulatedWorkingDirectory(); // Run again, to ensure nothing funny happened phase.execute( releaseDescriptor, new Settings(), null ); assertPopulatedWorkingDirectory(); } @Test public void testWorkingDirAlreadyExistsNoProjectCheckout() throws Exception { workingDirectory.mkdirs(); assertEmptyWorkingDirectory(); phase.execute( releaseDescriptor, new Settings(), null ); assertPopulatedWorkingDirectory(); } private void assertEmptyWorkingDirectory() { assertTrue( workingDirectory.exists() ); assertTrue( workingDirectory.listFiles().length == 0 ); } private void assertPopulatedWorkingDirectory() { assertTrue( workingDirectory.exists() ); assertTrue( workingDirectory.listFiles().length > 0 ); } private ContinuumReleaseDescriptor createReleaseDescriptor() { // project source and working directory paths String projectUrl = getBasedir() + "/target/scm-test/trunk"; String workingDirPath = getBasedir() + "/target/test-classes/updateWorkingCopy_working-directory"; // create release descriptor ContinuumReleaseDescriptor releaseDescriptor = new ContinuumReleaseDescriptor(); releaseDescriptor.setScmSourceUrl( "scm:svn:file://localhost/" + projectUrl ); releaseDescriptor.setWorkingDirectory( workingDirPath ); return releaseDescriptor; } }
5,400
0
Create_ds/continuum/continuum-release/src/test/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/test/java/org/apache/maven/continuum/release/executors/ReleaseTaskExecutorTest.java
package org.apache.maven.continuum.release.executors; /* * 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.release.config.ContinuumReleaseDescriptor; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.PlexusSpringTestCase; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.release.tasks.PerformReleaseProjectTask; import org.apache.maven.continuum.release.tasks.PrepareReleaseProjectTask; import org.apache.maven.continuum.release.tasks.RollbackReleaseProjectTask; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.ScmVersion; import org.apache.maven.scm.manager.NoSuchScmProviderException; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.repository.ScmRepository; import org.apache.maven.scm.repository.ScmRepositoryException; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; 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.IOUtil; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import static org.junit.Assert.*; /** * @author Edwin Punzalan */ public class ReleaseTaskExecutorTest extends PlexusSpringTestCase { private ScmManager scmManager; private TaskExecutor prepareExec; private TaskExecutor performExec; private TaskExecutor rollbackExec; private ContinuumReleaseManager releaseManager; private FileSystemManager fsManager; @Before public void setUp() throws Exception { if ( scmManager == null ) { scmManager = lookup( ScmManager.class ); } if ( prepareExec == null ) { prepareExec = lookup( TaskExecutor.class, "prepare-release" ); } if ( performExec == null ) { performExec = lookup( TaskExecutor.class, "perform-release" ); } if ( rollbackExec == null ) { rollbackExec = lookup( TaskExecutor.class, "rollback-release" ); } if ( releaseManager == null ) { releaseManager = lookup( ContinuumReleaseManager.class ); } if ( fsManager == null ) { fsManager = lookup( FileSystemManager.class ); } File scmPath = new File( getBasedir(), "target/scm-src" ).getAbsoluteFile(); File scmTargetPath = new File( getBasedir(), "target/scm-test" ).getAbsoluteFile(); fsManager.copyDir( scmPath, scmTargetPath ); } public void releaseSimpleProject() throws Exception { String scmPath = new File( getBasedir(), "target/scm-test" ).getAbsolutePath().replace( '\\', '/' ); File workDir = new File( getBasedir(), "target/test-classes/work-dir" ); fsManager.removeDir( workDir ); File testDir = new File( getBasedir(), "target/test-classes/test-dir" ); fsManager.removeDir( testDir ); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setInteractive( false ); descriptor.setScmSourceUrl( "scm:svn:file://localhost/" + scmPath + "/trunk" ); descriptor.setWorkingDirectory( workDir.getAbsolutePath() ); ScmRepository repository = getScmRepositorty( descriptor.getScmSourceUrl() ); ScmFileSet fileSet = new ScmFileSet( workDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); String pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test dev version", pom.indexOf( "<version>1.0-SNAPSHOT</version>" ) > 0 ); doPrepareWithNoError( descriptor ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test version increment", pom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); repository = getScmRepositorty( "scm:svn:file://localhost/" + scmPath + "/tags/test-artifact-1.0" ); fileSet = new ScmFileSet( testDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); pom = fsManager.fileContents( new File( testDir, "pom.xml" ) ); assertTrue( "Test released version", pom.indexOf( "<version>1.0</version>" ) > 0 ); } @Test public void testReleases() throws Exception { releaseSimpleProject(); releaseAndRollbackProject(); releaseSimpleProjectWithNextVersion(); releasePerformWithExecutableInDescriptor(); releaseProjectWithDependencyOfCustomPackagingType(); releaseProjectWithProfile(); } public void releaseSimpleProjectWithNextVersion() throws Exception { String scmPath = new File( getBasedir(), "target/scm-test" ).getAbsolutePath().replace( '\\', '/' ); File workDir = new File( getBasedir(), "target/test-classes/work-dir" ); fsManager.removeDir( workDir ); File testDir = new File( getBasedir(), "target/test-classes/test-dir" ); fsManager.removeDir( testDir ); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setInteractive( false ); descriptor.setScmSourceUrl( "scm:svn:file://localhost/" + scmPath + "/trunk" ); descriptor.setWorkingDirectory( workDir.getAbsolutePath() ); descriptor.mapReleaseVersion( "test-group:test-artifact", "2.0" ); descriptor.mapDevelopmentVersion( "test-group:test-artifact", "2.1-SNAPSHOT" ); ScmRepository repository = getScmRepositorty( descriptor.getScmSourceUrl() ); ScmFileSet fileSet = new ScmFileSet( workDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); String pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test dev version", pom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); doPrepareWithNoError( descriptor ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test version increment", pom.indexOf( "<version>2.1-SNAPSHOT</version>" ) > 0 ); repository = getScmRepositorty( "scm:svn:file://localhost/" + scmPath + "/tags/test-artifact-2.0" ); fileSet = new ScmFileSet( testDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); pom = fsManager.fileContents( new File( testDir, "pom.xml" ) ); assertTrue( "Test released version", pom.indexOf( "<version>2.0</version>" ) > 0 ); /* CONTINUUM-2559 performExec.executeTask( getPerformTask( "testRelease", descriptor, new File( getBasedir(), "target/test-classes/build-dir" ) ) ); ReleaseResult result = (ReleaseResult) releaseManager.getReleaseResults().get( "testRelease" ); if ( result.getResultCode() != ReleaseResult.SUCCESS ) { fail( "Error in release:perform. Release output follows:\n" + result.getOutput() ); } */ } public void releaseAndRollbackProject() throws Exception { String scmPath = new File( getBasedir(), "target/scm-test" ).getAbsolutePath().replace( '\\', '/' ); File workDir = new File( getBasedir(), "target/test-classes/work-dir" ); fsManager.removeDir( workDir ); File testDir = new File( getBasedir(), "target/test-classes/test-dir" ); fsManager.removeDir( testDir ); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setInteractive( false ); descriptor.setScmSourceUrl( "scm:svn:file://localhost/" + scmPath + "/trunk" ); descriptor.setWorkingDirectory( workDir.getAbsolutePath() ); ScmRepository repository = getScmRepositorty( descriptor.getScmSourceUrl() ); ScmFileSet fileSet = new ScmFileSet( workDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); String pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test dev version", pom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); doPrepareWithNoError( descriptor ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test version increment", pom.indexOf( "<version>1.2-SNAPSHOT</version>" ) > 0 ); repository = getScmRepositorty( "scm:svn:file://localhost/" + scmPath + "/tags/test-artifact-1.1" ); fileSet = new ScmFileSet( testDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); pom = fsManager.fileContents( new File( testDir, "pom.xml" ) ); assertTrue( "Test released version", pom.indexOf( "<version>1.1</version>" ) > 0 ); rollbackExec.executeTask( new RollbackReleaseProjectTask( "testRelease", descriptor, null ) ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test rollback version", pom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); assertFalse( "Test that release.properties has been cleaned", new File( workDir, "release.properties" ).exists() ); assertFalse( "Test that backup file has been cleaned", new File( workDir, "pom.xml.releaseBackup" ).exists() ); //@todo when implemented already, check if tag was also removed } public void releasePerformWithExecutableInDescriptor() throws Exception { String scmPath = new File( getBasedir(), "target/scm-test" ).getAbsolutePath().replace( '\\', '/' ); File workDir = new File( getBasedir(), "target/test-classes/work-dir" ); fsManager.removeDir( workDir ); File testDir = new File( getBasedir(), "target/test-classes/test-dir" ); fsManager.removeDir( testDir ); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setInteractive( false ); descriptor.setScmSourceUrl( "scm:svn:file://localhost/" + scmPath + "/trunk" ); descriptor.setWorkingDirectory( workDir.getAbsolutePath() ); ScmRepository repository = getScmRepositorty( descriptor.getScmSourceUrl() ); ScmFileSet fileSet = new ScmFileSet( workDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); String pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test dev version", pom.indexOf( "<version>2.1-SNAPSHOT</version>" ) > 0 ); doPrepareWithNoError( descriptor ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test version increment", pom.indexOf( "<version>2.2-SNAPSHOT</version>" ) > 0 ); repository = getScmRepositorty( "scm:svn:file://localhost/" + scmPath + "/tags/test-artifact-2.1" ); fileSet = new ScmFileSet( testDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); pom = fsManager.fileContents( new File( testDir, "pom.xml" ) ); assertTrue( "Test released version", pom.indexOf( "<version>2.1</version>" ) > 0 ); File file = new File( descriptor.getWorkingDirectory(), "release.properties" ); assertTrue( "release.properties file does not exist", file.exists() ); Properties properties = new Properties(); InputStream inStream = null; OutputStream outStream = null; try { inStream = new FileInputStream( file ); properties.load( inStream ); properties.setProperty( "build.executable", "test/executable/mvn" ); outStream = new FileOutputStream( file ); properties.store( outStream, "release configuration" ); } finally { IOUtil.close( inStream ); } performExec.executeTask( getPerformTask( "testRelease", descriptor, new File( getBasedir(), "target/test-classes/build-dir" ) ) ); ReleaseResult result = (ReleaseResult) releaseManager.getReleaseResults().get( "testRelease" ); if ( !result.getOutput().replace( "\\", "/" ).contains( "test/executable/mvn" ) ) { fail( "Error in release:perform. Missing executable" ); } } // CONTINUUM-1814 public void releaseProjectWithDependencyOfCustomPackagingType() throws Exception { String scmPath = new File( getBasedir(), "target/scm-test/continuum-1814" ).getAbsolutePath().replace( '\\', '/' ); File workDir = new File( getBasedir(), "target/test-classes/continuum-1814" ); fsManager.removeDir( workDir ); File testDir = new File( getBasedir(), "target/test-classes/test-dir" ); fsManager.removeDir( testDir ); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setInteractive( false ); descriptor.setScmSourceUrl( "scm:svn:file://localhost/" + scmPath + "/trunk" ); descriptor.setWorkingDirectory( workDir.getAbsolutePath() ); ScmRepository repository = getScmRepositorty( descriptor.getScmSourceUrl() ); ScmFileSet fileSet = new ScmFileSet( workDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); String pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test dev version", pom.indexOf( "<version>1.6-SNAPSHOT</version>" ) > 0 ); doPrepareWithNoError( descriptor ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test version increment", pom.indexOf( "<version>1.7-SNAPSHOT</version>" ) > 0 ); repository = getScmRepositorty( "scm:svn:file://localhost/" + scmPath + "/tags/continuum-1814-1.6" ); fileSet = new ScmFileSet( testDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); pom = fsManager.fileContents( new File( testDir, "pom.xml" ) ); assertTrue( "Test released version", pom.indexOf( "<version>1.6</version>" ) > 0 ); /* CONTINUUM-2559 performExec.executeTask( getPerformTask( "testRelease", descriptor, new File( getBasedir(), "target/test-classes/build-dir" ) ) ); ReleaseResult result = (ReleaseResult) releaseManager.getReleaseResults().get( "testRelease" ); if ( result.getResultCode() != ReleaseResult.SUCCESS ) { fail( "Error in release:perform. Release output follows:\n" + result.getOutput() ); } */ } // CONTINUUM-2610 public void releaseProjectWithProfile() throws Exception { String scmPath = new File( getBasedir(), "target/scm-test/continuum-2610" ).getAbsolutePath().replace( '\\', '/' ); File workDir = new File( getBasedir(), "target/test-classes/continuum-2610" ); fsManager.removeDir( workDir ); File testDir = new File( getBasedir(), "target/test-classes/test-dir" ); fsManager.removeDir( testDir ); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setInteractive( false ); descriptor.setScmSourceUrl( "scm:svn:file://localhost/" + scmPath + "/trunk" ); descriptor.setWorkingDirectory( workDir.getAbsolutePath() ); descriptor.setAdditionalArguments( "-Pall" ); ScmRepository repository = getScmRepositorty( descriptor.getScmSourceUrl() ); ScmFileSet fileSet = new ScmFileSet( workDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); String pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test root dev version", pom.indexOf( "<version>1.0-SNAPSHOT</version>" ) > 0 ); String moduleAPom = fsManager.fileContents( new File( workDir, "module-A/pom.xml" ) ); assertTrue( "Test module A dev version", moduleAPom.indexOf( "<version>1.0-SNAPSHOT</version>" ) > 0 ); String moduleBPom = fsManager.fileContents( new File( workDir, "module-B/pom.xml" ) ); assertTrue( "Test module B dev version", moduleBPom.indexOf( "<version>1.0-SNAPSHOT</version>" ) > 0 ); doPrepareWithNoError( descriptor ); pom = fsManager.fileContents( new File( workDir, "pom.xml" ) ); assertTrue( "Test root version increment", pom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); moduleAPom = fsManager.fileContents( new File( workDir, "module-A/pom.xml" ) ); assertTrue( "Test module A version increment", moduleAPom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); moduleBPom = fsManager.fileContents( new File( workDir, "module-B/pom.xml" ) ); assertTrue( "Test module B version increment", moduleBPom.indexOf( "<version>1.1-SNAPSHOT</version>" ) > 0 ); repository = getScmRepositorty( "scm:svn:file://localhost/" + scmPath + "/tags/continuum-2610-1.0" ); fileSet = new ScmFileSet( testDir ); scmManager.getProviderByRepository( repository ).checkOut( repository, fileSet, (ScmVersion) null ); pom = fsManager.fileContents( new File( testDir, "pom.xml" ) ); assertTrue( "Test root released version", pom.indexOf( "<version>1.0</version>" ) > 0 ); moduleAPom = fsManager.fileContents( new File( testDir, "module-A/pom.xml" ) ); assertTrue( "Test module A released version", moduleAPom.indexOf( "<version>1.0</version>" ) > 0 ); moduleBPom = fsManager.fileContents( new File( testDir, "module-B/pom.xml" ) ); assertTrue( "Test module B released version", moduleBPom.indexOf( "<version>1.0</version>" ) > 0 ); } private void doPrepareWithNoError( ReleaseDescriptor descriptor ) throws TaskExecutionException { prepareExec.executeTask( getPrepareTask( "testRelease", descriptor ) ); ReleaseResult result = (ReleaseResult) releaseManager.getReleaseResults().get( "testRelease" ); if ( result.getResultCode() != ReleaseResult.SUCCESS ) { fail( "Error in release:prepare. Release output follows:\n" + result.getOutput() ); } } private Task getPrepareTask( String releaseId, ReleaseDescriptor descriptor ) { return new PrepareReleaseProjectTask( releaseId, descriptor, null ); } private Task getPerformTask( String releaseId, ReleaseDescriptor descriptor, File buildDir ) { return new PerformReleaseProjectTask( releaseId, descriptor, buildDir, "package", true, null ); } private ScmRepository getScmRepositorty( String scmUrl ) throws ScmRepositoryException, NoSuchScmProviderException { ScmRepository repository = scmManager.makeScmRepository( scmUrl.trim() ); repository.getProviderRepository().setPersistCheckout( true ); return repository; } }
5,401
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/DefaultReleaseManagerListener.java
package org.apache.maven.continuum.release; /* * 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.shared.release.ReleaseManagerListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Edwin Punzalan */ public class DefaultReleaseManagerListener implements ReleaseManagerListener, ContinuumReleaseManagerListener { private String goalName; private List<String> completedPhases; private String inProgress; private List<String> phases; private String error; private int state; private String username; public void goalStart( String name, List phases ) { state = LISTENING; goalName = name; this.phases = phases; completedPhases = Collections.synchronizedList( new ArrayList<String>() ); inProgress = null; } public void phaseStart( String name ) { inProgress = name; } public void phaseEnd() { completedPhases.add( inProgress ); inProgress = null; } public void phaseSkip( String name ) { completedPhases.add( name ); } public void goalEnd() { state = FINISHED; } public void error( String message ) { error = message; goalEnd(); } public List<String> getCompletedPhases() { return completedPhases; } public String getInProgress() { return inProgress; } public List<String> getPhases() { return phases; } public String getGoalName() { return goalName; } public String getError() { return error; } public int getState() { return state; } public void setUsername( String username ) { this.username = username; } public String getUsername() { return username; } }
5,402
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/DefaultContinuumReleaseManager.java
package org.apache.maven.continuum.release; /* * 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.BooleanUtils; import org.apache.continuum.model.release.ReleaseListenerSummary; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.release.config.ContinuumReleaseDescriptor; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.release.tasks.PerformReleaseProjectTask; import org.apache.maven.continuum.release.tasks.PrepareReleaseProjectTask; import org.apache.maven.continuum.release.tasks.RollbackReleaseProjectTask; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.provider.ScmProvider; import org.apache.maven.scm.repository.ScmRepository; import org.apache.maven.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.config.ReleaseDescriptorStore; import org.apache.maven.shared.release.config.ReleaseDescriptorStoreException; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; 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.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.Collections; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; /** * @author Jason van Zyl * @author Edwin Punzalan */ public class DefaultContinuumReleaseManager implements ContinuumReleaseManager, Contextualizable { private static final String PLEXUS_KEY_PERFORM_RELEASE_TASKQUEUE_EXECUTOR = "perform-release"; private static final String PLEXUS_KEY_PREPARE_RELEASE_TASKQUEUE_EXECUTOR = "prepare-release"; private static final String PLEXUS_KEY_ROLLBACK_RELEASE_TASKQUEUE_EXECUTOR = "rollback-release"; @Requirement private ReleaseDescriptorStore releaseStore; @Requirement private TaskQueue prepareReleaseQueue; @Requirement private TaskQueue performReleaseQueue; @Requirement private TaskQueue rollbackReleaseQueue; @Requirement private ScmManager scmManager; private PlexusContainer container; private Map<String, ContinuumReleaseManagerListener> listeners; /** * contains previous release:prepare descriptors; one per project * * @todo remove static when singleton strategy is working */ private static Map<String, ReleaseDescriptor> preparedReleases; /** * contains results * * @todo remove static when singleton strategy is working */ private static Map releaseResults; public String prepare( Project project, Properties releaseProperties, Map<String, String> relVersions, Map<String, String> devVersions, ContinuumReleaseManagerListener listener, String workingDirectory ) throws ContinuumReleaseException { return prepare( project, releaseProperties, relVersions, devVersions, listener, workingDirectory, null, null ); } public String prepare( Project project, Properties releaseProperties, Map<String, String> relVersions, Map<String, String> devVersions, ContinuumReleaseManagerListener listener, String workingDirectory, Map<String, String> environments, String executable ) throws ContinuumReleaseException { String releaseId = project.getGroupId() + ":" + project.getArtifactId(); ReleaseDescriptor descriptor = getReleaseDescriptor( project, releaseProperties, relVersions, devVersions, environments, workingDirectory, executable ); if ( listener == null ) { listener = new DefaultReleaseManagerListener(); listener.setUsername( releaseProperties.getProperty( "release-by" ) ); } // check if releaseId exists while ( getPreparedReleases().get( releaseId ) != null ) { releaseId = releaseId + ":" + String.valueOf( System.currentTimeMillis() ); } getListeners().put( releaseId, listener ); try { prepareReleaseQueue.put( new PrepareReleaseProjectTask( releaseId, descriptor, (ReleaseManagerListener) listener ) ); } catch ( TaskQueueException e ) { throw new ContinuumReleaseException( "Failed to add prepare release task in queue.", e ); } return releaseId; } public void perform( String releaseId, File buildDirectory, String goals, String arguments, boolean useReleaseProfile, ContinuumReleaseManagerListener listener ) throws ContinuumReleaseException { perform( releaseId, buildDirectory, goals, arguments, useReleaseProfile, listener, null ); } public void perform( String releaseId, File buildDirectory, String goals, String arguments, boolean useReleaseProfile, ContinuumReleaseManagerListener listener, LocalRepository repository ) throws ContinuumReleaseException { ReleaseDescriptor descriptor = getPreparedReleases().get( releaseId ); if ( descriptor != null ) { perform( releaseId, descriptor, buildDirectory, goals, arguments, useReleaseProfile, listener, repository ); } } public void perform( String releaseId, String workingDirectory, File buildDirectory, String goals, String arguments, boolean useReleaseProfile, ContinuumReleaseManagerListener listener ) throws ContinuumReleaseException { ReleaseDescriptor descriptor = readReleaseDescriptor( workingDirectory ); perform( releaseId, descriptor, buildDirectory, goals, arguments, useReleaseProfile, listener, null ); } private void perform( String releaseId, ReleaseDescriptor descriptor, File buildDirectory, String goals, String arguments, boolean useReleaseProfile, ContinuumReleaseManagerListener listener, LocalRepository repository ) throws ContinuumReleaseException { if ( descriptor != null ) { descriptor.setAdditionalArguments( arguments ); } if ( listener == null ) { listener = new DefaultReleaseManagerListener(); if ( descriptor instanceof ContinuumReleaseDescriptor ) { listener.setUsername( ( (ContinuumReleaseDescriptor) descriptor ).getReleaseBy() ); } } try { getListeners().put( releaseId, listener ); performReleaseQueue.put( new PerformReleaseProjectTask( releaseId, descriptor, buildDirectory, goals, useReleaseProfile, (ReleaseManagerListener) listener, repository ) ); } catch ( TaskQueueException e ) { throw new ContinuumReleaseException( "Failed to add perform release task in queue.", e ); } } public void rollback( String releaseId, String workingDirectory, ContinuumReleaseManagerListener listener ) throws ContinuumReleaseException { ReleaseDescriptor descriptor = readReleaseDescriptor( workingDirectory ); if ( listener == null ) { listener = new DefaultReleaseManagerListener(); if ( descriptor instanceof ContinuumReleaseDescriptor ) { listener.setUsername( ( (ContinuumReleaseDescriptor) descriptor ).getReleaseBy() ); } } rollback( releaseId, descriptor, listener ); } private void rollback( String releaseId, ReleaseDescriptor descriptor, ContinuumReleaseManagerListener listener ) throws ContinuumReleaseException { Task releaseTask = new RollbackReleaseProjectTask( releaseId, descriptor, (ReleaseManagerListener) listener ); try { rollbackReleaseQueue.put( releaseTask ); } catch ( TaskQueueException e ) { throw new ContinuumReleaseException( "Failed to rollback release.", e ); } } public Map<String, ReleaseDescriptor> getPreparedReleases() { if ( preparedReleases == null ) { preparedReleases = Collections.synchronizedMap( new LinkedHashMap<String, ReleaseDescriptor>() ); } return preparedReleases; } public Map<String, String> getPreparedReleasesForProject( String groupId, String artifactId ) { String key = ArtifactUtils.versionlessKey( groupId, artifactId ); Map<String, String> projectPreparedReleases = new LinkedHashMap<String, String>(); Map<String, ReleaseDescriptor> preparedReleases = getPreparedReleases(); for ( String releaseId : preparedReleases.keySet() ) { // get exact match, or one with a timestamp appended if ( releaseId.equals( key ) || releaseId.startsWith( key + ":" ) ) { ReleaseDescriptor descriptor = preparedReleases.get( releaseId ); // use key to lookup, not release ID - versions don't get any timestamp appended projectPreparedReleases.put( releaseId, descriptor.getReleaseVersions().get( key ).toString() ); } } return projectPreparedReleases; } public Map getReleaseResults() { if ( releaseResults == null ) { releaseResults = new Hashtable(); } return releaseResults; } private ReleaseDescriptor getReleaseDescriptor( Project project, Properties releaseProperties, Map<String, String> relVersions, Map<String, String> devVersions, Map<String, String> environments, String workingDirectory, String executable ) { ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); //release properties from the project descriptor.setWorkingDirectory( workingDirectory ); descriptor.setScmSourceUrl( project.getScmUrl() ); //required properties descriptor.setScmReleaseLabel( releaseProperties.getProperty( "scm-tag" ) ); descriptor.setScmTagBase( releaseProperties.getProperty( "scm-tagbase" ) ); descriptor.setReleaseVersions( relVersions ); descriptor.setDevelopmentVersions( devVersions ); descriptor.setPreparationGoals( releaseProperties.getProperty( "preparation-goals" ) ); descriptor.setAdditionalArguments( releaseProperties.getProperty( "arguments" ) ); descriptor.setAddSchema( Boolean.valueOf( releaseProperties.getProperty( "add-schema" ) ) ); descriptor.setAutoVersionSubmodules( Boolean.valueOf( releaseProperties.getProperty( "auto-version-submodules" ) ) ); String useEditMode = releaseProperties.getProperty( "use-edit-mode" ); if ( BooleanUtils.toBoolean( useEditMode ) ) { descriptor.setScmUseEditMode( Boolean.valueOf( useEditMode ) ); } LocalRepository repository = project.getProjectGroup().getLocalRepository(); if ( repository != null ) { String args = descriptor.getAdditionalArguments(); if ( StringUtils.isNotEmpty( args ) ) { descriptor.setAdditionalArguments( args + " \"-Dmaven.repo.local=" + repository.getLocation() + "\"" ); } else { descriptor.setAdditionalArguments( "\"-Dmaven.repo.local=" + repository.getLocation() + "\"" ); } } //other properties if ( releaseProperties.containsKey( "scm-username" ) ) { descriptor.setScmUsername( releaseProperties.getProperty( "scm-username" ) ); } if ( releaseProperties.containsKey( "scm-password" ) ) { descriptor.setScmPassword( releaseProperties.getProperty( "scm-password" ) ); } if ( releaseProperties.containsKey( "scm-comment-prefix" ) ) { descriptor.setScmCommentPrefix( releaseProperties.getProperty( "scm-comment-prefix" ) ); } if ( releaseProperties.containsKey( "use-release-profile" ) ) { descriptor.setUseReleaseProfile( Boolean.valueOf( releaseProperties.getProperty( "use-release-profile" ) ) ); } //forced properties descriptor.setInteractive( false ); //set environments descriptor.setEnvironments( environments ); descriptor.setExecutable( executable ); //release by descriptor.setReleaseBy( releaseProperties.getProperty( "release-by" ) ); return descriptor; } private ReleaseDescriptor readReleaseDescriptor( String workingDirectory ) throws ContinuumReleaseException { ReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setWorkingDirectory( workingDirectory ); try { descriptor = releaseStore.read( descriptor ); } catch ( ReleaseDescriptorStoreException e ) { throw new ContinuumReleaseException( "Failed to parse descriptor file.", e ); } return descriptor; } public Map<String, ContinuumReleaseManagerListener> getListeners() { if ( listeners == null ) { listeners = new Hashtable<String, ContinuumReleaseManagerListener>(); } return listeners; } public String sanitizeTagName( String scmUrl, String tagName ) throws Exception { ScmRepository scmRepo = scmManager.makeScmRepository( scmUrl ); ScmProvider scmProvider = scmManager.getProviderByRepository( scmRepo ); return scmProvider.sanitizeTagName( tagName ); } public ReleaseListenerSummary getListener( String releaseId ) { ContinuumReleaseManagerListener listener = (ContinuumReleaseManagerListener) getListeners().get( releaseId ); if ( listener != null ) { ReleaseListenerSummary listenerSummary = new ReleaseListenerSummary(); listenerSummary.setGoalName( listener.getGoalName() ); listenerSummary.setError( listener.getError() ); listenerSummary.setInProgress( listener.getInProgress() ); listenerSummary.setState( listener.getState() ); listenerSummary.setPhases( listener.getPhases() ); listenerSummary.setCompletedPhases( listener.getCompletedPhases() ); listenerSummary.setUsername( listener.getUsername() ); return listenerSummary; } return null; } public boolean isExecutingRelease() throws Exception { return prepareReleaseQueue.getQueueSnapshot().size() > 0 || performReleaseQueue.getQueueSnapshot().size() > 0 || rollbackReleaseQueue.getQueueSnapshot().size() > 0 || getPerformReleaseTaskQueueExecutor().getCurrentTask() != null || getPrepareReleaseTaskQueueExecutor().getCurrentTask() != null || getRollbackReleaseTaskQueueExecutor().getCurrentTask() != null; } public TaskQueueExecutor getPerformReleaseTaskQueueExecutor() throws TaskQueueManagerException { try { return (TaskQueueExecutor) container.lookup( TaskQueueExecutor.class, PLEXUS_KEY_PERFORM_RELEASE_TASKQUEUE_EXECUTOR ); } catch ( ComponentLookupException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } } public TaskQueueExecutor getPrepareReleaseTaskQueueExecutor() throws TaskQueueManagerException { try { return (TaskQueueExecutor) container.lookup( TaskQueueExecutor.class, PLEXUS_KEY_PREPARE_RELEASE_TASKQUEUE_EXECUTOR ); } catch ( ComponentLookupException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } } public TaskQueueExecutor getRollbackReleaseTaskQueueExecutor() throws TaskQueueManagerException { try { return (TaskQueueExecutor) container.lookup( TaskQueueExecutor.class, PLEXUS_KEY_ROLLBACK_RELEASE_TASKQUEUE_EXECUTOR ); } catch ( ComponentLookupException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
5,403
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/phase/GenerateReactorProjectsPhase.java
package org.apache.maven.continuum.release.phase; /* * 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.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; 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.release.ContinuumReleaseException; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.apache.maven.project.DuplicateProjectException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.MissingProjectException; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectSorter; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Settings; import org.apache.maven.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.ReleaseFailureException; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.ReleaseEnvironment; import org.apache.maven.shared.release.phase.AbstractReleasePhase; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; 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.dag.CycleDetectedException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; /** * Generate the reactor projects * * @author Edwin Punzalan */ public class GenerateReactorProjectsPhase extends AbstractReleasePhase implements Contextualizable { private MavenProjectBuilder projectBuilder; private MavenSettingsBuilder settingsBuilder; private PlexusContainer container; private static final char SET_SYSTEM_PROPERTY = 'D'; private static final char ACTIVATE_PROFILES = 'P'; public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, Settings settings, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { ReleaseResult result = new ReleaseResult(); try { reactorProjects.addAll( getReactorProjects( releaseDescriptor ) ); } catch ( ContinuumReleaseException e ) { throw new ReleaseExecutionException( "Unable to get reactor projects: " + e.getMessage(), e ); } result.setResultCode( ReleaseResult.SUCCESS ); return result; } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, Settings settings, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, settings, reactorProjects ); } public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, releaseEnvironment.getSettings(), reactorProjects ); } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, releaseEnvironment.getSettings(), reactorProjects ); } private List getReactorProjects( ReleaseDescriptor descriptor ) throws ContinuumReleaseException { List<MavenProject> reactorProjects = new ArrayList<MavenProject>(); MavenProject project; try { String arguments = descriptor.getAdditionalArguments(); ArtifactRepository repository = getLocalRepository( arguments ); ProfileManager profileManager = getProfileManager( getSettings() ); if ( arguments != null ) { activateProfiles( arguments, profileManager ); } project = projectBuilder.build( getProjectDescriptorFile( descriptor ), repository, profileManager ); reactorProjects.add( project ); addModules( reactorProjects, project, repository ); } catch ( ParseException e ) { throw new ContinuumReleaseException( "Unable to parse arguments.", e ); } catch ( ProjectBuildingException e ) { throw new ContinuumReleaseException( "Failed to build project.", e ); } try { reactorProjects = new ProjectSorter( reactorProjects ).getSortedProjects(); } catch ( CycleDetectedException e ) { throw new ContinuumReleaseException( "Failed to sort projects.", e ); } catch ( DuplicateProjectException e ) { throw new ContinuumReleaseException( "Failed to sort projects.", e ); } catch ( MissingProjectException e ) { throw new ContinuumReleaseException( "Failed to sort projects.", e ); } return reactorProjects; } private void addModules( List<MavenProject> reactorProjects, MavenProject project, ArtifactRepository repository ) throws ContinuumReleaseException { for ( Object o : project.getModules() ) { String moduleDir = StringUtils.replace( o.toString(), '\\', '/' ); File pomFile = new File( project.getBasedir(), moduleDir + "/pom.xml" ); try { MavenProject reactorProject = projectBuilder.build( pomFile, repository, getProfileManager( getSettings() ) ); reactorProjects.add( reactorProject ); addModules( reactorProjects, reactorProject, repository ); } catch ( ProjectBuildingException e ) { throw new ContinuumReleaseException( "Failed to build project.", e ); } } } private File getProjectDescriptorFile( ReleaseDescriptor descriptor ) { String parentPath = descriptor.getWorkingDirectory(); String pomFilename = descriptor.getPomFileName(); if ( pomFilename == null ) { pomFilename = "pom.xml"; } return new File( parentPath, pomFilename ); } private ArtifactRepository getLocalRepository( String arguments ) throws ContinuumReleaseException { String localRepository = null; boolean found = false; if ( arguments != null ) { String[] args = arguments.split( " " ); for ( String arg : args ) { if ( arg.contains( "-Dmaven.repo.local=" ) ) { localRepository = arg.substring( arg.indexOf( "=" ) + 1 ); if ( localRepository.endsWith( "\"" ) ) { localRepository = localRepository.substring( 0, localRepository.indexOf( "\"" ) ); break; } found = true; continue; } if ( found ) { localRepository += " " + arg; if ( localRepository.endsWith( "\"" ) ) { localRepository = localRepository.substring( 0, localRepository.indexOf( "\"" ) ); break; } } } } if ( localRepository == null ) { localRepository = getSettings().getLocalRepository(); } return new DefaultArtifactRepository( "local-repository", "file://" + localRepository, new DefaultRepositoryLayout() ); } private ProfileManager getProfileManager( Settings settings ) { Properties props = new Properties(); return new DefaultProfileManager( container, settings, props ); } private Settings getSettings() throws ContinuumReleaseException { try { return settingsBuilder.buildSettings(); } catch ( IOException e ) { throw new ContinuumReleaseException( "Failed to get Maven Settings.", e ); } catch ( XmlPullParserException e ) { throw new ContinuumReleaseException( "Failed to get Maven Settings.", e ); } } @SuppressWarnings( "static-access" ) private void activateProfiles( String arguments, ProfileManager profileManager ) throws ParseException { CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption( OptionBuilder.withLongOpt( "activate-profiles" ).withDescription( "Comma-delimited list of profiles to activate" ).hasArg().create( ACTIVATE_PROFILES ) ); options.addOption( OptionBuilder.withLongOpt( "define" ).hasArg().withDescription( "Define a system property" ).create( SET_SYSTEM_PROPERTY ) ); String[] args = StringUtils.split( arguments ); CommandLine commandLine = parser.parse( options, args ); if ( commandLine.hasOption( ACTIVATE_PROFILES ) ) { String[] profileOptionValues = commandLine.getOptionValues( ACTIVATE_PROFILES ); if ( profileOptionValues != null ) { for ( int i = 0; i < profileOptionValues.length; ++i ) { StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i], "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) || profileAction.startsWith( "!" ) ) { profileManager.explicitlyDeactivate( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "+" ) ) { profileManager.explicitlyActivate( profileAction.substring( 1 ) ); } else { profileManager.explicitlyActivate( profileAction ); } } } } } } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
5,404
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/phase/UpdateWorkingCopyPhase.java
package org.apache.maven.continuum.release.phase; /* * 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.StringUtils; import org.apache.continuum.scm.ContinuumScmUtils; import org.apache.maven.scm.ScmBranch; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.ScmVersion; import org.apache.maven.scm.command.checkout.CheckOutScmResult; import org.apache.maven.scm.command.update.UpdateScmResult; import org.apache.maven.scm.manager.NoSuchScmProviderException; import org.apache.maven.scm.manager.plexus.PlexusLogger; import org.apache.maven.scm.provider.ScmProvider; import org.apache.maven.scm.provider.ScmProviderRepository; import org.apache.maven.scm.provider.ScmUrlUtils; import org.apache.maven.scm.provider.git.gitexe.command.branch.GitBranchCommand; import org.apache.maven.scm.provider.git.repository.GitScmProviderRepository; import org.apache.maven.scm.repository.ScmRepository; import org.apache.maven.scm.repository.ScmRepositoryException; import org.apache.maven.settings.Settings; import org.apache.maven.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.ReleaseFailureException; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.ReleaseEnvironment; import org.apache.maven.shared.release.phase.AbstractReleasePhase; import org.apache.maven.shared.release.scm.ReleaseScmCommandException; import org.apache.maven.shared.release.scm.ReleaseScmRepositoryException; import org.apache.maven.shared.release.scm.ScmRepositoryConfigurator; import java.io.File; import java.util.List; /** * Update working copy * * @author Edwin Punzalan */ public class UpdateWorkingCopyPhase extends AbstractReleasePhase { /** * Tool that gets a configured SCM repository from release configuration. */ private ScmRepositoryConfigurator scmRepositoryConfigurator; private boolean copyUpdated = false; public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, Settings settings, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { ReleaseResult relResult = new ReleaseResult(); logInfo( relResult, "Updating local copy against the scm..." ); ScmRepository repository; ScmProvider provider; // CONTINUUM-2628 // if git ssh, use credentials specified in scm url if present. otherwise, use the scm credentials of project String providerType = ScmUrlUtils.getProvider( releaseDescriptor.getScmSourceUrl() ); String scmSpecificUrl = releaseDescriptor.getScmSourceUrl().substring( providerType.length() + 5 ); if ( providerType.contains( ContinuumScmUtils.GIT_SCM_PROVIDERTYPE ) && scmSpecificUrl.startsWith( GitScmProviderRepository.PROTOCOL_SSH ) ) { scmSpecificUrl = scmSpecificUrl.substring( GitScmProviderRepository.PROTOCOL_SSH.length() + 3 ); // extract user information int indexAt = scmSpecificUrl.indexOf( "@" ); String sshScmUsername = ""; String sshScmPassword = ""; if ( indexAt >= 0 ) { String userInfo = scmSpecificUrl.substring( 0, indexAt ); sshScmUsername = userInfo; int indexPwdSep = userInfo.indexOf( ":" ); // password is specified in the url if ( indexPwdSep < 0 ) { sshScmUsername = userInfo.substring( indexPwdSep + 1 ); } else { sshScmUsername = userInfo.substring( 0, indexPwdSep ); sshScmPassword = userInfo.substring( indexPwdSep + 1 ); } } if ( !StringUtils.isBlank( sshScmUsername ) ) { releaseDescriptor.setScmUsername( sshScmUsername ); if ( !StringUtils.isBlank( sshScmPassword ) ) { releaseDescriptor.setScmPassword( sshScmPassword ); } else { releaseDescriptor.setScmPassword( null ); } } } try { repository = scmRepositoryConfigurator.getConfiguredRepository( releaseDescriptor, settings ); provider = scmRepositoryConfigurator.getRepositoryProvider( repository ); } catch ( ScmRepositoryException e ) { throw new ReleaseScmRepositoryException( e.getMessage() + " for URL: " + releaseDescriptor.getScmSourceUrl(), e.getValidationMessages() ); } catch ( NoSuchScmProviderException e ) { throw new ReleaseExecutionException( "Unable to configure SCM repository: " + e.getMessage(), e ); } UpdateScmResult updateScmResult = null; CheckOutScmResult checkOutScmResult = null; File workingDirectory = new File( releaseDescriptor.getWorkingDirectory() ); ScmFileSet workingDirSet = new ScmFileSet( workingDirectory ); try { if ( !workingDirectory.exists() ) { workingDirectory.mkdirs(); } ScmVersion scmTag = null; ScmProviderRepository providerRepo = repository.getProviderRepository(); // FIXME: This should be handled by the maven-scm git provider if ( providerRepo instanceof GitScmProviderRepository ) { String branchName = GitBranchCommand.getCurrentBranch( new PlexusLogger( getLogger() ), (GitScmProviderRepository) providerRepo, workingDirSet ); scmTag = new ScmBranch( branchName ); } if ( workingDirectory.listFiles().length > 1 ) { updateScmResult = provider.update( repository, workingDirSet, scmTag ); } else { checkOutScmResult = provider.checkOut( repository, new ScmFileSet( workingDirectory ) ); checkOutScmResult = provider.checkOut( repository, workingDirSet, scmTag ); } } catch ( ScmException e ) { throw new ReleaseExecutionException( "An error occurred while updating your local copy: " + e.getMessage(), e ); } if ( updateScmResult != null ) { if ( !updateScmResult.isSuccess() ) { throw new ReleaseScmCommandException( "Unable to update current working copy", updateScmResult ); } copyUpdated = updateScmResult.getUpdatedFiles().size() > 0; } else { if ( !checkOutScmResult.isSuccess() ) { throw new ReleaseScmCommandException( "Unable to checkout project", checkOutScmResult ); } copyUpdated = checkOutScmResult.getCheckedOutFiles().size() > 0; } relResult.setResultCode( ReleaseResult.SUCCESS ); return relResult; } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, Settings settings, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, settings, reactorProjects ); } public boolean isCopyUpdated() { return copyUpdated; } public void setCopyUpdated( boolean copyUpdated ) { this.copyUpdated = copyUpdated; } public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, releaseEnvironment.getSettings(), reactorProjects ); } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, releaseEnvironment.getSettings(), reactorProjects ); } }
5,405
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/tasks/AbstractReleaseProjectTask.java
package org.apache.maven.continuum.release.tasks; /* * 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.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.codehaus.plexus.taskqueue.Task; /** * @author Edwin Punzalan */ public abstract class AbstractReleaseProjectTask implements Task, ReleaseProjectTask { private String releaseId; private ReleaseDescriptor descriptor; private ReleaseManagerListener listener; private long maxExecutionTime; public AbstractReleaseProjectTask( String releaseId, ReleaseDescriptor descriptor, ReleaseManagerListener listener ) { this.releaseId = releaseId; this.descriptor = descriptor; this.listener = listener; } public ReleaseDescriptor getDescriptor() { return descriptor; } public void setDescriptor( ReleaseDescriptor descriptor ) { this.descriptor = descriptor; } public String getReleaseId() { return releaseId; } public void setReleaseId( String releaseId ) { this.releaseId = releaseId; } public ReleaseManagerListener getListener() { return listener; } public void setListener( ReleaseManagerListener listener ) { this.listener = listener; } public long getMaxExecutionTime() { return maxExecutionTime; } public void setMaxExecutionTime( long maxTime ) { this.maxExecutionTime = maxTime; } }
5,406
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/tasks/PerformReleaseProjectTask.java
package org.apache.maven.continuum.release.tasks; /* * 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.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.config.ReleaseDescriptor; import java.io.File; /** * @author Edwin Punzalan */ public class PerformReleaseProjectTask extends AbstractReleaseProjectTask { private File buildDirectory; private String goals; private boolean useReleaseProfile = true; private LocalRepository localRepository; public PerformReleaseProjectTask( String releaseId, ReleaseDescriptor descriptor, File buildDirectory, String goals, boolean useReleaseProfile, ReleaseManagerListener listener ) { this( releaseId, descriptor, buildDirectory, goals, useReleaseProfile, listener, null ); } public PerformReleaseProjectTask( String releaseId, ReleaseDescriptor descriptor, File buildDirectory, String goals, boolean useReleaseProfile, ReleaseManagerListener listener, LocalRepository repository ) { super( releaseId, descriptor, listener ); setBuildDirectory( buildDirectory ); setGoals( goals ); setUseReleaseProfile( useReleaseProfile ); setLocalRepository( repository ); } public String getGoals() { return goals; } public void setGoals( String goals ) { this.goals = goals; } public boolean isUseReleaseProfile() { return useReleaseProfile; } public void setUseReleaseProfile( boolean useReleaseProfile ) { this.useReleaseProfile = useReleaseProfile; } public File getBuildDirectory() { return buildDirectory; } public void setBuildDirectory( File buildDirectory ) { this.buildDirectory = buildDirectory; } public LocalRepository getLocalRepository() { return localRepository; } public void setLocalRepository( LocalRepository localRepository ) { this.localRepository = localRepository; } }
5,407
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/tasks/RollbackReleaseProjectTask.java
package org.apache.maven.continuum.release.tasks; import org.apache.maven.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.config.ReleaseDescriptor; /* * 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 Edwin Punzalan */ public class RollbackReleaseProjectTask extends AbstractReleaseProjectTask { public RollbackReleaseProjectTask( String releaseId, ReleaseDescriptor descriptor, ReleaseManagerListener listener ) { super( releaseId, descriptor, listener ); } }
5,408
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/tasks/PrepareReleaseProjectTask.java
package org.apache.maven.continuum.release.tasks; /* * 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.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.config.ReleaseDescriptor; /** * @author Edwin Punzalan */ public class PrepareReleaseProjectTask extends AbstractReleaseProjectTask { public PrepareReleaseProjectTask( String releaseId, ReleaseDescriptor descriptor, ReleaseManagerListener listener ) { super( releaseId, descriptor, listener ); } }
5,409
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/tasks/ReleaseProjectTask.java
package org.apache.maven.continuum.release.tasks; /* * 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.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.config.ReleaseDescriptor; /** * @author Edwin Punzalan */ public interface ReleaseProjectTask { public void setDescriptor( ReleaseDescriptor descriptor ); public ReleaseDescriptor getDescriptor(); public void setReleaseId( String releaseId ); public String getReleaseId(); public void setListener( ReleaseManagerListener listener ); public ReleaseManagerListener getListener(); }
5,410
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/executors/ReleaseTaskExecutor.java
package org.apache.maven.continuum.release.executors; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.taskqueue.execution.TaskExecutor; /** * @author Edwin Punzalan */ public interface ReleaseTaskExecutor extends TaskExecutor { String ROLE = TaskExecutor.class.getName(); }
5,411
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/executors/PrepareReleaseTaskExecutor.java
package org.apache.maven.continuum.release.executors; /* * 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.tasks.PrepareReleaseProjectTask; import org.apache.maven.continuum.release.tasks.ReleaseProjectTask; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.DefaultReleaseEnvironment; import org.apache.maven.shared.release.env.ReleaseEnvironment; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import java.util.ArrayList; /** * @author Edwin Punzalan */ public class PrepareReleaseTaskExecutor extends AbstractReleaseTaskExecutor { protected void execute( ReleaseProjectTask task ) throws TaskExecutionException { PrepareReleaseProjectTask prepareTask = (PrepareReleaseProjectTask) task; ReleaseDescriptor descriptor = prepareTask.getDescriptor(); ReleaseEnvironment releaseEnvironment = new DefaultReleaseEnvironment(); releaseEnvironment.setSettings( settings ); ReleaseResult result = releaseManager.prepareWithResult( descriptor, releaseEnvironment, new ArrayList(), false, false, prepareTask.getListener() ); //override to show the actual start time result.setStartTime( getStartTime() ); if ( result.getResultCode() == ReleaseResult.SUCCESS ) { continuumReleaseManager.getPreparedReleases().put( prepareTask.getReleaseId(), descriptor ); } continuumReleaseManager.getReleaseResults().put( prepareTask.getReleaseId(), result ); } }
5,412
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/executors/RollbackReleaseTaskExecutor.java
package org.apache.maven.continuum.release.executors; /* * 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.tasks.ReleaseProjectTask; import org.apache.maven.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.ReleaseFailureException; import org.apache.maven.shared.release.ReleaseManagerListener; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import java.util.ArrayList; /** * @author Edwin Punzalan */ public class RollbackReleaseTaskExecutor extends AbstractReleaseTaskExecutor { protected void execute( ReleaseProjectTask releaseTask ) throws TaskExecutionException { try { releaseManager.rollback( releaseTask.getDescriptor(), settings, new ArrayList(), releaseTask.getListener() ); } catch ( ReleaseExecutionException e ) { updateListener( releaseTask.getListener(), e.getMessage() ); throw new TaskExecutionException( "Failed to rollback release", e ); } catch ( ReleaseFailureException e ) { updateListener( releaseTask.getListener(), e.getMessage() ); throw new TaskExecutionException( "Failed to rollback release", e ); } } private void updateListener( ReleaseManagerListener listener, String name ) { listener.error( name ); } }
5,413
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/executors/AbstractReleaseTaskExecutor.java
package org.apache.maven.continuum.release.executors; /* * 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.continuum.release.tasks.ReleaseProjectTask; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Settings; import org.apache.maven.shared.release.ReleaseManager; import org.apache.maven.shared.release.ReleaseResult; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.IOException; /** * @author Edwin Punzalan */ public abstract class AbstractReleaseTaskExecutor implements ReleaseTaskExecutor { @Requirement protected ContinuumReleaseManager continuumReleaseManager; @Requirement protected ReleaseManager releaseManager; @Requirement private MavenSettingsBuilder settingsBuilder; protected Settings settings; private long startTime; public void executeTask( Task task ) throws TaskExecutionException { ReleaseProjectTask releaseTask = (ReleaseProjectTask) task; setUp( releaseTask ); execute( releaseTask ); } protected void setUp( ReleaseProjectTask releaseTask ) throws TaskExecutionException { //actual release execution start time setStartTime( System.currentTimeMillis() ); try { //make sure settings is re-read each time settings = getSettings(); } catch ( ContinuumReleaseException e ) { ReleaseResult result = createReleaseResult(); result.appendError( e ); continuumReleaseManager.getReleaseResults().put( releaseTask.getReleaseId(), result ); releaseTask.getListener().error( e.getMessage() ); throw new TaskExecutionException( "Failed to build reactor projects.", e ); } } protected abstract void execute( ReleaseProjectTask releaseTask ) throws TaskExecutionException; private Settings getSettings() throws ContinuumReleaseException { try { settings = settingsBuilder.buildSettings( false ); } catch ( IOException e ) { throw new ContinuumReleaseException( "Failed to get Maven Settings.", e ); } catch ( XmlPullParserException e ) { throw new ContinuumReleaseException( "Failed to get Maven Settings.", e ); } return settings; } protected ReleaseResult createReleaseResult() { ReleaseResult result = new ReleaseResult(); result.setStartTime( getStartTime() ); result.setEndTime( System.currentTimeMillis() ); return result; } protected long getStartTime() { return startTime; } protected void setStartTime( long startTime ) { this.startTime = startTime; } }
5,414
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/maven/continuum/release/executors/PerformReleaseTaskExecutor.java
package org.apache.maven.continuum.release.executors; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.LocalRepository; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.DefaultArtifactRepository; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.continuum.release.ContinuumReleaseException; import org.apache.maven.continuum.release.tasks.PerformReleaseProjectTask; import org.apache.maven.continuum.release.tasks.ReleaseProjectTask; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.apache.maven.project.DuplicateProjectException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.MissingProjectException; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectSorter; import org.apache.maven.settings.Settings; import org.apache.maven.shared.release.ReleaseManagerListener; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.DefaultReleaseEnvironment; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.dag.CycleDetectedException; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Edwin Punzalan */ public class PerformReleaseTaskExecutor extends AbstractReleaseTaskExecutor implements Contextualizable { @Requirement private MavenProjectBuilder projectBuilder; private ProfileManager profileManager; private PlexusContainer container; private LocalRepository repository; public void execute( ReleaseProjectTask task ) throws TaskExecutionException { PerformReleaseProjectTask performTask = (PerformReleaseProjectTask) task; ReleaseManagerListener listener = performTask.getListener(); ReleaseDescriptor descriptor = performTask.getDescriptor(); descriptor.setUseReleaseProfile( performTask.isUseReleaseProfile() ); descriptor.setPerformGoals( performTask.getGoals() ); descriptor.setCheckoutDirectory( performTask.getBuildDirectory().getAbsolutePath() ); repository = performTask.getLocalRepository(); List reactorProjects; try { if ( !StringUtils.isEmpty( descriptor.getWorkingDirectory() ) ) { MavenProject mavenProject = getMavenProject( performTask ); reactorProjects = getReactorProjects( descriptor, mavenProject ); } else { //Perform with provided release parameters (CONTINUUM-1541) descriptor.setCheckoutDirectory( performTask.getBuildDirectory().getAbsolutePath() ); // Workaround bugs in maven-release-manager 2.1 that require a project even though it will ultimately // not be used. TODO: check if upgrading will fix, and return to being an empty list // The project is fake and won't exist in this location MavenProject project = new MavenProject(); project.setFile( new File( descriptor.getCheckoutDirectory(), "pom.xml" ) ); reactorProjects = Collections.singletonList( project ); // reactorProjects = Collections.emptyList(); } } catch ( ContinuumReleaseException e ) { ReleaseResult result = createReleaseResult(); result.appendError( e ); continuumReleaseManager.getReleaseResults().put( performTask.getReleaseId(), result ); performTask.getListener().error( e.getMessage() ); throw new TaskExecutionException( "Failed to build reactor projects.", e ); } ReleaseResult result = releaseManager.performWithResult( descriptor, new DefaultReleaseEnvironment().setSettings( settings ), reactorProjects, listener ); //override to show the actual start time result.setStartTime( getStartTime() ); if ( result.getResultCode() == ReleaseResult.SUCCESS ) { continuumReleaseManager.getPreparedReleases().remove( performTask.getReleaseId() ); } continuumReleaseManager.getReleaseResults().put( performTask.getReleaseId(), result ); } /** * @todo remove and use generate-reactor-projects phase */ protected List<MavenProject> getReactorProjects( ReleaseDescriptor descriptor, MavenProject project ) throws ContinuumReleaseException { List<MavenProject> reactorProjects = new ArrayList<MavenProject>(); reactorProjects.add( project ); addModules( reactorProjects, project ); try { reactorProjects = new ProjectSorter( reactorProjects ).getSortedProjects(); } catch ( CycleDetectedException e ) { throw new ContinuumReleaseException( "Failed to sort projects.", e ); } catch ( DuplicateProjectException e ) { throw new ContinuumReleaseException( "Failed to sort projects.", e ); } catch ( MissingProjectException e ) { throw new ContinuumReleaseException( "Failed to sort projects.", e ); } return reactorProjects; } private void addModules( List<MavenProject> reactorProjects, MavenProject project ) throws ContinuumReleaseException { for ( Object o : project.getModules() ) { String moduleDir = o.toString(); File pomFile = new File( project.getBasedir(), moduleDir + "/pom.xml" ); try { MavenProject reactorProject = projectBuilder.build( pomFile, getLocalRepository(), getProfileManager( settings ) ); reactorProjects.add( reactorProject ); addModules( reactorProjects, reactorProject ); } catch ( ProjectBuildingException e ) { throw new ContinuumReleaseException( "Failed to build project.", e ); } } } private File getProjectDescriptorFile( ReleaseDescriptor descriptor ) { String parentPath = descriptor.getWorkingDirectory(); String pomFilename = descriptor.getPomFileName(); if ( pomFilename == null ) { pomFilename = "pom.xml"; } return new File( parentPath, pomFilename ); } private ArtifactRepository getLocalRepository() { if ( repository == null ) { return new DefaultArtifactRepository( "local-repository", "file://" + settings.getLocalRepository(), new DefaultRepositoryLayout() ); } else { return new DefaultArtifactRepository( repository.getName(), "file://" + repository.getLocation(), new DefaultRepositoryLayout() ); } } private ProfileManager getProfileManager( Settings settings ) { if ( profileManager == null ) { profileManager = new DefaultProfileManager( container, settings ); } return profileManager; } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } protected MavenProject getMavenProject( PerformReleaseProjectTask releaseTask ) throws ContinuumReleaseException { ReleaseDescriptor descriptor = releaseTask.getDescriptor(); MavenProject project; try { project = projectBuilder.build( getProjectDescriptorFile( descriptor ), getLocalRepository(), getProfileManager( settings ) ); } catch ( ProjectBuildingException e ) { throw new ContinuumReleaseException( "Failed to build project.", e ); } return project; } }
5,415
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/phase/RunPrepareGoalsPhase.java
package org.apache.continuum.release.phase; /* * 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.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.ReleaseFailureException; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.ReleaseEnvironment; import org.codehaus.plexus.component.annotations.Component; import java.io.File; import java.util.List; /** * Run Release Preparation Goals */ @Component( role = org.apache.maven.shared.release.phase.ReleasePhase.class, hint = "run-release-prepare-goals" ) public class RunPrepareGoalsPhase extends AbstractContinuumRunGoalsPhase { @Override protected String getGoals( ReleaseDescriptor releaseDescriptor ) { return releaseDescriptor.getPreparationGoals(); } public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, new File( releaseDescriptor.getWorkingDirectory() ), releaseDescriptor.getAdditionalArguments() ); } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { ReleaseResult result = new ReleaseResult(); logInfo( result, "Executing preparation goals - since this is simulation mode it is running against the " + "original project, not the rewritten ones" ); execute( releaseDescriptor, releaseEnvironment, reactorProjects ); return result; } }
5,416
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/phase/RunPerformGoalsPhase.java
package org.apache.continuum.release.phase; /* * 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.settings.Settings; import org.apache.maven.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.ReleaseFailureException; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.ReleaseEnvironment; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.List; /** * Run Release Perform Goals */ @Component( role = org.apache.maven.shared.release.phase.ReleasePhase.class, hint = "run-release-perform-goals" ) public class RunPerformGoalsPhase extends AbstractContinuumRunGoalsPhase { @Override protected String getGoals( ReleaseDescriptor releaseDescriptor ) { return releaseDescriptor.getPerformGoals(); } public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { String additionalArguments = releaseDescriptor.getAdditionalArguments(); if ( releaseDescriptor.isUseReleaseProfile() ) { if ( !StringUtils.isEmpty( additionalArguments ) ) { additionalArguments = additionalArguments + " -DperformRelease=true"; } else { additionalArguments = "-DperformRelease=true"; } } return execute( releaseDescriptor, new File( releaseDescriptor.getCheckoutDirectory() ), additionalArguments ); } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, Settings settings, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { ReleaseResult result = new ReleaseResult(); logInfo( result, "Executing perform goals" ); execute( releaseDescriptor, settings, reactorProjects ); return result; } }
5,417
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/phase/AbstractContinuumRunGoalsPhase.java
package org.apache.continuum.release.phase; /* * 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.release.config.ContinuumReleaseDescriptor; import org.apache.continuum.utils.shell.ShellCommandHelper; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.ReleaseFailureException; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.env.ReleaseEnvironment; import org.apache.maven.shared.release.phase.AbstractRunGoalsPhase; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.List; import java.util.Map; /** * @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a> */ public abstract class AbstractContinuumRunGoalsPhase extends AbstractRunGoalsPhase { @Requirement private ShellCommandHelper shellCommandHelper; @Requirement private InstallationService installationService; /** * TODO olamy use maven-invoker with an installation (jdk, mvn path, env var) */ public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, File workingDirectory, String additionalArguments ) throws ReleaseExecutionException { ReleaseResult result = new ReleaseResult(); try { String goals = getGoals( releaseDescriptor ); if ( !StringUtils.isEmpty( goals ) ) { Map<String, String> environments = null; String executable = null; if ( releaseDescriptor instanceof ContinuumReleaseDescriptor ) { environments = ( (ContinuumReleaseDescriptor) releaseDescriptor ).getEnvironments(); executable = ( (ContinuumReleaseDescriptor) releaseDescriptor ).getExecutable(); } shellCommandHelper.executeGoals( determineWorkingDirectory( workingDirectory, releaseDescriptor.getScmRelativePathProjectDirectory() ), executable, goals, releaseDescriptor.isInteractive(), additionalArguments, result, environments ); } } catch ( Exception e ) { throw new ReleaseExecutionException( result.getOutput(), e ); } result.setResultCode( ReleaseResult.SUCCESS ); return result; } @Override public ReleaseResult execute( ReleaseDescriptor arg0, ReleaseEnvironment arg1, File arg2, String arg3 ) throws ReleaseExecutionException { return super.execute( arg0, arg1, arg2, arg3 ); } public ReleaseResult execute( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, new File( releaseDescriptor.getWorkingDirectory() ), releaseDescriptor.getAdditionalArguments() ); } public ReleaseResult simulate( ReleaseDescriptor releaseDescriptor, ReleaseEnvironment releaseEnvironment, List reactorProjects ) throws ReleaseExecutionException, ReleaseFailureException { return execute( releaseDescriptor, new File( releaseDescriptor.getWorkingDirectory() ), releaseDescriptor.getAdditionalArguments() ); } }
5,418
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/config/ContinuumReleaseDescriptor.java
package org.apache.continuum.release.config; /* * 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.shared.release.config.ReleaseDescriptor; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a> */ public class ContinuumReleaseDescriptor extends ReleaseDescriptor { private Map<String, String> environments; private String executable; private String releaseBy; public void addEnvironment( String name, String value ) { getEnvironments().put( name, value ); } public Map<String, String> getEnvironments() { if ( environments == null ) { environments = new HashMap<String, String>(); } return environments; } public void mapEnvironments( String name, String value ) { if ( environments == null ) { environments = new HashMap<String, String>(); } else { assert !environments.containsKey( name ); } environments.put( name, value ); } public void setEnvironments( Map<String, String> environments ) { this.environments = environments; } public String getExecutable() { return executable; } public void setExecutable( String executable ) { this.executable = executable; } public String getReleaseBy() { return releaseBy; } public void setReleaseBy( String releaseBy ) { this.releaseBy = releaseBy; } }
5,419
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/config/ContinuumPropertiesReleaseDescriptorStore.java
package org.apache.continuum.release.config; /* * 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.model.Scm; import org.apache.maven.shared.release.config.PropertiesReleaseDescriptorStore; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.apache.maven.shared.release.config.ReleaseDescriptorStoreException; import org.apache.maven.shared.release.config.ReleaseUtils; import org.codehaus.plexus.util.IOUtil; import org.eclipse.jetty.util.security.Password; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; public class ContinuumPropertiesReleaseDescriptorStore extends PropertiesReleaseDescriptorStore { public ReleaseDescriptor read( ReleaseDescriptor mergeDescriptor, File file ) throws ReleaseDescriptorStoreException { Properties properties = new Properties(); InputStream inStream = null; try { inStream = new FileInputStream( file ); properties.load( inStream ); } catch ( FileNotFoundException e ) { getLogger().debug( file.getName() + " not found - using empty properties" ); } catch ( IOException e ) { throw new ReleaseDescriptorStoreException( "Error reading properties file '" + file.getName() + "': " + e.getMessage(), e ); } finally { IOUtil.close( inStream ); } ContinuumReleaseDescriptor releaseDescriptor = new ContinuumReleaseDescriptor(); releaseDescriptor.setCompletedPhase( properties.getProperty( "completedPhase" ) ); releaseDescriptor.setScmSourceUrl( properties.getProperty( "scm.url" ) ); releaseDescriptor.setScmUsername( properties.getProperty( "scm.username" ) ); String password = properties.getProperty( "scm.password" ); if ( password != null && password.startsWith( "OBF:" ) ) { releaseDescriptor.setScmPassword( Password.deobfuscate( password ) ); } else { releaseDescriptor.setScmPassword( password ); } releaseDescriptor.setScmPrivateKey( properties.getProperty( "scm.privateKey" ) ); releaseDescriptor.setScmPrivateKeyPassPhrase( properties.getProperty( "scm.passphrase" ) ); releaseDescriptor.setScmTagBase( properties.getProperty( "scm.tagBase" ) ); releaseDescriptor.setScmReleaseLabel( properties.getProperty( "scm.tag" ) ); releaseDescriptor.setScmCommentPrefix( properties.getProperty( "scm.commentPrefix" ) ); releaseDescriptor.setAdditionalArguments( properties.getProperty( "exec.additionalArguments" ) ); releaseDescriptor.setPomFileName( properties.getProperty( "exec.pomFileName" ) ); releaseDescriptor.setPreparationGoals( properties.getProperty( "preparationGoals" ) ); releaseDescriptor.setExecutable( properties.getProperty( "build.executable" ) ); releaseDescriptor.setReleaseBy( properties.getProperty( "release.by" ) ); loadResolvedDependencies( properties, releaseDescriptor ); // boolean properties are not written to the properties file because the value from the caller is always used for ( Object o : properties.keySet() ) { String property = (String) o; if ( property.startsWith( "project.rel." ) ) { releaseDescriptor.mapReleaseVersion( property.substring( "project.rel.".length() ), properties.getProperty( property ) ); } else if ( property.startsWith( "project.dev." ) ) { releaseDescriptor.mapDevelopmentVersion( property.substring( "project.dev.".length() ), properties.getProperty( property ) ); } else if ( property.startsWith( "project.scm." ) ) { int index = property.lastIndexOf( '.' ); if ( index > "project.scm.".length() ) { String key = property.substring( "project.scm.".length(), index ); if ( !releaseDescriptor.getOriginalScmInfo().containsKey( key ) ) { if ( properties.getProperty( "project.scm." + key + ".empty" ) != null ) { releaseDescriptor.mapOriginalScmInfo( key, null ); } else { Scm scm = new Scm(); scm.setConnection( properties.getProperty( "project.scm." + key + ".connection" ) ); scm.setDeveloperConnection( properties.getProperty( "project.scm." + key + ".developerConnection" ) ); scm.setUrl( properties.getProperty( "project.scm." + key + ".url" ) ); scm.setTag( properties.getProperty( "project.scm." + key + ".tag" ) ); releaseDescriptor.mapOriginalScmInfo( key, scm ); } } } } else if ( property.startsWith( "build.env." ) ) { releaseDescriptor.mapEnvironments( property.substring( "build.env.".length() ), properties.getProperty( property ) ); } } if ( mergeDescriptor != null ) { releaseDescriptor = (ContinuumReleaseDescriptor) ReleaseUtils.merge( releaseDescriptor, mergeDescriptor ); releaseDescriptor.setEnvironments( ( (ContinuumReleaseDescriptor) mergeDescriptor ).getEnvironments() ); } return releaseDescriptor; } public void write( ReleaseDescriptor configFile, File file ) throws ReleaseDescriptorStoreException { ContinuumReleaseDescriptor config = (ContinuumReleaseDescriptor) configFile; Properties properties = new Properties(); properties.setProperty( "completedPhase", config.getCompletedPhase() ); properties.setProperty( "scm.url", config.getScmSourceUrl() ); if ( config.getScmUsername() != null ) { properties.setProperty( "scm.username", config.getScmUsername() ); } if ( config.getScmPassword() != null ) { // obfuscate password properties.setProperty( "scm.password", Password.obfuscate( config.getScmPassword() ) ); } if ( config.getScmPrivateKey() != null ) { properties.setProperty( "scm.privateKey", config.getScmPrivateKey() ); } if ( config.getScmPrivateKeyPassPhrase() != null ) { properties.setProperty( "scm.passphrase", config.getScmPrivateKeyPassPhrase() ); } if ( config.getScmTagBase() != null ) { properties.setProperty( "scm.tagBase", config.getScmTagBase() ); } if ( config.getScmReleaseLabel() != null ) { properties.setProperty( "scm.tag", config.getScmReleaseLabel() ); } if ( config.getScmCommentPrefix() != null ) { properties.setProperty( "scm.commentPrefix", config.getScmCommentPrefix() ); } if ( config.getAdditionalArguments() != null ) { properties.setProperty( "exec.additionalArguments", config.getAdditionalArguments() ); } if ( config.getPomFileName() != null ) { properties.setProperty( "exec.pomFileName", config.getPomFileName() ); } if ( config.getPreparationGoals() != null ) { properties.setProperty( "preparationGoals", config.getPreparationGoals() ); } // boolean properties are not written to the properties file because the value from the caller is always used for ( Object o : config.getReleaseVersions().entrySet() ) { Entry entry = (Entry) o; properties.setProperty( "project.rel." + entry.getKey(), (String) entry.getValue() ); } for ( Object o : config.getDevelopmentVersions().entrySet() ) { Entry entry = (Entry) o; properties.setProperty( "project.dev." + entry.getKey(), (String) entry.getValue() ); } for ( Object o : config.getOriginalScmInfo().entrySet() ) { Entry entry = (Entry) o; Scm scm = (Scm) entry.getValue(); String prefix = "project.scm." + entry.getKey(); if ( scm != null ) { if ( scm.getConnection() != null ) { properties.setProperty( prefix + ".connection", scm.getConnection() ); } if ( scm.getDeveloperConnection() != null ) { properties.setProperty( prefix + ".developerConnection", scm.getDeveloperConnection() ); } if ( scm.getUrl() != null ) { properties.setProperty( prefix + ".url", scm.getUrl() ); } if ( scm.getTag() != null ) { properties.setProperty( prefix + ".tag", scm.getTag() ); } } else { properties.setProperty( prefix + ".empty", "true" ); } } for ( Object o : config.getEnvironments().entrySet() ) { Entry entry = (Entry) o; properties.setProperty( "build.env." + entry.getKey(), (String) entry.getValue() ); } if ( ( config.getResolvedSnapshotDependencies() != null ) && ( config.getResolvedSnapshotDependencies().size() > 0 ) ) { processResolvedDependencies( properties, config.getResolvedSnapshotDependencies() ); } // executables if ( config.getExecutable() != null ) { properties.setProperty( "build.executable", config.getExecutable() ); } // release by if ( config.getReleaseBy() != null ) { properties.setProperty( "release.by", config.getReleaseBy() ); } OutputStream outStream = null; //noinspection OverlyBroadCatchBlock try { outStream = new FileOutputStream( file ); properties.store( outStream, "release configuration" ); } catch ( IOException e ) { throw new ReleaseDescriptorStoreException( "Error writing properties file '" + file.getName() + "': " + e.getMessage(), e ); } finally { IOUtil.close( outStream ); } } private void processResolvedDependencies( Properties prop, Map resolvedDependencies ) { Set entries = resolvedDependencies.entrySet(); Iterator iterator = entries.iterator(); Entry currentEntry; while ( iterator.hasNext() ) { currentEntry = (Entry) iterator.next(); Map versionMap = (Map) currentEntry.getValue(); prop.setProperty( "dependency." + currentEntry.getKey() + ".release", (String) versionMap.get( ReleaseDescriptor.RELEASE_KEY ) ); prop.setProperty( "dependency." + currentEntry.getKey() + ".development", (String) versionMap.get( ReleaseDescriptor.DEVELOPMENT_KEY ) ); } } private void loadResolvedDependencies( Properties prop, ReleaseDescriptor descriptor ) { Map<String, Map<String, Object>> resolvedDependencies = new HashMap<String, Map<String, Object>>(); Set entries = prop.entrySet(); Iterator iterator = entries.iterator(); String propertyName; Entry currentEntry; while ( iterator.hasNext() ) { currentEntry = (Entry) iterator.next(); propertyName = (String) currentEntry.getKey(); if ( propertyName.startsWith( "dependency." ) ) { Map<String, Object> versionMap; String artifactVersionlessKey; int startIndex; int endIndex; String versionType; startIndex = propertyName.lastIndexOf( "dependency." ); if ( propertyName.indexOf( ".development" ) != -1 ) { endIndex = propertyName.indexOf( ".development" ); versionType = ReleaseDescriptor.DEVELOPMENT_KEY; } else { endIndex = propertyName.indexOf( ".release" ); versionType = ReleaseDescriptor.RELEASE_KEY; } artifactVersionlessKey = propertyName.substring( startIndex, endIndex ); if ( resolvedDependencies.containsKey( artifactVersionlessKey ) ) { versionMap = resolvedDependencies.get( artifactVersionlessKey ); } else { versionMap = new HashMap<String, Object>(); resolvedDependencies.put( artifactVersionlessKey, versionMap ); } versionMap.put( versionType, currentEntry.getValue() ); } } descriptor.setResolvedSnapshotDependencies( resolvedDependencies ); } }
5,420
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/utils/ReleaseHelper.java
package org.apache.continuum.release.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.maven.artifact.repository.ArtifactRepository; import java.util.List; import java.util.Map; public interface ReleaseHelper { /** * Extracts parameters specified for the maven-release-plugin from the given project's metadata. * * @param localRepo the local artifact repo to use for resolving project metadata * @param workingDirectory working directory of project containing pom file * @param pomFilename the name of the pom file in working directory * @return a map consisting of the release plugin parameters from project metadata * @throws Exception */ Map<String, Object> extractPluginParameters( ArtifactRepository localRepo, String workingDirectory, String pomFilename ) throws Exception; /** * Constructs a list of release preparation parameters for the given project and its modules. The parameter map for * each project consists of: * <ul> * <li>key - groupId:artifactId</li> * <li>name - name or artifactId if none</li> * <li>dev - the version the project will assume after preparation</li> * <li>release - the version the project will ultimately released as when performing</li> * </ul> * * @param localRepo the local artifact repo to use for resolving project metadata * @param workingDirectory working directory of project * @param pomFilename the filename of the pom inside the working directory * @param autoVersionSubmodules true sets all modules to the root project's version, false uses module versions * @param projects the resulting list of parameter maps for the project and its modules * @throws Exception */ public void buildVersionParams( ArtifactRepository localRepo, String workingDirectory, String pomFilename, boolean autoVersionSubmodules, List<Map<String, String>> projects ) throws Exception; }
5,421
0
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-release/src/main/java/org/apache/continuum/release/utils/DefaultReleaseHelper.java
package org.apache.continuum.release.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.maven.artifact.repository.ArtifactRepository; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.shared.release.versions.DefaultVersionInfo; import org.apache.maven.shared.release.versions.VersionInfo; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @Service( "releaseHelper" ) public class DefaultReleaseHelper implements ReleaseHelper { @Resource MavenProjectBuilder mavenProjectBuilder; public Map<String, Object> extractPluginParameters( ArtifactRepository localRepo, String workingDirectory, String pomFilename ) throws Exception { Map<String, Object> params = new HashMap<String, Object>(); // TODO: Use the model reader so we'll can get the plugin configuration from parent too MavenProject model = getMavenProject( localRepo, workingDirectory, pomFilename ); if ( model.getBuild() != null && model.getBuild().getPlugins() != null ) { for ( Plugin plugin : model.getBuild().getPlugins() ) { if ( plugin.getGroupId() != null && plugin.getGroupId().equals( "org.apache.maven.plugins" ) && plugin.getArtifactId() != null && plugin.getArtifactId().equals( "maven-release-plugin" ) ) { Xpp3Dom dom = (Xpp3Dom) plugin.getConfiguration(); // TODO: use constants if ( dom != null ) { Xpp3Dom configuration = dom.getChild( "releaseLabel" ); if ( configuration != null ) { params.put( "scm-tag", configuration.getValue() ); } configuration = dom.getChild( "tag" ); if ( configuration != null ) { params.put( "scm-tag", configuration.getValue() ); } configuration = dom.getChild( "tagBase" ); if ( configuration != null ) { params.put( "scm-tagbase", configuration.getValue() ); } configuration = dom.getChild( "preparationGoals" ); if ( configuration != null ) { params.put( "preparation-goals", configuration.getValue() ); } configuration = dom.getChild( "arguments" ); if ( configuration != null ) { params.put( "arguments", configuration.getValue() ); } configuration = dom.getChild( "scmCommentPrefix" ); if ( configuration != null ) { params.put( "scm-comment-prefix", configuration.getValue() ); } configuration = dom.getChild( "autoVersionSubmodules" ); if ( configuration != null ) { params.put( "auto-version-submodules", Boolean.valueOf( configuration.getValue() ) ); } configuration = dom.getChild( "addSchema" ); if ( configuration != null ) { params.put( "add-schema", Boolean.valueOf( configuration.getValue() ) ); } configuration = dom.getChild( "useReleaseProfile" ); if ( configuration != null ) { params.put( "use-release-profile", Boolean.valueOf( configuration.getValue() ) ); } configuration = dom.getChild( "goals" ); if ( configuration != null ) { String goals = configuration.getValue(); if ( model.getDistributionManagement() != null && model.getDistributionManagement().getSite() != null ) { goals += " site-deploy"; } params.put( "perform-goals", goals ); } } } } } return params; } public void buildVersionParams( ArtifactRepository localRepo, String workingDirectory, String pomFilename, boolean autoVersionSubmodules, List<Map<String, String>> projects ) throws Exception { MavenProject model = getMavenProject( localRepo, workingDirectory, pomFilename ); if ( model.getGroupId() == null ) { model.setGroupId( model.getParent().getGroupId() ); } if ( model.getVersion() == null ) { model.setVersion( model.getParent().getVersion() ); } setProperties( model, autoVersionSubmodules, projects ); for ( Iterator modules = model.getModules().iterator(); modules.hasNext(); ) { String module = StringUtils.replace( modules.next().toString(), '\\', '/' ); buildVersionParams( localRepo, workingDirectory + "/" + module, "pom.xml", autoVersionSubmodules, projects ); } } private void setProperties( MavenProject model, boolean autoVersionSubmodules, List<Map<String, String>> projects ) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put( "key", model.getGroupId() + ":" + model.getArtifactId() ); if ( model.getName() == null ) { model.setName( model.getArtifactId() ); } params.put( "name", model.getName() ); if ( !autoVersionSubmodules || projects.size() == 0 ) { VersionInfo version = new DefaultVersionInfo( model.getVersion() ); params.put( "release", version.getReleaseVersionString() ); params.put( "dev", version.getNextVersion().getSnapshotVersionString() ); } else { Map<String, String> rootParams = projects.get( 0 ); // get the root map params.put( "release", rootParams.get( "release" ) ); params.put( "dev", rootParams.get( "dev" ) ); } projects.add( params ); } private MavenProject getMavenProject( ArtifactRepository localRepo, String workingDirectory, String pomFilename ) throws ProjectBuildingException { return mavenProjectBuilder.build( new File( workingDirectory, pomFilename ), localRepo, null ); } }
5,422
0
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-api/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-api/src/main/java/org/apache/continuum/distributed/transport/slave/SlaveBuildAgentTransportService.java
package org.apache.continuum.distributed.transport.slave; /* * 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.atlassian.xmlrpc.ServiceObject; import java.util.List; import java.util.Map; import java.util.Properties; /** * SlaveBuildAgentTransportService */ @ServiceObject( "SlaveBuildAgentTransportService" ) public interface SlaveBuildAgentTransportService { public Boolean buildProjects( List<Map<String, Object>> projectsBuildContext ) throws Exception; public Map<String, Object> getBuildResult( int projectId ) throws Exception; public Map<String, Object> getProjectCurrentlyBuilding() throws Exception; public List<Map<String, String>> getAvailableInstallations() throws Exception; public Boolean ping() throws Exception; public Boolean cancelBuild() throws Exception; public String generateWorkingCopyContent( int projectId, String directory, String baseUrl, String imagesBaseUrl ) throws Exception; public Map<String, Object> getProjectFile( int projectId, String directory, String filename ) throws Exception; public Map getReleasePluginParameters( int projectId, String pomFilename ) throws Exception; public List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws Exception; public String releasePrepare( Map project, Properties properties, Map releaseVersion, Map developmentVersion, Map environments, String username ) throws Exception; public Map<String, Object> getReleaseResult( String releaseId ) throws Exception; public Map<String, Object> getListener( String releaseId ) throws Exception; public Boolean removeListener( String releaseId ) throws Exception; public String getPreparedReleaseName( String releaseId ) throws Exception; public Boolean releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws Exception; public String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map environments, String username ) throws Exception; public String releaseCleanup( String releaseId ) throws Exception; public Boolean releaseRollback( String releaseId, int projectId ) throws Exception; public Integer getBuildSizeOfAgent() throws Exception; public List<Map<String, Object>> getProjectsInPrepareBuildQueue() throws Exception; public List<Map<String, Object>> getProjectsAndBuildDefinitionsInPrepareBuildQueue() throws Exception; public List<Map<String, Object>> getProjectsInBuildQueue() throws Exception; public Map<String, Object> getProjectCurrentlyPreparingBuild() throws Exception; public List<Map<String, Object>> getProjectsAndBuildDefinitionsCurrentlyPreparingBuild() throws Exception; public Boolean isProjectGroupInQueue( int projectGroupId ) throws Exception; public Boolean isProjectScmRootInQueue( int projectScmRootId, List<Integer> projectIds ) throws Exception; public Boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws Exception; public Boolean isProjectInBuildQueue( int projectId, int buildDefinitionId ) throws Exception; public Boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws Exception; public Boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) throws Exception; public Boolean isProjectGroupInPrepareBuildQueue( int projectGroupId ) throws Exception; public Boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId ) throws Exception; public Boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws Exception; public Boolean removeFromPrepareBuildQueue( List<String> hashCodes ) throws Exception; public Boolean removeFromBuildQueue( int projectId, int buildDefinitionId ) throws Exception; public Boolean removeFromBuildQueue( List<String> hashCodes ) throws Exception; /** * Get build agent's platform. * * @return The operating system name of the build agent * @throws Exception */ public String getBuildAgentPlatform() throws Exception; /** * 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 * @throws Exception error that will occur during the purge */ public void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws Exception; /** * 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 Exception; }
5,423
0
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-server/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-server/src/main/java/org/apache/continuum/distributed/transport/slave/SlaveBuildAgentTransportServer.java
package org.apache.continuum.distributed.transport.slave; /* * 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.ContinuumBuildAgentException; import org.apache.continuum.buildagent.ContinuumBuildAgentService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; import java.util.Properties; /** * ProxyMasterBuildAgentTransportService */ public class SlaveBuildAgentTransportServer implements SlaveBuildAgentTransportService { private Logger log = LoggerFactory.getLogger( this.getClass() ); private ContinuumBuildAgentService continuumBuildAgentService; public SlaveBuildAgentTransportServer( ContinuumBuildAgentService continuumBuildAgentService ) { this.continuumBuildAgentService = continuumBuildAgentService; } public Boolean buildProjects( List<Map<String, Object>> projectsBuildContext ) throws Exception { Boolean result; try { continuumBuildAgentService.buildProjects( projectsBuildContext ); result = Boolean.TRUE; log.debug( "building projects" ); } catch ( ContinuumBuildAgentException e ) { log.error( "failed to build projects", e ); throw e; } return result; } public List<Map<String, String>> getAvailableInstallations() throws Exception { List<Map<String, String>> installations; try { installations = continuumBuildAgentService.getAvailableInstallations(); log.debug( "Available installations: {}", installations.size() ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to get available installations.", e ); throw e; } return installations; } public Map<String, Object> getBuildResult( int projectId ) throws Exception { Map<String, Object> buildResult; try { buildResult = continuumBuildAgentService.getBuildResult( projectId ); log.debug( "Build result for project '{}' acquired.", projectId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to get build result for project '" + projectId + "'", e ); throw e; } return buildResult; } public Map<String, Object> getProjectCurrentlyBuilding() throws Exception { Map<String, Object> project = continuumBuildAgentService.getProjectCurrentlyBuilding(); log.debug( "Retrieving currently building project" ); return project; } public Boolean ping() throws Exception { return continuumBuildAgentService.ping(); } public Boolean cancelBuild() throws Exception { Boolean result; try { continuumBuildAgentService.cancelBuild(); result = Boolean.TRUE; log.debug( "Cancelled build" ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to cancel build", e ); throw e; } return result; } public String generateWorkingCopyContent( int projectId, String directory, String baseUrl, String imagesBaseUrl ) throws Exception { try { log.debug( "Generate working copy content for project '{}'", projectId ); return continuumBuildAgentService.generateWorkingCopyContent( projectId, directory, baseUrl, imagesBaseUrl ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to generate working copy content for projectId=" + projectId, e ); throw e; } } public Map<String, Object> getProjectFile( int projectId, String directory, String filename ) throws Exception { try { log.debug( "Retrieve project '{}' file content", projectId ); return continuumBuildAgentService.getProjectFile( projectId, directory, filename ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve project '" + projectId + "' file content", e ); throw e; } } public Map getReleasePluginParameters( int projectId, String pomFilename ) throws Exception { try { log.debug( "Retrieving release plugin parameters for project '{}'", projectId ); return continuumBuildAgentService.getReleasePluginParameters( projectId, pomFilename ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve release plugin parameters for project '" + projectId + "'", e ); throw e; } } public List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws Exception { try { log.debug( "Processing project '{}'", projectId ); return continuumBuildAgentService.processProject( projectId, pomFilename, autoVersionSubmodules ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to process project '" + projectId + "'", e ); throw e; } } public String releasePrepare( Map project, Properties properties, Map releaseVersion, Map developmentVersion, Map environments, String username ) throws Exception { try { log.debug( "Preparing release" ); return continuumBuildAgentService.releasePrepare( project, properties, releaseVersion, developmentVersion, environments, username ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to prepare release", e ); throw e; } } public Map<String, Object> getListener( String releaseId ) throws Exception { try { log.debug( "Retrieving listener for releaseId={}", releaseId ); return continuumBuildAgentService.getListener( releaseId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve listener state of releaseId=" + releaseId, e ); throw e; } } public Map<String, Object> getReleaseResult( String releaseId ) throws Exception { try { log.debug( "Retrieving release result, releaseId={}", releaseId ); return continuumBuildAgentService.getReleaseResult( releaseId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve release result of releaseId=" + releaseId, e ); throw e; } } public Boolean removeListener( String releaseId ) throws Exception { Boolean result; try { continuumBuildAgentService.removeListener( releaseId ); result = Boolean.TRUE; log.debug( "Removing listener for releaseId={}", releaseId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to remove listener of releaseId=" + releaseId, e ); throw e; } return result; } public String getPreparedReleaseName( String releaseId ) throws Exception { try { log.debug( "Retrieving prepared release name, releaseId={}", releaseId ); return continuumBuildAgentService.getPreparedReleaseName( releaseId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve prepared release name of releaseId=" + releaseId ); throw e; } } public Boolean releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws Exception { Boolean result; try { continuumBuildAgentService.releasePerform( releaseId, goals, arguments, useReleaseProfile, repository, username ); result = Boolean.TRUE; log.debug( "Perform release of releaseId={}", releaseId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Unable to perform release of releaseId=" + releaseId, e ); throw e; } return result; } public String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map environments, String username ) throws Exception { try { log.debug( "Perform release of scmUrl={}", scmUrl ); return continuumBuildAgentService.releasePerformFromScm( goals, arguments, useReleaseProfile, repository, scmUrl, scmUsername, scmPassword, scmTag, scmTagBase, environments, username ); } catch ( ContinuumBuildAgentException e ) { log.error( "Unable to perform release of scmUrl=" + scmUrl, e ); throw e; } } public String releaseCleanup( String releaseId ) throws Exception { try { log.debug( "Cleanup release, releaseId={}", releaseId ); return continuumBuildAgentService.releaseCleanup( releaseId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Unable to cleanup release, releaseId=" + releaseId, e ); throw e; } } public Boolean releaseRollback( String releaseId, int projectId ) throws Exception { Boolean result; try { continuumBuildAgentService.releaseRollback( releaseId, projectId ); result = Boolean.TRUE; log.debug( "Rollback release. releaseId={}, projectId={}", releaseId, projectId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to rollback release. releaseId=" + releaseId + ", projectId=" + projectId, e ); throw e; } return result; } public Integer getBuildSizeOfAgent() throws Exception { try { return continuumBuildAgentService.getBuildSizeOfAgent(); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve build size of agent", e ); throw e; } } public Map<String, Object> getProjectCurrentlyPreparingBuild() throws Exception { try { return continuumBuildAgentService.getProjectCurrentlyPreparingBuild(); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve projects currently preparing build", e ); throw e; } } public List<Map<String, Object>> getProjectsAndBuildDefinitionsCurrentlyPreparingBuild() throws Exception { try { return continuumBuildAgentService.getProjectsAndBuildDefinitionsCurrentlyPreparingBuild(); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve projects currently preparing build", e ); throw e; } } public List<Map<String, Object>> getProjectsInBuildQueue() throws Exception { try { log.debug( "Retrieving projects in build queue" ); return continuumBuildAgentService.getProjectsInBuildQueue(); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve projects in build queue", e ); throw e; } } public List<Map<String, Object>> getProjectsInPrepareBuildQueue() throws Exception { try { log.debug( "Retrieving projects in prepare build queue" ); return continuumBuildAgentService.getProjectsInPrepareBuildQueue(); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve projects in prepare build queue", e ); throw e; } } public List<Map<String, Object>> getProjectsAndBuildDefinitionsInPrepareBuildQueue() throws Exception { try { log.debug( "Retrieving projects in prepare build queue" ); return continuumBuildAgentService.getProjectsAndBuildDefinitionsInPrepareBuildQueue(); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to retrieve projects in prepare build queue", e ); throw e; } } public Boolean isProjectGroupInQueue( int projectGroupId ) throws Exception { log.debug( "Checking if project group '{}' is in queue", projectGroupId ); return continuumBuildAgentService.isProjectGroupInQueue( projectGroupId ); } public Boolean isProjectScmRootInQueue( int projectScmRootId, List<Integer> projectIds ) throws Exception { log.debug( "Checking if project scm root '{}' is in queue", projectScmRootId ); return continuumBuildAgentService.isProjectScmRootInQueue( projectScmRootId, projectIds ); } public Boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws Exception { log.debug( "Checking if projectId={}, buildDefinitionId={} is currently building in agent", projectId, buildDefinitionId ); return continuumBuildAgentService.isProjectCurrentlyBuilding( projectId, buildDefinitionId ); } public Boolean isProjectInBuildQueue( int projectId, int buildDefinitionId ) throws Exception { log.debug( "Checking if projectId={}, buildDefinitionId={} is in build queue of agent", projectId, buildDefinitionId ); return continuumBuildAgentService.isProjectInBuildQueue( projectId, buildDefinitionId ); } public Boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws Exception { log.debug( "Checking if projectId={}, buildDefinitionId={} is currently preparing build", projectId, buildDefinitionId ); return continuumBuildAgentService.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ); } public Boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) throws Exception { log.debug( "Checking if projectId={}, buildDefinitionId={} is in prepare build queue", projectId, buildDefinitionId ); return continuumBuildAgentService.isProjectInPrepareBuildQueue( projectId, buildDefinitionId ); } public Boolean isProjectGroupInPrepareBuildQueue( int projectGroupId ) throws Exception { log.debug( "Checking if project group {} is in prepare build queue", projectGroupId ); return continuumBuildAgentService.isProjectGroupInPrepareBuildQueue( projectGroupId ); } public Boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId ) throws Exception { log.debug( "Checking if project group {} is currently preparing build", projectGroupId ); return continuumBuildAgentService.isProjectGroupCurrentlyPreparingBuild( projectGroupId ); } public Boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws Exception { try { log.debug( "Remove projects from prepare build queue. projectGroupId={}, scmRootId={}", projectGroupId, scmRootId ); return continuumBuildAgentService.removeFromPrepareBuildQueue( projectGroupId, scmRootId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to remove projects from prepare build queue. projectGroupId=" + projectGroupId + ", scmRootId=" + scmRootId ); throw e; } } public Boolean removeFromPrepareBuildQueue( List<String> hashCodes ) throws Exception { Boolean result; try { continuumBuildAgentService.removeFromPrepareBuildQueue( hashCodes ); result = Boolean.TRUE; log.debug( "removed projects from prepare build queue" ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to remove projects from prepare build queue" ); throw e; } return result; } public Boolean removeFromBuildQueue( int projectId, int buildDefinitionId ) throws Exception { try { log.debug( "Remove project '" + projectId + "' from build queue" ); return continuumBuildAgentService.removeFromBuildQueue( projectId, buildDefinitionId ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to remove project '" + projectId + "' from build queue" ); throw e; } } public Boolean removeFromBuildQueue( List<String> hashCodes ) throws Exception { Boolean result; try { continuumBuildAgentService.removeFromBuildQueue( hashCodes ); result = Boolean.TRUE; log.debug( "removed projects from build queue" ); } catch ( ContinuumBuildAgentException e ) { log.error( "Failed to remove projects from build queue" ); throw e; } return result; } public String getBuildAgentPlatform() throws Exception { return continuumBuildAgentService.getBuildAgentPlatform(); } public void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws Exception { continuumBuildAgentService.executeDirectoryPurge( directoryType, daysOlder, retentionCount, deleteAll ); } public void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll, boolean deleteReleasedSnapshots ) throws Exception { continuumBuildAgentService.executeRepositoryPurge( repoName, daysOlder, retentionCount, deleteAll, deleteReleasedSnapshots ); } }
5,424
0
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-server/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-server/src/main/java/org/apache/continuum/distributed/transport/slave/SlaveBuildAgentTransportAuthenticator.java
package org.apache.continuum.distributed.transport.slave; /* * 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.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl; import org.apache.xmlrpc.server.AbstractReflectiveHandlerMapping.AuthenticationHandler; import org.codehaus.plexus.util.StringUtils; public class SlaveBuildAgentTransportAuthenticator implements AuthenticationHandler { private BuildAgentConfigurationService buildAgentConfigurationService; public SlaveBuildAgentTransportAuthenticator( BuildAgentConfigurationService buildAgentConfigurationService ) { this.buildAgentConfigurationService = buildAgentConfigurationService; } public boolean isAuthorized( XmlRpcRequest pRequest ) throws XmlRpcException { if ( pRequest.getConfig() instanceof XmlRpcHttpRequestConfigImpl ) { XmlRpcHttpRequestConfigImpl config = (XmlRpcHttpRequestConfigImpl) pRequest.getConfig(); if ( config.getBasicPassword() == null || StringUtils.isBlank( config.getBasicPassword() ) ) { throw new XmlRpcException( "Shared Secret Password is not present in the server request" ); } if ( buildAgentConfigurationService.getSharedSecretPassword() == null || StringUtils.isBlank( buildAgentConfigurationService.getSharedSecretPassword() ) ) { throw new XmlRpcException( "Shared Secret Password is not configured properly on the build agent" ); } return buildAgentConfigurationService.getSharedSecretPassword().equals( config.getBasicPassword() ); } throw new XmlRpcException( "Unsupported transport (must be http)" ); } }
5,425
0
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-client/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-client/src/main/java/org/apache/continuum/distributed/transport/slave/SampleBuildAgentClient.java
package org.apache.continuum.distributed.transport.slave; /* * 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.net.MalformedURLException; import java.net.URL; public class SampleBuildAgentClient { public static void main( String[] args ) throws Exception { try { SlaveBuildAgentTransportClient client = new SlaveBuildAgentTransportClient( new URL( args[0] ) ); client.ping(); System.out.println( client.getBuildAgentPlatform() ); } catch ( MalformedURLException e ) { System.out.println( "Invalid Url." + e ); } catch ( Exception e ) { System.out.println( "build agent is un reachable. " + e ); } } }
5,426
0
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-client/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-slave/continuum-distributed-slave-client/src/main/java/org/apache/continuum/distributed/transport/slave/SlaveBuildAgentTransportClient.java
package org.apache.continuum.distributed.transport.slave; /* * 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.atlassian.xmlrpc.Binder; import com.atlassian.xmlrpc.BindingException; import com.atlassian.xmlrpc.ConnectionInfo; import org.apache.continuum.distributed.commons.utils.ContinuumXmlRpcBinder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TimeZone; /** * SlaveBuildAgentTransportClient */ public class SlaveBuildAgentTransportClient implements SlaveBuildAgentTransportService { private static final Logger log = LoggerFactory.getLogger( SlaveBuildAgentTransportClient.class ); private SlaveBuildAgentTransportService slave; private String buildAgentUrl; public SlaveBuildAgentTransportClient( URL serviceUrl ) throws Exception { this( serviceUrl, null, null ); } public SlaveBuildAgentTransportClient( URL serviceUrl, String login, String password ) throws Exception { Binder binder = ContinuumXmlRpcBinder.getInstance(); ConnectionInfo connectionInfo = new ConnectionInfo(); connectionInfo.setUsername( login ); connectionInfo.setPassword( password ); connectionInfo.setTimeZone( TimeZone.getDefault() ); buildAgentUrl = serviceUrl.toString(); try { slave = binder.bind( SlaveBuildAgentTransportService.class, serviceUrl, connectionInfo ); } catch ( BindingException e ) { log.error( "Can't bind service interface " + SlaveBuildAgentTransportService.class.getName() + " to " + serviceUrl.toExternalForm() + " using " + connectionInfo.getUsername() + ", " + connectionInfo.getPassword(), e ); throw new Exception( "Can't bind service interface " + SlaveBuildAgentTransportService.class.getName() + " to " + serviceUrl.toExternalForm() + " using " + connectionInfo.getUsername() + ", " + connectionInfo.getPassword(), e ); } } public Boolean buildProjects( List<Map<String, Object>> projectsBuildContext ) throws Exception { Boolean result; try { result = slave.buildProjects( projectsBuildContext ); log.debug( "Building projects in build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to build projects in build agent " + buildAgentUrl, e ); log.error( "Context: " + projectsBuildContext ); throw new Exception( "Failed to build projects in build agent " + buildAgentUrl, e ); } return result; } public List<Map<String, String>> getAvailableInstallations() throws Exception { List<Map<String, String>> installations; try { installations = slave.getAvailableInstallations(); log.debug( "Available installations in build agent {} : {}", buildAgentUrl, installations.size() ); } catch ( Exception e ) { log.error( "Failed to get available installations in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to get available installations in build agent " + buildAgentUrl, e ); } return installations; } public Map<String, Object> getBuildResult( int projectId ) throws Exception { Map<String, Object> buildResult; try { buildResult = slave.getBuildResult( projectId ); log.debug( "Build result for project '{}' acquired from build agent {}", projectId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to get build result for project '" + projectId + "' in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to get build result for project '" + projectId + "' in build agent " + buildAgentUrl, e ); } return buildResult; } public Map<String, Object> getProjectCurrentlyBuilding() throws Exception { Map<String, Object> map; try { map = slave.getProjectCurrentlyBuilding(); log.debug( "Retrieving currently building project in build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to get the currently building project in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to get the currently building project in build agent " + buildAgentUrl, e ); } return map; } public Boolean ping() throws Exception { Boolean result; try { result = slave.ping(); log.debug( "Ping build agent {} : {}", buildAgentUrl, ( result ? "ok" : "failed" ) ); } catch ( Exception e ) { log.error( "Ping build agent " + buildAgentUrl + " error", e ); throw new Exception( "Ping build agent " + buildAgentUrl + " error", e ); } return result; } public Boolean cancelBuild() throws Exception { Boolean result; try { result = slave.cancelBuild(); log.debug( "Cancelled current build in build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Error cancelling current build in build agent " + buildAgentUrl, e ); throw new Exception( "Error cancelling current build in build agent " + buildAgentUrl, e ); } return result; } public String generateWorkingCopyContent( int projectId, String directory, String baseUrl, String imagesBaseUrl ) throws Exception { String result; try { result = slave.generateWorkingCopyContent( projectId, directory, baseUrl, imagesBaseUrl ); log.debug( "Generated working copy content for project '{}' in build agent ", projectId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error generating working copy content for project '" + projectId + "' in build agent " + buildAgentUrl, e ); throw new Exception( "Error generating working copy content for project '" + projectId + "' in build agent " + buildAgentUrl, e ); } return result; } public Map<String, Object> getProjectFile( int projectId, String directory, String filename ) throws Exception { Map<String, Object> result; try { result = slave.getProjectFile( projectId, directory, filename ); log.debug( "Retrieved project '{}' file content from build agent {}", projectId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error retrieving project '" + projectId + "' file content from build agent " + buildAgentUrl, e ); throw new Exception( "Error retrieving project '" + projectId + "' file content from build agent " + buildAgentUrl, e ); } return result; } public Map getReleasePluginParameters( int projectId, String pomFilename ) throws Exception { Map result; try { result = slave.getReleasePluginParameters( projectId, pomFilename ); log.debug( "Retrieving release plugin parameters for project '{}' from build agent {}", projectId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error retrieving release plugin parameters for project '" + projectId + "' from build agent " + buildAgentUrl, e ); throw new Exception( "Error retrieving release plugin parameters for project '" + projectId + "' from build agent " + buildAgentUrl, e ); } return result; } public List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws Exception { List<Map<String, String>> result; try { result = slave.processProject( projectId, pomFilename, autoVersionSubmodules ); log.debug( "Processing project '{}' in build agent ", projectId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error processing project '" + projectId + "' in build agent " + buildAgentUrl, e ); throw new Exception( "Error processing project '" + projectId + "' in build agent " + buildAgentUrl, e ); } return result; } public String releasePrepare( Map project, Properties properties, Map releaseVersion, Map developmentVersion, Map environments, String username ) throws Exception { String releaseId; try { releaseId = slave.releasePrepare( project, properties, releaseVersion, developmentVersion, environments, username ); log.debug( "Preparing release '{}' in build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error while preparing release in build agent " + buildAgentUrl, e ); throw new Exception( "Error while preparing release in build agent " + buildAgentUrl, e ); } return releaseId; } public Map<String, Object> getReleaseResult( String releaseId ) throws Exception { Map<String, Object> result; try { result = slave.getReleaseResult( releaseId ); log.debug( "Retrieving release result, releaseId={} from build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error retrieving release result, releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); throw new Exception( "Error retrieving release result, releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); } return result; } public Map<String, Object> getListener( String releaseId ) throws Exception { Map<String, Object> result; try { result = slave.getListener( releaseId ); log.debug( "Retrieving listener for releaseId={} from build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error retrieving listener for releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); throw new Exception( "Error retrieving listener for releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); } return result; } public Boolean removeListener( String releaseId ) throws Exception { Boolean result; try { slave.removeListener( releaseId ); result = Boolean.FALSE; log.debug( "Removing listener for releaseId={} from build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error removing listener for releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); throw new Exception( "Error removing listener for releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); } return result; } public String getPreparedReleaseName( String releaseId ) throws Exception { String result; try { result = slave.getPreparedReleaseName( releaseId ); log.debug( "Retrieving prepared release name, releaseId={} from build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error while retrieving prepared release name, releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); throw new Exception( "Error while retrieving prepared release name, releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); } return result; } public Boolean releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws Exception { Boolean result; try { slave.releasePerform( releaseId, goals, arguments, useReleaseProfile, repository, username ); result = Boolean.FALSE; log.debug( "Performing release of releaseId={} from build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error performing release of releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); throw new Exception( "Error performing release of releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); } return result; } public String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map environments, String username ) throws Exception { String result; try { result = slave.releasePerformFromScm( goals, arguments, useReleaseProfile, repository, scmUrl, scmUsername, scmPassword, scmTag, scmTagBase, environments, username ); log.debug( "Performing release of scmUrl={} from build agent {}", scmUrl, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error performing release from scm '" + scmUrl + "' from build agent " + buildAgentUrl, e ); throw new Exception( "Error performing release from scm '" + scmUrl + "' from build agent " + buildAgentUrl, e ); } return result; } public String releaseCleanup( String releaseId ) throws Exception { String result; try { result = slave.releaseCleanup( releaseId ); log.debug( "Cleanup release, releaseId={} from build agent {}", releaseId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Error cleaning up release, releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); throw new Exception( "Error cleaning up release, releaseId=" + releaseId + " from build agent " + buildAgentUrl, e ); } return result; } public Boolean releaseRollback( String releaseId, int projectId ) throws Exception { Boolean result; try { slave.releaseRollback( releaseId, projectId ); result = Boolean.TRUE; log.debug( "Rollback release. releaseId={}, projectId={} from build agent {}", new Object[]{releaseId, projectId, buildAgentUrl} ); } catch ( Exception e ) { log.error( "Failed to rollback release. releaseId=" + releaseId + ", projectId=" + projectId + " from build agent " + buildAgentUrl, e ); throw (Exception) e.getCause().getCause().getCause().getCause(); } return result; } public Integer getBuildSizeOfAgent() throws Exception { Integer size; try { size = slave.getBuildSizeOfAgent(); log.debug( "Retrieving build size of build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve build size of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to retrieve build size of build agent " + buildAgentUrl, e ); } return size; } public Map<String, Object> getProjectCurrentlyPreparingBuild() throws Exception { Map<String, Object> projects; try { projects = slave.getProjectCurrentlyPreparingBuild(); log.debug( "Retrieving projects currently preparing build in build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve projects currently preparing build in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to retrieve projects currently preparing build in build agent " + buildAgentUrl, e ); } return projects; } public List<Map<String, Object>> getProjectsAndBuildDefinitionsCurrentlyPreparingBuild() throws Exception { List<Map<String, Object>> projects; try { projects = slave.getProjectsAndBuildDefinitionsCurrentlyPreparingBuild(); log.debug( "Retrieving projects currently preparing build in build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve projects currently preparing build in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to retrieve projects currently preparing build in build agent " + buildAgentUrl, e ); } return projects; } public List<Map<String, Object>> getProjectsInBuildQueue() throws Exception { List<Map<String, Object>> projects; try { projects = slave.getProjectsInBuildQueue(); log.debug( "Retrieving projects in build queue of build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve projects in build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to retrieve projects in build queue of build agent " + buildAgentUrl, e ); } return projects; } public List<Map<String, Object>> getProjectsInPrepareBuildQueue() throws Exception { List<Map<String, Object>> projects; try { projects = slave.getProjectsInPrepareBuildQueue(); log.debug( "Retrieving projects in prepare build queue of build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve projects in prepare build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to retrieve projects in prepare build queue of build agent " + buildAgentUrl, e ); } return projects; } public List<Map<String, Object>> getProjectsAndBuildDefinitionsInPrepareBuildQueue() throws Exception { List<Map<String, Object>> projects; try { projects = slave.getProjectsAndBuildDefinitionsInPrepareBuildQueue(); log.debug( "Retrieving projects in prepare build queue of build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve projects in prepare build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to retrieve projects in prepare build queue of build agent " + buildAgentUrl, e ); } return projects; } public Boolean isProjectGroupInQueue( int projectGroupId ) throws Exception { Boolean result; try { result = slave.isProjectGroupInQueue( projectGroupId ); log.debug( "Checking if project group '{}' is in queue in build agent {}", projectGroupId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to check if project group '" + projectGroupId + "' is in queue in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if project group '" + projectGroupId + "' is in queue in build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectScmRootInQueue( int projectScmRootId, List<Integer> projectIds ) throws Exception { Boolean result; try { result = slave.isProjectScmRootInQueue( projectScmRootId, projectIds ); log.debug( "Checking if project scm root '{}' is in queue in build agent {}", projectScmRootId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to check if project scm root '" + projectScmRootId + "' is in queue in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if project scm root '" + projectScmRootId + "' is in queue in build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws Exception { Boolean result; try { result = slave.isProjectCurrentlyBuilding( projectId, buildDefinitionId ); log.debug( "Checking if projectId={}, buildDefinitionId={} is currently building in build agent {}", new Object[]{projectId, buildDefinitionId, buildAgentUrl} ); } catch ( Exception e ) { log.error( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is currently building in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is currently building in build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectInBuildQueue( int projectId, int buildDefinitionId ) throws Exception { Boolean result; try { result = slave.isProjectInBuildQueue( projectId, buildDefinitionId ); log.debug( "Checking if projectId={}, buildDefinitionId={} is in build queue of build agent {}", new Object[]{projectId, buildDefinitionId, buildAgentUrl} ); } catch ( Exception e ) { log.error( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is in build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is in build queue of build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws Exception { Boolean result; try { result = slave.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ); log.debug( "Checking if projectId={}, buildDefinitionId={} is currently preparing build in build agent {}", new Object[]{projectId, buildDefinitionId, buildAgentUrl} ); } catch ( Exception e ) { log.error( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is currently preparing build in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is currently preparing build in build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) throws Exception { Boolean result; try { result = slave.isProjectInPrepareBuildQueue( projectId, buildDefinitionId ); log.debug( "Checking if projectId={}, buildDefinitionId={} is in prepare build queue of build agent {}", new Object[]{projectId, buildDefinitionId, buildAgentUrl} ); } catch ( Exception e ) { log.error( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is in prepare build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is in prepare build queue of build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectGroupInPrepareBuildQueue( int projectGroupId ) throws Exception { Boolean result; try { result = slave.isProjectGroupInPrepareBuildQueue( projectGroupId ); log.debug( "Checking if projectGroup {} is in prepare build queue of build agent {}", projectGroupId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to check if projectGroup " + projectGroupId + " is in prepare build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if projectGroup " + projectGroupId + " is in prepare build queue of build agent " + buildAgentUrl, e ); } return result; } public Boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId ) throws Exception { Boolean result; try { result = slave.isProjectGroupCurrentlyPreparingBuild( projectGroupId ); log.debug( "Checking if projectGroup {} is currently preparing build in build agent {}", projectGroupId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to check if projectGroup " + projectGroupId + " is currently preparing build in build agent " + buildAgentUrl, e ); throw new Exception( "Failed to check if projectGroup " + projectGroupId + " is currently preparing build in build agent " + buildAgentUrl, e ); } return result; } public Boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws Exception { Boolean result; try { result = slave.removeFromPrepareBuildQueue( projectGroupId, scmRootId ); log.debug( "Remove projects from prepare build queue of build agent {}. projectGroupId={}, scmRootId={}", new Object[]{buildAgentUrl, projectGroupId, scmRootId} ); } catch ( Exception e ) { log.error( "Failed to remove projects from prepare build queue of build agent " + buildAgentUrl + ". projectGroupId=" + projectGroupId + ", scmRootId=" + scmRootId, e ); throw new Exception( "Failed to remove from prepare build queue of build agent " + buildAgentUrl + ". projectGroupId=" + projectGroupId + " scmRootId=" + scmRootId, e ); } return result; } public Boolean removeFromPrepareBuildQueue( List<String> hashCodes ) throws Exception { Boolean result; try { result = slave.removeFromPrepareBuildQueue( hashCodes ); log.debug( "Removing projects from prepare build queue of build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to remove projects from prepare build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to remove projects from prepare build queue of build agent " + buildAgentUrl, e ); } return result; } public Boolean removeFromBuildQueue( int projectId, int buildDefinitionId ) throws Exception { Boolean result; try { result = slave.removeFromBuildQueue( projectId, buildDefinitionId ); log.debug( "Removing project '{}' from build queue of build agent {}", projectId, buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to remove project '" + projectId + "' from build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to remove project '" + projectId + "' from build queue of build agent " + buildAgentUrl, e ); } return result; } public Boolean removeFromBuildQueue( List<String> hashCodes ) throws Exception { Boolean result; try { result = slave.removeFromBuildQueue( hashCodes ); log.debug( "Removing projects from build queue of build agent {}", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to remove projects from build queue of build agent " + buildAgentUrl, e ); throw new Exception( "Failed to remove projects from build queue of build agent " + buildAgentUrl, e ); } return result; } public String getBuildAgentPlatform() throws Exception { String result; try { result = slave.getBuildAgentPlatform(); log.debug( "Retrieved build agent {} platform", buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to return build agent " + buildAgentUrl + " platform", e ); throw new Exception( "Failed to return build agent " + buildAgentUrl + " platform", e ); } return result; } public void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws Exception { slave.executeDirectoryPurge( directoryType, daysOlder, retentionCount, deleteAll ); } public void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll, boolean deleteReleasedSnapshots ) throws Exception { slave.executeRepositoryPurge( repoName, daysOlder, retentionCount, deleteAll, deleteReleasedSnapshots ); } }
5,427
0
Create_ds/continuum/continuum-distributed/continuum-distributed-master/continuum-distributed-master-api/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-master/continuum-distributed-master-api/src/main/java/org/apache/continuum/distributed/transport/master/MasterBuildAgentTransportService.java
package org.apache.continuum.distributed.transport.master; /* * 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.atlassian.xmlrpc.ServiceObject; import java.util.Map; /** * MasterBuildAgentTransportService */ @ServiceObject( "MasterBuildAgentTransportService" ) public interface MasterBuildAgentTransportService { public Boolean returnBuildResult( Map<String, Object> buildResult, String buildAgentUrl ) throws Exception; public Boolean startProjectBuild( Integer projectId, Integer buildDefinitionId, String buildAgentUrl ) throws Exception; public Boolean prepareBuildFinished( Map<String, Object> prepareBuildResult, String buildAgentUrl ) throws Exception; public Boolean startPrepareBuild( Map<String, Object> prepareBuildResult, String buildAgentUrl ) throws Exception; public Map<String, String> getEnvironments( Integer buildDefinitionId, String installationType ) throws Exception; public Boolean updateProject( Map<String, Object> project ) throws Exception; public Boolean ping() throws Exception; public Boolean shouldBuild( Map<String, Object> context, String buildAgentUrl ) throws Exception; }
5,428
0
Create_ds/continuum/continuum-distributed/continuum-distributed-master/continuum-distributed-master-client/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-master/continuum-distributed-master-client/src/main/java/org/apache/continuum/distributed/transport/master/MasterBuildAgentTransportClient.java
package org.apache.continuum.distributed.transport.master; /* * 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.atlassian.xmlrpc.Binder; import com.atlassian.xmlrpc.BindingException; import com.atlassian.xmlrpc.ConnectionInfo; import org.apache.continuum.distributed.commons.utils.ContinuumDistributedUtil; import org.apache.continuum.distributed.commons.utils.ContinuumXmlRpcBinder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; import java.util.Map; import java.util.TimeZone; /** * MasterBuildAgentTransportClient */ public class MasterBuildAgentTransportClient implements MasterBuildAgentTransportService { private static final Logger log = LoggerFactory.getLogger( MasterBuildAgentTransportClient.class ); MasterBuildAgentTransportService master; private String masterServerUrl; public MasterBuildAgentTransportClient( URL serviceUrl ) throws Exception { this( serviceUrl, null, null ); } public MasterBuildAgentTransportClient( URL serviceUrl, String login, String password ) throws Exception { Binder binder = ContinuumXmlRpcBinder.getInstance(); ConnectionInfo connectionInfo = new ConnectionInfo(); connectionInfo.setUsername( login ); connectionInfo.setPassword( password ); connectionInfo.setTimeZone( TimeZone.getDefault() ); this.masterServerUrl = serviceUrl.toString(); try { master = binder.bind( MasterBuildAgentTransportService.class, serviceUrl, connectionInfo ); } catch ( BindingException e ) { log.error( "Can't bind service interface " + MasterBuildAgentTransportService.class.getName() + " to " + serviceUrl.toExternalForm() + " using " + connectionInfo.getUsername() + ", " + connectionInfo.getPassword(), e ); throw new Exception( "Can't bind service interface " + MasterBuildAgentTransportService.class.getName() + " to " + serviceUrl.toExternalForm() + " using " + connectionInfo.getUsername() + ", " + connectionInfo.getPassword(), e ); } } public Boolean returnBuildResult( Map<String, Object> buildResult, String buildAgentUrl ) throws Exception { Boolean result; String projectInfo = ContinuumDistributedUtil.getProjectNameAndId( buildResult ); try { result = master.returnBuildResult( buildResult, buildAgentUrl ); log.info( "Build finished. Returning the build result for project {} to master {}", projectInfo, masterServerUrl ); } catch ( Exception e ) { log.error( "Failed to finish the build and return the build result for project " + projectInfo + " to master " + masterServerUrl, e ); throw new Exception( "Failed to finish the build and return the build result for project " + projectInfo + " to master " + masterServerUrl, e ); } return result; } public Boolean ping() throws Exception { Boolean result; try { result = master.ping(); log.debug( "Ping Master {} : {}", masterServerUrl, ( result ? "ok" : "failed" ) ); } catch ( Exception e ) { log.error( "Ping Master " + masterServerUrl + " error", e ); throw new Exception( "Ping Master " + masterServerUrl + " error", e ); } return result; } public Boolean prepareBuildFinished( Map<String, Object> prepareBuildResult, String buildAgentUrl ) throws Exception { Boolean result; String projectInfo = ContinuumDistributedUtil.getProjectNameAndId( prepareBuildResult ); try { result = master.prepareBuildFinished( prepareBuildResult, buildAgentUrl ); log.info( "Prepare build finished for project '{}'", projectInfo ); } catch ( Exception e ) { log.error( "Failed to finish prepare build for project {}", projectInfo ); throw new Exception( "Failed to finish prepare build for project " + projectInfo + ".", e ); } return result; } public Boolean startProjectBuild( Integer projectId, Integer buildDefinitionId, String buildAgentUrl ) throws Exception { Boolean result; try { result = master.startProjectBuild( projectId, buildDefinitionId, buildAgentUrl ); log.info( "Start project {}, buildDef {} build", projectId, buildDefinitionId ); } catch ( Exception e ) { log.error( "Failed to start build of projectId=" + projectId + " to master " + masterServerUrl, e ); throw new Exception( "Failed to start build of projectId=" + projectId + " to master " + masterServerUrl, e ); } return result; } public Boolean startPrepareBuild( Map<String, Object> prepareBuildResult, String buildAgentUrl ) throws Exception { Boolean result; String projectInfo = ContinuumDistributedUtil.getProjectNameAndId( prepareBuildResult ); try { result = master.startPrepareBuild( prepareBuildResult, buildAgentUrl ); log.info( "Start prepare build for project {}", projectInfo ); } catch ( Exception e ) { log.error( "Failed to start prepare build for project {}", projectInfo, e ); throw new Exception( "Failed to start prepare build for project " + projectInfo, e ); } return result; } public Map<String, String> getEnvironments( Integer buildDefinitionId, String installationType ) throws Exception { Map<String, String> result; try { result = master.getEnvironments( buildDefinitionId, installationType ); log.debug( "Retrieved environments. buildDefinitionId={}, installationType={} from master {}", new Object[]{buildDefinitionId, installationType, masterServerUrl} ); } catch ( Exception e ) { log.error( "Failed to retrieve environments. buildDefinitionId=" + buildDefinitionId + ", installationType=" + installationType + " from master " + masterServerUrl, e ); throw new Exception( "Failed to retrieve environments. buildDefinitionId=" + buildDefinitionId + ", installationType=" + installationType + " from master " + masterServerUrl, e ); } return result; } public Boolean updateProject( Map<String, Object> project ) throws Exception { Boolean result; String projectInfo = ContinuumDistributedUtil.getProjectNameAndId( project ); try { result = master.updateProject( project ); log.debug( "Updating project {} in master {}", projectInfo, masterServerUrl ); } catch ( Exception e ) { log.error( "Failed to update project " + projectInfo + " in master " + masterServerUrl, e ); throw new Exception( "Failed to update project " + projectInfo + " in master " + masterServerUrl, e ); } return result; } public Boolean shouldBuild( Map<String, Object> context, String buildAgentUrl ) throws Exception { Boolean result; String projectInfo = ContinuumDistributedUtil.getProjectNameAndId( context ); try { result = master.shouldBuild( context, buildAgentUrl ); log.debug( "Checking if project {} should build from master {}", projectInfo, masterServerUrl ); } catch ( Exception e ) { log.error( "Failed to determine if project " + projectInfo + " should build from master " + masterServerUrl, e ); throw new Exception( "Failed to determine if project " + projectInfo + " should build from master " + masterServerUrl, e ); } return result; } }
5,429
0
Create_ds/continuum/continuum-distributed/continuum-distributed-master/continuum-distributed-master-server/src/main/java/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-master/continuum-distributed-master-server/src/main/java/org/apache/continuum/distributed/transport/master/MasterBuildAgentTransportServer.java
package org.apache.continuum.distributed.transport.master; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.DistributedBuildService; import org.apache.continuum.distributed.commons.utils.ContinuumDistributedUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * MasterBuildAgentTransportServer */ public class MasterBuildAgentTransportServer implements MasterBuildAgentTransportService { private static final Logger log = LoggerFactory.getLogger( MasterBuildAgentTransportServer.class ); private final DistributedBuildService distributedBuildService; public MasterBuildAgentTransportServer( DistributedBuildService distributedBuildService ) { this.distributedBuildService = distributedBuildService; } public Boolean returnBuildResult( Map<String, Object> buildResult, String buildAgentUrl ) throws Exception { distributedBuildService.updateBuildResult( buildResult ); log.info( "Project {} build finished in build agent {}. Returned build result.", ContinuumDistributedUtil.getProjectNameAndId( buildResult ), buildAgentUrl ); return Boolean.TRUE; } public Boolean ping() throws Exception { log.debug( "Ping master ok" ); return Boolean.TRUE; } public Boolean prepareBuildFinished( Map<String, Object> prepareBuildResult, String buildAgentUrl ) throws Exception { distributedBuildService.prepareBuildFinished( prepareBuildResult ); log.info( "Prepare build finished for project {} in build agent {}", ContinuumDistributedUtil.getProjectNameAndId( prepareBuildResult ), buildAgentUrl ); return Boolean.TRUE; } public Boolean startProjectBuild( Integer projectId, Integer buildDefinitionId, String buildAgentUrl ) throws Exception { distributedBuildService.startProjectBuild( projectId, buildDefinitionId ); log.info( "Start building project (projectId={}, buildDefId={}) in build agent {}.", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); return Boolean.TRUE; } public Boolean startPrepareBuild( Map<String, Object> prepareBuildResult, String buildAgentUrl ) throws Exception { distributedBuildService.startPrepareBuild( prepareBuildResult ); log.info( "Start preparing build of project {} in build agent {}", ContinuumDistributedUtil.getProjectNameAndId( prepareBuildResult ), buildAgentUrl ); return Boolean.TRUE; } public Map<String, String> getEnvironments( Integer buildDefinitionId, String installationType ) throws Exception { Map<String, String> envs = distributedBuildService.getEnvironments( buildDefinitionId, installationType ); log.debug( "Retrieving environments buildDefinitionId={}, installationType={}", new Object[] { buildDefinitionId, installationType } ); return envs; } public Boolean updateProject( Map<String, Object> project ) throws Exception { distributedBuildService.updateProject( project ); log.debug( "Start updating project {}", ContinuumDistributedUtil.getProjectNameAndId( project ) ); return Boolean.TRUE; } public Boolean shouldBuild( Map<String, Object> context, String buildAgentUrl ) throws Exception { log.debug( "Checking if project {} should build in build agent {}", ContinuumDistributedUtil.getProjectNameAndId( context ), buildAgentUrl ); return distributedBuildService.shouldBuild( context ); } }
5,430
0
Create_ds/continuum/continuum-distributed/continuum-distributed-commons/src/main/java/org/apache/continuum/distributed/commons
Create_ds/continuum/continuum-distributed/continuum-distributed-commons/src/main/java/org/apache/continuum/distributed/commons/utils/ContinuumXmlRpcBinder.java
package org.apache.continuum.distributed.commons.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 com.atlassian.xmlrpc.Binder; import com.atlassian.xmlrpc.BinderTypeFactory; import com.atlassian.xmlrpc.BindingException; import com.atlassian.xmlrpc.ConnectionInfo; import com.atlassian.xmlrpc.ServiceObject; import com.atlassian.xmlrpc.XmlRpcClientProvider; import com.atlassian.xmlrpc.XmlRpcInvocationHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import java.lang.reflect.Proxy; import java.net.URL; import java.util.Vector; /** * Used to bind the given XML-RPC service to an instance of * the given interface type. * * This implementation uses the Apache XML-RPC client. * * This is derived from ApacheBinder from the atlassian-xmlrpc-binder project. In this version, we customise the * transport used for better connection management. It is thread-safe and should be reused. * * @author <a href="mailto:james@atlassian.com">James William Dumay</a> */ public class ContinuumXmlRpcBinder implements Binder { private final HttpClient httpClient; private static ContinuumXmlRpcBinder binder = new ContinuumXmlRpcBinder(); private ContinuumXmlRpcBinder() { this.httpClient = new HttpClient( new MultiThreadedHttpConnectionManager() ); } public <T> T bind( Class<T> bindClass, URL url ) throws BindingException { return bind( bindClass, url, new ConnectionInfo() ); } public <T> T bind( Class<T> bindClass, URL url, ConnectionInfo connectionInfo ) throws BindingException { if ( !bindClass.isInterface() ) { throw new BindingException( "Class " + bindClass.getName() + "is not an interface" ); } ServiceObject serviceObject = bindClass.getAnnotation( ServiceObject.class ); if ( serviceObject == null ) { throw new BindingException( "Could not find ServiceObject annotation on " + bindClass.getName() ); } final XmlRpcClient client = getXmlRpcClient( url, connectionInfo ); XmlRpcInvocationHandler handler = new XmlRpcInvocationHandler( new XmlRpcClientProvider() { public Object execute( String serviceName, String methodName, Vector arguments ) throws BindingException { try { return client.execute( serviceName + "." + methodName, arguments ); } catch ( XmlRpcException e ) { throw new BindingException( e ); } } } ); return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[]{bindClass}, handler ); } private XmlRpcClient getXmlRpcClient( URL url, ConnectionInfo connectionInfo ) { XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl(); clientConfig.setServerURL( url ); clientConfig.setEnabledForExceptions( true ); if ( connectionInfo != null ) { clientConfig.setBasicUserName( connectionInfo.getUsername() ); clientConfig.setBasicPassword( connectionInfo.getPassword() ); clientConfig.setBasicEncoding( connectionInfo.getEncoding() ); clientConfig.setGzipCompressing( connectionInfo.isGzip() ); clientConfig.setGzipRequesting( connectionInfo.isGzip() ); clientConfig.setReplyTimeout( connectionInfo.getTimeout() ); clientConfig.setConnectionTimeout( connectionInfo.getTimeout() ); clientConfig.setTimeZone( connectionInfo.getTimeZone() ); } final XmlRpcClient client = new XmlRpcClient(); client.setTypeFactory( new BinderTypeFactory( client ) ); XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory( client ); // Alternative - use simple connection manager, but make sure it closes the connection each time // This would be set here since it would not be thread-safe // factory.setHttpClient( new HttpClient( new SimpleHttpConnectionManager( true ) ) ); factory.setHttpClient( httpClient ); client.setConfig( clientConfig ); return client; } public static ContinuumXmlRpcBinder getInstance() { return binder; } }
5,431
0
Create_ds/continuum/continuum-distributed/continuum-distributed-commons/src/main/java/org/apache/continuum/distributed/commons
Create_ds/continuum/continuum-distributed/continuum-distributed-commons/src/main/java/org/apache/continuum/distributed/commons/utils/ContinuumDistributedUtil.java
package org.apache.continuum.distributed.commons.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 java.util.Map; /** * ContinuumDistributedUtil */ public class ContinuumDistributedUtil { public static final String KEY_PROJECT_ID = "project-id"; public static final String KEY_PROJECT_GROUP_ID = "project-group-id"; public static final String KEY_PROJECT_NAME = "project-name"; public static final String KEY_ARTIFACT_ID = "artifact-id"; public static int getProjectId( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_ID ); } public static int getProjectGroupId( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_GROUP_ID ); } public static String getArtifactId( Map<String, Object> context ) { return getString( context, KEY_ARTIFACT_ID ); } public static String getProjectName( Map<String, Object> context ) { return getString( context, KEY_PROJECT_NAME ); } public static String getProjectNameAndId( Map<String, Object> context ) { StringBuilder result = new StringBuilder(); if ( getProjectName( context ) != null ) { result.append( getProjectName( context ) ).append( " " ); } else if ( getArtifactId( context ) != null ) { result.append( getArtifactId( context ) ).append( " " ); } if ( context.containsKey( KEY_PROJECT_ID ) ) { result.append( "(projectId=" ).append( getProjectId( context ) ).append( ")" ); } else { result.append( "(projectGroupId=" ).append( getProjectGroupId( context ) ).append( ")" ); } return result.toString(); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private static String getString( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return null; } else { return (String) obj; } } private static int getInteger( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return 0; } else { return (Integer) obj; } } private static Object getObject( Map<String, Object> context, String key, Object defaultValue ) { Object value = context.get( key ); if ( value == null ) { return defaultValue; } return value; } }
5,432
0
Create_ds/continuum/continuum-distributed/continuum-distributed-tests/src/test/it/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-tests/src/test/it/org/apache/continuum/distributed/transport/tests/SlaveBuildAgentTransportServiceTest.java
package org.apache.continuum.distributed.transport.tests; /* * 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 junit.framework.TestCase; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.junit.Before; import org.junit.Test; import java.net.URL; import java.util.Collections; import static org.junit.Assert.*; /** * SlaveBuildAgentTransportServiceTest */ public class SlaveBuildAgentTransportServiceTest { private SlaveBuildAgentTransportService slaveProxy; private BeanFactory beanFactory = new XmlBeanFactory( new ClassPathResource( "applicationContext.xml" ) ); @Before protected void setUp() throws Exception { slaveProxy = new SlaveBuildAgentTransportClient( new URL( "http://localhost:9191/slave-xmlrpc" ), null, null ); } @Test public void testBuildProjects() { try { slaveProxy.buildProjects( Collections.EMPTY_LIST ); } catch ( Exception e ) { fail( e.getMessage() ); } } @Test public void testGetAvailableInstallations() { try { slaveProxy.getAvailableInstallations(); } catch ( Exception e ) { fail( e.getMessage() ); } } @Test public void testGetBuildResult() { try { slaveProxy.getBuildResult( 0 ); } catch ( Exception e ) { fail( e.getMessage() ); } } @Test public void testGetProjectCurrentlyBuilding() { try { slaveProxy.getProjectCurrentlyBuilding(); } catch ( Exception e ) { fail( e.getMessage() ); } } @Test public void testPing() { try { slaveProxy.ping(); } catch ( Exception e ) { fail( e.getMessage() ); } } @Test public void testExecuteDirectoryPurge() { try { slaveProxy.executeDirectoryPurge( "releases", 1, 2, false ); } catch ( Exception e ) { fail( e.getMessage() ); } } }
5,433
0
Create_ds/continuum/continuum-distributed/continuum-distributed-tests/src/test/it/org/apache/continuum/distributed/transport
Create_ds/continuum/continuum-distributed/continuum-distributed-tests/src/test/it/org/apache/continuum/distributed/transport/tests/MasterBuildAgentTransportServiceTest.java
package org.apache.continuum.distributed.transport.tests; /* * 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 junit.framework.TestCase; import org.apache.continuum.distributed.transport.master.MasterBuildAgentTransportClient; import org.apache.continuum.distributed.transport.master.MasterBuildAgentTransportService; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.junit.Before; import org.junit.Test; import java.net.URL; import java.util.HashMap; import static org.junit.Assert.*; /** * MasterBuildAgentTransportServiceTest */ public class MasterBuildAgentTransportServiceTest { private MasterBuildAgentTransportService masterProxy; private BeanFactory beanFactory = new XmlBeanFactory( new ClassPathResource( "applicationContext.xml" ) ); @Before public void setUp() throws Exception { masterProxy = new MasterBuildAgentTransportClient( new URL( "http://localhost:9191/master-xmlrpc" ), null, null ); } @Test public void testReturnBuildResult() { try { masterProxy.returnBuildResult( new HashMap<String, Object>(), /* ??? */ null ); } catch ( Exception e ) { fail( e.getMessage() ); } } /* this method apparently no longer exists in the interface @Test public void testReturnScmResult() { try { masterProxy.returnScmResult( new HashMap<String, Object>() ); } catch ( Exception e ) { fail( e.getMessage() ); } } */ @Test public void testPing() { try { masterProxy.ping(); } catch ( Exception e ) { fail( e.getMessage() ); } } }
5,434
0
Create_ds/continuum/continuum-distributed/continuum-distributed-tests/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-distributed/continuum-distributed-tests/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 Logger log = LoggerFactory.getLogger( getClass() ); /** * @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" ) ); } }
5,435
0
Create_ds/continuum/continuum-artifact-manager/src/main/java/org/apache/maven/artifact
Create_ds/continuum/continuum-artifact-manager/src/main/java/org/apache/maven/artifact/manager/DefaultWagonManager.java
package org.apache.maven.artifact.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.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.DefaultArtifactRepository; 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.events.TransferListener; import org.apache.maven.wagon.observers.ChecksumObserver; import org.apache.maven.wagon.proxy.ProxyInfo; import org.apache.maven.wagon.proxy.ProxyInfoProvider; import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.repository.RepositoryPermissions; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.logging.AbstractLogEnabled; 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.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class DefaultWagonManager extends AbstractLogEnabled implements WagonManager, Contextualizable, Initializable { private static final String WILDCARD = "*"; private static final String EXTERNAL_WILDCARD = "external:*"; private static final String MAVEN_ARTIFACT_PROPERTIES = "META-INF/maven/org.apache.maven/maven-artifact/pom.properties"; private static final String WAGON_PROVIDER_CONFIGURATION = "wagonProvider"; private static int anonymousMirrorIdSeed = 0; private PlexusContainer container; // TODO: proxies, authentication and mirrors are via settings, and should come in via an alternate method - perhaps // attached to ArtifactRepository before the method is called (so AR would be composed of WR, not inherit it) private Map proxies = new HashMap(); private Map authenticationInfoMap = new HashMap(); private Map serverPermissionsMap = new HashMap(); //used LinkedMap to preserve the order. private Map mirrors = new LinkedHashMap(); private Map<String, String> serverWagonProviderMap = new HashMap<String, String>(); private TransferListener downloadMonitor; private boolean online = true; private ArtifactRepositoryFactory repositoryFactory; private boolean interactive = true; private Map<String, PlexusContainer> availableWagons = new HashMap<String, PlexusContainer>(); private RepositoryPermissions defaultRepositoryPermissions; private String httpUserAgent; private WagonProviderMapping providerMapping = new DefaultWagonProviderMapping(); // TODO: this leaks the component in the public api - it is never released back to the container public Wagon getWagon( Repository repository ) throws UnsupportedProtocolException, WagonConfigurationException { String protocol = repository.getProtocol(); if ( protocol == null ) { throw new UnsupportedProtocolException( "The repository " + repository + " does not specify a protocol" ); } Wagon wagon = getWagon( protocol, repository.getId() ); return wagon; } public Wagon getWagon( String protocol ) throws UnsupportedProtocolException { return getWagon( protocol, null ); } private Wagon getWagon( String protocol, String repositoryId ) throws UnsupportedProtocolException { String hint = getWagonHint( protocol, repositoryId ); PlexusContainer container = getWagonContainer( hint ); Wagon wagon; try { wagon = (Wagon) container.lookup( Wagon.ROLE, hint ); } catch ( ComponentLookupException e1 ) { throw new UnsupportedProtocolException( "Cannot find wagon which supports the requested protocol: " + protocol, e1 ); } wagon.setInteractive( interactive ); return wagon; } private String getWagonHint( String protocol, String repositoryId ) { // TODO: Implement a better way to get the hint, via settings.xml or something. String impl = null; if ( repositoryId != null && serverWagonProviderMap.containsKey( repositoryId ) ) { impl = serverWagonProviderMap.get( repositoryId ); getLogger().debug( "Using Wagon implementation " + impl + " from settings for server " + repositoryId ); } else { impl = providerMapping.getWagonProvider( protocol ); if ( impl != null ) { getLogger().debug( "Using Wagon implementation " + impl + " from default mapping for protocol " + protocol ); } } String hint; if ( impl != null ) { hint = protocol + "-" + impl; PlexusContainer container = getWagonContainer( hint ); if ( container == null || !container.hasComponent( Wagon.ROLE, hint ) ) { getLogger().debug( "Cannot find wagon for protocol-provider hint: '" + hint + "', configured for repository: '" + repositoryId + "'. Using protocol hint: '" + protocol + "' instead." ); hint = protocol; } } else { hint = protocol; } return hint; } private PlexusContainer getWagonContainer( String hint ) { PlexusContainer container = this.container; if ( availableWagons.containsKey( hint ) ) { container = availableWagons.get( hint ); } return container; } public void putArtifact( File source, Artifact artifact, ArtifactRepository deploymentRepository ) throws TransferFailedException { putRemoteFile( deploymentRepository, source, deploymentRepository.pathOf( artifact ), downloadMonitor ); } public void putArtifactMetadata( File source, ArtifactMetadata artifactMetadata, ArtifactRepository repository ) throws TransferFailedException { getLogger().info( "Uploading " + artifactMetadata ); putRemoteFile( repository, source, repository.pathOfRemoteRepositoryMetadata( artifactMetadata ), null ); } private void putRemoteFile( ArtifactRepository repository, File source, String remotePath, TransferListener downloadMonitor ) throws TransferFailedException { failIfNotOnline(); String protocol = repository.getProtocol(); Wagon wagon; try { wagon = getWagon( protocol, repository.getId() ); } catch ( UnsupportedProtocolException e ) { throw new TransferFailedException( "Unsupported Protocol: '" + protocol + "': " + e.getMessage(), e ); } if ( downloadMonitor != null ) { wagon.addTransferListener( downloadMonitor ); } Map checksums = new HashMap( 2 ); Map sums = new HashMap( 2 ); // TODO: configure these on the repository try { ChecksumObserver checksumObserver = new ChecksumObserver( "MD5" ); wagon.addTransferListener( checksumObserver ); checksums.put( "md5", checksumObserver ); checksumObserver = new ChecksumObserver( "SHA-1" ); wagon.addTransferListener( checksumObserver ); checksums.put( "sha1", checksumObserver ); } catch ( NoSuchAlgorithmException e ) { throw new TransferFailedException( "Unable to add checksum methods: " + e.getMessage(), e ); } try { Repository artifactRepository = new Repository( repository.getId(), repository.getUrl() ); if ( serverPermissionsMap.containsKey( repository.getId() ) ) { RepositoryPermissions perms = (RepositoryPermissions) serverPermissionsMap.get( repository.getId() ); getLogger().debug( "adding permissions to wagon connection: " + perms.getFileMode() + " " + perms.getDirectoryMode() ); artifactRepository.setPermissions( perms ); } else { if ( defaultRepositoryPermissions != null ) { artifactRepository.setPermissions( defaultRepositoryPermissions ); } else { getLogger().debug( "not adding permissions to wagon connection" ); } } wagon.connect( artifactRepository, getAuthenticationInfo( repository.getId() ), new ProxyInfoProvider() { public ProxyInfo getProxyInfo( String protocol ) { return getProxy( protocol ); } }); wagon.put( source, remotePath ); wagon.removeTransferListener( downloadMonitor ); // Pre-store the checksums as any future puts will overwrite them for ( Iterator i = checksums.keySet().iterator(); i.hasNext(); ) { String extension = (String) i.next(); ChecksumObserver observer = (ChecksumObserver) checksums.get( extension ); sums.put( extension, observer.getActualChecksum() ); } // We do this in here so we can checksum the artifact metadata too, otherwise it could be metadata itself for ( Iterator i = checksums.keySet().iterator(); i.hasNext(); ) { String extension = (String) i.next(); // TODO: shouldn't need a file intermediatary - improve wagon to take a stream File temp = File.createTempFile( "maven-artifact", null ); temp.deleteOnExit(); FileUtils.fileWrite( temp.getAbsolutePath(), "UTF-8", (String) sums.get( extension ) ); wagon.put( temp, remotePath + "." + extension ); } } catch ( ConnectionException e ) { throw new TransferFailedException( "Connection failed: " + e.getMessage(), e ); } catch ( AuthenticationException e ) { throw new TransferFailedException( "Authentication failed: " + e.getMessage(), e ); } catch ( AuthorizationException e ) { throw new TransferFailedException( "Authorization failed: " + e.getMessage(), e ); } catch ( ResourceDoesNotExistException e ) { throw new TransferFailedException( "Resource to deploy not found: " + e.getMessage(), e ); } catch ( IOException e ) { throw new TransferFailedException( "Error creating temporary file for deployment: " + e.getMessage(), e ); } finally { disconnectWagon( wagon ); releaseWagon( protocol, wagon, repository.getId() ); } } public void getArtifact( Artifact artifact, List remoteRepositories ) throws TransferFailedException, ResourceDoesNotExistException { // TODO [BP]: The exception handling here needs some work boolean successful = false; for ( Iterator iter = remoteRepositories.iterator(); iter.hasNext() && !successful; ) { ArtifactRepository repository = (ArtifactRepository) iter.next(); try { getArtifact( artifact, repository ); successful = artifact.isResolved(); } catch ( ResourceDoesNotExistException e ) { // This one we will eat when looking through remote repositories // because we want to cycle through them all before squawking. getLogger().info( "Unable to find resource '" + artifact.getId() + "' in repository " + repository.getId() + " (" + repository.getUrl() + ")" ); } catch ( TransferFailedException e ) { getLogger().warn( "Unable to get resource '" + artifact.getId() + "' from repository " + repository.getId() + " (" + repository.getUrl() + "): " + e.getMessage() ); } } // if it already exists locally we were just trying to force it - ignore the update if ( !successful && !artifact.getFile().exists() ) { throw new ResourceDoesNotExistException( "Unable to download the artifact from any repository" ); } } public void getArtifact( Artifact artifact, ArtifactRepository repository ) throws TransferFailedException, ResourceDoesNotExistException { String remotePath = repository.pathOf( artifact ); ArtifactRepositoryPolicy policy = artifact.isSnapshot() ? repository.getSnapshots() : repository.getReleases(); if ( !policy.isEnabled() ) { getLogger().debug( "Skipping disabled repository " + repository.getId() ); } else if ( repository.isBlacklisted() ) { getLogger().debug( "Skipping blacklisted repository " + repository.getId() ); } else { getLogger().debug( "Trying repository " + repository.getId() ); getRemoteFile( getMirrorRepository( repository ), artifact.getFile(), remotePath, downloadMonitor, policy.getChecksumPolicy(), false ); getLogger().debug( " Artifact resolved" ); artifact.setResolved( true ); } } public void getArtifactMetadata( ArtifactMetadata metadata, ArtifactRepository repository, File destination, String checksumPolicy ) throws TransferFailedException, ResourceDoesNotExistException { String remotePath = repository.pathOfRemoteRepositoryMetadata( metadata ); getRemoteFile( getMirrorRepository( repository ), destination, remotePath, null, checksumPolicy, true ); } public void getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository repository, File destination, String checksumPolicy ) throws TransferFailedException, ResourceDoesNotExistException { String remotePath = repository.pathOfRemoteRepositoryMetadata( metadata ); getRemoteFile( repository, destination, remotePath, null, checksumPolicy, true ); } private void getRemoteFile( ArtifactRepository repository, File destination, String remotePath, TransferListener downloadMonitor, String checksumPolicy, boolean force ) throws TransferFailedException, ResourceDoesNotExistException { // TODO: better excetpions - transfer failed is not enough? failIfNotOnline(); String protocol = repository.getProtocol(); Wagon wagon; try { wagon = getWagon( protocol, repository.getId() ); } catch ( UnsupportedProtocolException e ) { throw new TransferFailedException( "Unsupported Protocol: '" + protocol + "': " + e.getMessage(), e ); } if ( downloadMonitor != null ) { wagon.addTransferListener( downloadMonitor ); } File temp = new File( destination + ".tmp" ); temp.deleteOnExit(); boolean downloaded = false; try { getLogger().debug( "Connecting to repository: \'" + repository.getId() + "\' with url: \'" + repository.getUrl() + "\'." ); wagon.connect( new Repository( repository.getId(), repository.getUrl() ), getAuthenticationInfo( repository.getId() ), new ProxyInfoProvider() { public ProxyInfo getProxyInfo( String protocol ) { return getProxy( protocol ); } }); boolean firstRun = true; boolean retry = true; // this will run at most twice. The first time, the firstRun flag is turned off, and if the retry flag // is set on the first run, it will be turned off and not re-set on the second try. This is because the // only way the retry flag can be set is if ( firstRun == true ). while ( firstRun || retry ) { // reset the retry flag. retry = false; // TODO: configure on repository ChecksumObserver md5ChecksumObserver = null; ChecksumObserver sha1ChecksumObserver = null; try { md5ChecksumObserver = new ChecksumObserver( "MD5" ); wagon.addTransferListener( md5ChecksumObserver ); sha1ChecksumObserver = new ChecksumObserver( "SHA-1" ); wagon.addTransferListener( sha1ChecksumObserver ); // This should take care of creating destination directory now on if ( destination.exists() && !force ) { try { downloaded = wagon.getIfNewer( remotePath, temp, destination.lastModified() ); if ( !downloaded ) { // prevent additional checks of this artifact until it expires again destination.setLastModified( System.currentTimeMillis() ); } } catch ( UnsupportedOperationException e ) { // older wagons throw this. Just get() instead wagon.get( remotePath, temp ); downloaded = true; } } else { wagon.get( remotePath, temp ); downloaded = true; } } catch ( NoSuchAlgorithmException e ) { throw new TransferFailedException( "Unable to add checksum methods: " + e.getMessage(), e ); } finally { if ( md5ChecksumObserver != null ) { wagon.removeTransferListener( md5ChecksumObserver ); } if ( sha1ChecksumObserver != null ) { wagon.removeTransferListener( sha1ChecksumObserver ); } } if ( downloaded ) { // keep the checksum files from showing up on the download monitor... if ( downloadMonitor != null ) { wagon.removeTransferListener( downloadMonitor ); } // try to verify the SHA-1 checksum for this file. try { verifyChecksum( sha1ChecksumObserver, destination, temp, remotePath, ".sha1", wagon ); } catch ( ChecksumFailedException e ) { // if we catch a ChecksumFailedException, it means the transfer/read succeeded, but the checksum // doesn't match. This could be a problem with the server (ibiblio HTTP-200 error page), so we'll // try this up to two times. On the second try, we'll handle it as a bona-fide error, based on the // repository's checksum checking policy. if ( firstRun ) { getLogger().warn( "*** CHECKSUM FAILED - " + e.getMessage() + " - RETRYING" ); retry = true; } else { handleChecksumFailure( checksumPolicy, e.getMessage(), e.getCause() ); } } catch ( ResourceDoesNotExistException sha1TryException ) { getLogger().debug( "SHA1 not found, trying MD5", sha1TryException ); // if this IS NOT a ChecksumFailedException, it was a problem with transfer/read of the checksum // file...we'll try again with the MD5 checksum. try { verifyChecksum( md5ChecksumObserver, destination, temp, remotePath, ".md5", wagon ); } catch ( ChecksumFailedException e ) { // if we also fail to verify based on the MD5 checksum, and the checksum transfer/read // succeeded, then we need to determine whether to retry or handle it as a failure. if ( firstRun ) { retry = true; } else { handleChecksumFailure( checksumPolicy, e.getMessage(), e.getCause() ); } } catch ( ResourceDoesNotExistException md5TryException ) { // this was a failed transfer, and we don't want to retry. handleChecksumFailure( checksumPolicy, "Error retrieving checksum file for " + remotePath, md5TryException ); } } // reinstate the download monitor... if ( downloadMonitor != null ) { wagon.addTransferListener( downloadMonitor ); } } // unset the firstRun flag, so we don't get caught in an infinite loop... firstRun = false; } } catch ( ConnectionException e ) { throw new TransferFailedException( "Connection failed: " + e.getMessage(), e ); } catch ( AuthenticationException e ) { throw new TransferFailedException( "Authentication failed: " + e.getMessage(), e ); } catch ( AuthorizationException e ) { throw new TransferFailedException( "Authorization failed: " + e.getMessage(), e ); } finally { disconnectWagon( wagon ); releaseWagon( protocol, wagon, repository.getId() ); } if ( downloaded ) { if ( !temp.exists() ) { throw new ResourceDoesNotExistException( "Downloaded file does not exist: " + temp ); } // The temporary file is named destination + ".tmp" and is done this way to ensure // that the temporary file is in the same file system as the destination because the // File.renameTo operation doesn't really work across file systems. // So we will attempt to do a File.renameTo for efficiency and atomicity, if this fails // then we will use a brute force copy and delete the temporary file. if ( !temp.renameTo( destination ) ) { try { FileUtils.copyFile( temp, destination ); temp.delete(); } catch ( IOException e ) { throw new TransferFailedException( "Error copying temporary file to the final destination: " + e.getMessage(), e ); } } } } public ArtifactRepository getMirrorRepository( ArtifactRepository repository ) { ArtifactRepository mirror = getMirror( repository ); if ( mirror != null ) { String id = mirror.getId(); if ( id == null ) { // TODO: this should be illegal in settings.xml id = repository.getId(); } getLogger().debug( "Using mirror: " + mirror.getUrl() + " (id: " + id + ")" ); repository = repositoryFactory.createArtifactRepository( id, mirror.getUrl(), repository.getLayout(), repository.getSnapshots(), repository.getReleases() ); } return repository; } private void failIfNotOnline() throws TransferFailedException { if ( !isOnline() ) { throw new TransferFailedException( "System is offline." ); } } private void handleChecksumFailure( String checksumPolicy, String message, Throwable cause ) throws ChecksumFailedException { if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals( checksumPolicy ) ) { throw new ChecksumFailedException( message, cause ); } else if ( !ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals( checksumPolicy ) ) { // warn if it is set to anything other than ignore getLogger().warn( "*** CHECKSUM FAILED - " + message + " - IGNORING" ); } // otherwise it is ignore } private void verifyChecksum( ChecksumObserver checksumObserver, File destination, File tempDestination, String remotePath, String checksumFileExtension, Wagon wagon ) throws ResourceDoesNotExistException, TransferFailedException, AuthorizationException { try { // grab it first, because it's about to change... String actualChecksum = checksumObserver.getActualChecksum(); File tempChecksumFile = new File( tempDestination + checksumFileExtension + ".tmp" ); tempChecksumFile.deleteOnExit(); wagon.get( remotePath + checksumFileExtension, tempChecksumFile ); String expectedChecksum = FileUtils.fileRead( tempChecksumFile, "UTF-8" ); // remove whitespaces at the end expectedChecksum = expectedChecksum.trim(); // check for 'ALGO (name) = CHECKSUM' like used by openssl if ( expectedChecksum.regionMatches( true, 0, "MD", 0, 2 ) || expectedChecksum.regionMatches( true, 0, "SHA", 0, 3 ) ) { int lastSpacePos = expectedChecksum.lastIndexOf( ' ' ); expectedChecksum = expectedChecksum.substring( lastSpacePos + 1 ); } else { // remove everything after the first space (if available) int spacePos = expectedChecksum.indexOf( ' ' ); if ( spacePos != -1 ) { expectedChecksum = expectedChecksum.substring( 0, spacePos ); } } if ( expectedChecksum.equalsIgnoreCase( actualChecksum ) ) { File checksumFile = new File( destination + checksumFileExtension ); if ( checksumFile.exists() ) { checksumFile.delete(); } FileUtils.copyFile( tempChecksumFile, checksumFile ); } else { throw new ChecksumFailedException( "Checksum failed on download: local = '" + actualChecksum + "'; remote = '" + expectedChecksum + "'" ); } } catch ( IOException e ) { throw new ChecksumFailedException( "Invalid checksum file", e ); } } private void disconnectWagon( Wagon wagon ) { try { wagon.disconnect(); } catch ( ConnectionException e ) { getLogger().error( "Problem disconnecting from wagon - ignoring: " + e.getMessage() ); } } private void releaseWagon( String protocol, Wagon wagon, String repositoryId ) { String hint = getWagonHint( protocol, repositoryId ); PlexusContainer container = getWagonContainer( hint ); try { container.release( wagon ); } catch ( ComponentLifecycleException e ) { getLogger().error( "Problem releasing wagon - ignoring: " + e.getMessage() ); } } public ProxyInfo getProxy( String protocol ) { ProxyInfo info = (ProxyInfo) proxies.get( protocol ); if ( info != null ) { getLogger().debug( "Using Proxy: " + info.getHost() ); } return info; } public AuthenticationInfo getAuthenticationInfo( String id ) { return (AuthenticationInfo) authenticationInfoMap.get( id ); } /** * This method finds a matching mirror for the selected repository. If there is an exact match, this will be used. * If there is no exact match, then the list of mirrors is examined to see if a pattern applies. * * @param originalRepository See if there is a mirror for this repository. * @return the selected mirror or null if none are found. */ public ArtifactRepository getMirror( ArtifactRepository originalRepository ) { ArtifactRepository selectedMirror = (ArtifactRepository) mirrors.get( originalRepository.getId() ); if ( null == selectedMirror ) { // Process the patterns in order. First one that matches wins. Set keySet = mirrors.keySet(); if ( keySet != null ) { Iterator iter = keySet.iterator(); while ( iter.hasNext() ) { String pattern = (String) iter.next(); if ( matchPattern( originalRepository, pattern ) ) { selectedMirror = (ArtifactRepository) mirrors.get( pattern ); break; } } } } return selectedMirror; } /** * This method checks if the pattern matches the originalRepository. * Valid patterns: * * = everything * external:* = everything not on the localhost and not file based. * repo,repo1 = repo or repo1 * *,!repo1 = everything except repo1 * * @param originalRepository to compare for a match. * @param pattern used for match. Currently only '*' is supported. * @return true if the repository is a match to this pattern. */ public boolean matchPattern( ArtifactRepository originalRepository, String pattern ) { boolean result = false; String originalId = originalRepository.getId(); // simple checks first to short circuit processing below. if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) ) { result = true; } else { // process the list String[] repos = pattern.split( "," ); for ( int i = 0; i < repos.length; i++ ) { String repo = repos[i]; // see if this is a negative match if ( repo.length() > 1 && repo.startsWith( "!" ) ) { if ( originalId.equals( repo.substring( 1 ) ) ) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match else if ( originalId.equals( repo ) ) { result = true; break; } // check for external:* else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( originalRepository ) ) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } else if ( WILDCARD.equals( repo ) ) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } } } return result; } /** * Checks the URL to see if this repository refers to an external repository * * @param originalRepository * @return true if external. */ public boolean isExternalRepo( ArtifactRepository originalRepository ) { try { URL url = new URL( originalRepository.getUrl() ); return !( url.getHost().equals( "localhost" ) || url.getHost().equals( "127.0.0.1" ) || url.getProtocol().equals( "file" ) ); } catch ( MalformedURLException e ) { // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it return false; } } /** * Set the proxy used for a particular protocol. * * @param protocol the protocol (required) * @param host the proxy host name (required) * @param port the proxy port (required) * @param username the username for the proxy, or null if there is none * @param password the password for the proxy, or null if there is none * @param nonProxyHosts the set of hosts not to use the proxy for. Follows Java system property format: * <code>*.foo.com|localhost</code>. * @todo [BP] would be nice to configure this via plexus in some way */ public void addProxy( String protocol, String host, int port, String username, String password, String nonProxyHosts ) { ProxyInfo proxyInfo = new ProxyInfo(); proxyInfo.setHost( host ); proxyInfo.setType( protocol ); proxyInfo.setPort( port ); proxyInfo.setNonProxyHosts( nonProxyHosts ); proxyInfo.setUserName( username ); proxyInfo.setPassword( password ); proxies.put( protocol, proxyInfo ); } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } /** @todo I'd rather not be setting this explicitly. */ public void setDownloadMonitor( TransferListener downloadMonitor ) { this.downloadMonitor = downloadMonitor; } public void addAuthenticationInfo( String repositoryId, String username, String password, String privateKey, String passphrase ) { AuthenticationInfo authInfo = new AuthenticationInfo(); authInfo.setUserName( username ); authInfo.setPassword( password ); authInfo.setPrivateKey( privateKey ); authInfo.setPassphrase( passphrase ); authenticationInfoMap.put( repositoryId, authInfo ); } public void addPermissionInfo( String repositoryId, String filePermissions, String directoryPermissions ) { RepositoryPermissions permissions = new RepositoryPermissions(); boolean addPermissions = false; if ( filePermissions != null ) { permissions.setFileMode( filePermissions ); addPermissions = true; } if ( directoryPermissions != null ) { permissions.setDirectoryMode( directoryPermissions ); addPermissions = true; } if ( addPermissions ) { serverPermissionsMap.put( repositoryId, permissions ); } } public void addMirror( String id, String mirrorOf, String url ) { if ( id == null ) { id = "mirror-" + anonymousMirrorIdSeed++; getLogger().warn( "You are using a mirror that doesn't declare an <id/> element. Using \'" + id + "\' instead:\nId: " + id + "\nmirrorOf: " + mirrorOf + "\nurl: " + url + "\n" ); } ArtifactRepository mirror = new DefaultArtifactRepository( id, url, null ); //to preserve first wins, don't add repeated mirrors. if (!mirrors.containsKey( mirrorOf )) { mirrors.put( mirrorOf, mirror ); } } public void setOnline( boolean online ) { this.online = online; } public boolean isOnline() { return online; } public void setInteractive( boolean interactive ) { this.interactive = interactive; } @SuppressWarnings( "unchecked" ) public void registerWagons( Collection wagons, PlexusContainer extensionContainer ) { for ( Iterator<String> i = wagons.iterator(); i.hasNext(); ) { availableWagons.put( i.next(), extensionContainer ); } } public void addConfiguration( String repositoryId, Xpp3Dom configuration ) { if ( repositoryId == null || configuration == null ) { throw new IllegalArgumentException( "arguments can't be null" ); } getLogger().warn( "Unsupported configuration: " + configuration + " for repository " + repositoryId ); } public void setDefaultRepositoryPermissions( RepositoryPermissions defaultRepositoryPermissions ) { this.defaultRepositoryPermissions = defaultRepositoryPermissions; } // TODO: Remove this, once the maven-shade-plugin 1.2 release is out, allowing configuration of httpHeaders in the components.xml public void initialize() throws InitializationException { if ( httpUserAgent == null ) { InputStream resourceAsStream = null; try { Properties properties = new Properties(); resourceAsStream = getClass().getClassLoader().getResourceAsStream( MAVEN_ARTIFACT_PROPERTIES ); if ( resourceAsStream != null ) { try { properties.load( resourceAsStream ); httpUserAgent = "maven-artifact/" + properties.getProperty( "version" ) + " (Java " + System.getProperty( "java.version" ) + "; " + System.getProperty( "os.name" ) + " " + System.getProperty( "os.version" ) + ")"; } catch ( IOException e ) { getLogger().warn( "Failed to load Maven artifact properties from:\n" + MAVEN_ARTIFACT_PROPERTIES + "\n\nUser-Agent HTTP header may be incorrect for artifact resolution." ); } } } finally { IOUtil.close( resourceAsStream ); } } } /** * {@inheritDoc} */ public void setHttpUserAgent( String userAgent ) { this.httpUserAgent = userAgent; } /** * {@inheritDoc} */ public String getHttpUserAgent() { return httpUserAgent; } }
5,436
0
Create_ds/continuum/continuum-commons/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/test/java/org/apache/maven/continuum/configuration/ConfigurationServiceTest.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.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.utils.file.DefaultFileSystemManager; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.PlexusSpringTestCase; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import static org.junit.Assert.*; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public class ConfigurationServiceTest extends PlexusSpringTestCase { private static final Logger log = LoggerFactory.getLogger( ConfigurationServiceTest.class ); private static final String confFile = "target/test-classes/conf/continuum.xml"; private FileSystemManager fsManager; @Override protected void preContextStart() throws IOException { fsManager = new DefaultFileSystemManager(); // can't lookup, before setup File originalConf = new File( getBasedir(), "src/test/resources/conf/continuum.xml" ); File confUsed = new File( getBasedir(), confFile ); if ( confUsed.exists() ) { confUsed.delete(); } fsManager.copyFile( originalConf, confUsed ); } @Test public void testLoad() throws Exception { ConfigurationService service = (ConfigurationService) lookup( "configurationService" ); assertNotNull( service ); assertNotNull( service.getUrl() ); assertEquals( "http://test", service.getUrl() ); log.info( "myBuildOutputDir " + new File( getBasedir(), "target/myBuildOutputDir" ).getAbsolutePath() ); log.info( "getBuildOutputDirectory " + service.getBuildOutputDirectory().getAbsolutePath() ); assertEquals( new File( getBasedir(), "target/myBuildOutputDir" ).getAbsolutePath(), service.getBuildOutputDirectory().getAbsolutePath() ); } @Test public void testConfigurationService() throws Exception { File conf = new File( getBasedir(), confFile ); if ( conf.exists() ) { conf.delete(); } ConfigurationService service = (ConfigurationService) lookup( "configurationService" ); assertNotNull( service ); assertEquals( "check # build agents", 1, service.getBuildAgents().size() ); service.setUrl( "http://test/zloug" ); service.setBuildOutputDirectory( new File( "testBuildOutputDir" ) ); BuildAgentConfiguration buildAgent = new BuildAgentConfiguration( "http://test/xmlrpc", "windows", false ); service.addBuildAgent( buildAgent ); service.store(); fsManager.fileContents( conf ); service.reload(); assertEquals( "http://test/zloug", service.getUrl() ); assertEquals( "check # build agents", 2, service.getBuildAgents().size() ); assertEquals( "http://test/xmlrpc", service.getBuildAgents().get( 1 ).getUrl() ); assertEquals( "windows", service.getBuildAgents().get( 1 ).getDescription() ); assertFalse( service.getBuildAgents().get( 1 ).isEnabled() ); assertEquals( "http://test/xmlrpc", buildAgent.getUrl() ); service.removeBuildAgent( buildAgent ); service.store(); service.reload(); assertEquals( "check # build agents", 1, service.getBuildAgents().size() ); assertEquals( "http://buildagent/xmlrpc", service.getBuildAgents().get( 0 ).getUrl() ); assertEquals( "linux", service.getBuildAgents().get( 0 ).getDescription() ); assertTrue( service.getBuildAgents().get( 0 ).isEnabled() ); BuildAgentGroupConfiguration buildAgentGroup = new BuildAgentGroupConfiguration(); buildAgentGroup.setName( "group-1" ); buildAgentGroup.addBuildAgent( buildAgent ); service.addBuildAgentGroup( buildAgentGroup ); service.store(); service.reload(); assertEquals( "check # build agent groups", 1, service.getBuildAgentGroups().size() ); assertEquals( "group-1", service.getBuildAgentGroups().get( 0 ).getName() ); assertEquals( "windows", service.getBuildAgentGroups().get( 0 ).getBuildAgents().get( 0 ).getDescription() ); BuildAgentConfiguration buildAgent2 = new BuildAgentConfiguration( "http://machine-1/xmlrpc", "node-1", true ); //buildAgentGroup.addBuildAgent( buildAgent2 ); service.addBuildAgent( buildAgentGroup, buildAgent2 ); service.store(); service.reload(); assertEquals( "check # build agent groups", 1, service.getBuildAgentGroups().size() ); assertEquals( "check # build agent groups", 2, service.getBuildAgentGroups().get( 0 ).getBuildAgents().size() ); assertEquals( "group-1", service.getBuildAgentGroups().get( 0 ).getName() ); assertEquals( "windows", service.getBuildAgentGroups().get( 0 ).getBuildAgents().get( 0 ).getDescription() ); assertEquals( "http://machine-1/xmlrpc", service.getBuildAgentGroups().get( 0 ).getBuildAgents().get( 1 ).getUrl() ); assertEquals( "node-1", service.getBuildAgentGroups().get( 0 ).getBuildAgents().get( 1 ).getDescription() ); assertEquals( true, service.getBuildAgentGroups().get( 0 ).getBuildAgents().get( 1 ).isEnabled() ); service.removeBuildAgent( buildAgentGroup, buildAgent2 ); service.store(); service.reload(); assertEquals( "check # build agent groups", 1, service.getBuildAgentGroups().size() ); assertEquals( "group-1", service.getBuildAgentGroups().get( 0 ).getName() ); assertEquals( "windows", service.getBuildAgentGroups().get( 0 ).getBuildAgents().get( 0 ).getDescription() ); assertNull( service.getSharedSecretPassword() ); service.setSharedSecretPassword( "password" ); service.store(); service.reload(); assertEquals( "password", service.getSharedSecretPassword() ); } @Test public void testAddDuplicateBuildAgentUrl() throws Exception { ConfigurationService service = (ConfigurationService) lookup( "configurationService" ); assertNotNull( service ); BuildAgentConfiguration buildAgent = new BuildAgentConfiguration( "http://agent1/xmlrpc ", "windows", false ); service.addBuildAgent( buildAgent ); service.store(); service.reload(); assertEquals( "check # build agents", 2, service.getBuildAgents().size() ); assertNotNull( service.getBuildAgent( "http://agent1/xmlrpc" ) ); BuildAgentConfiguration buildAgent2 = new BuildAgentConfiguration( "http://agent1/xmlrpc", "windows", false ); try { service.addBuildAgent( buildAgent2 ); fail( "Should have thrown an exception because of duplicate agent url" ); } catch ( ConfigurationException e ) { assertEquals( "Unable to add build agent: build agent already exist", e.getMessage() ); } service.removeBuildAgent( buildAgent ); service.store(); } }
5,437
0
Create_ds/continuum/continuum-commons/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/test/java/org/apache/maven/continuum/utils/ContinuumUrlValidatorTest.java
package org.apache.maven.continuum.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.maven.continuum.PlexusSpringTestCase; import org.junit.Test; import java.io.File; import static org.junit.Assert.*; /** * @author <a href="mailto:olamy@apache.org">olamy</a> */ public class ContinuumUrlValidatorTest extends PlexusSpringTestCase { protected ContinuumUrlValidator getContinuumUrlValidator() throws Exception { return getContinuumUrlValidator( "continuumUrl" ); } protected ContinuumUrlValidator getContinuumUrlValidator( String roleHint ) throws Exception { return lookup( ContinuumUrlValidator.class, roleHint ); } @Test public void testSuccessHttp() throws Exception { assertTrue( getContinuumUrlValidator().validate( "http://svn.apache.org/repos/asf/continuum/trunk/pom.xml" ) ); } @Test public void testFailureHttp() throws Exception { assertFalse( getContinuumUrlValidator().validate( "ttp://svn.apache.org/repos/asf/continuum/trunk/pom.xml" ) ); } @Test public void testSuccessHttpWithAuth() throws Exception { assertTrue( getContinuumUrlValidator().validate( "https://username:password@svn.apache.org/repos/asf/continuum/trunk/pom.xml" ) ); } @Test public void testFailureHttpWithAuth() throws Exception { assertTrue( getContinuumUrlValidator().validate( "http://username:passwordsvn.apache.org/repos/asf/continuum/trunk/pom.xml" ) ); } @Test public void testFailureHttpWithFile() throws Exception { assertFalse( getContinuumUrlValidator( "continuumUrlWithoutFile" ).validate( "file:///home/zloug/pom.xml" ) ); } @Test public void testSuccessHttps() throws Exception { assertTrue( getContinuumUrlValidator().validate( "https://svn.apache.org/repos/asf/continuum/trunk/pom.xml" ) ); } @Test public void testSuccessHttpsWithAuth() throws Exception { assertTrue( getContinuumUrlValidator().validate( "https://username:password@svn.apache.org/repos/asf/continuum/trunk/pom.xml" ) ); } @Test public void testSuccessHttpviewvc() throws Exception { assertTrue( getContinuumUrlValidator().validate( "http://svn.apache.org/viewvc/continuum/trunk/pom.xml?revision=681492&content-type=text%2Fplain" ) ); } @Test public void testSuccessHttpviewvcWithAuth() throws Exception { assertTrue( getContinuumUrlValidator().validate( "http://username:password@svn.apache.org/viewvc/continuum/trunk/pom.xml?revision=681492&content-type=text%2Fplain" ) ); } @Test public void testSuccessHttpsviewvc() throws Exception { assertTrue( getContinuumUrlValidator().validate( "https://svn.apache.org/viewvc/continuum/trunk/pom.xml?revision=681492&content-type=text%2Fplain" ) ); } @Test public void testSuccessHttpsviewvcWithAuth() throws Exception { assertTrue( getContinuumUrlValidator().validate( "https://username:password@svn.apache.org/viewvc/continuum/trunk/pom.xml?revision=681492&content-type=text%2Fplain" ) ); } @Test public void testSuccessHttpfisheye() throws Exception { assertTrue( getContinuumUrlValidator().validate( "http://fisheye6.atlassian.com/browse/~raw,r=680040/continuum/trunk/pom.xml" ) ); } @Test public void testSuccessHttpsfisheye() throws Exception { assertTrue( getContinuumUrlValidator().validate( "https://fisheye6.atlassian.com/browse/~raw,r=680040/continuum/trunk/pom.xml" ) ); } @Test public void testValidateFile() throws Exception { File rootPom = getTestFile( "src/test/resources/META-INF/continuum/continuum-configuration.xml" ); assertTrue( rootPom.exists() ); assertTrue( getContinuumUrlValidator().validate( rootPom.toURL().toExternalForm() ) ); } @Test public void testExtractUserNamePwd() throws Exception { ContinuumUrlValidator continuumUrlValidator = new ContinuumUrlValidator(); URLUserInfo usrInfo = continuumUrlValidator.extractURLUserInfo( "https://username:password@svn.apache.org/repos/asf/continuum/trunk/pom.xml" ); assertEquals( "username", usrInfo.getUsername() ); assertEquals( "password", usrInfo.getPassword() ); } @Test public void testExtractUserNameEmptyPwd() throws Exception { ContinuumUrlValidator continuumUrlValidator = new ContinuumUrlValidator(); URLUserInfo usrInfo = continuumUrlValidator.extractURLUserInfo( "https://username@svn.apache.org/repos/asf/continuum/trunk/pom.xml" ); assertEquals( "username", usrInfo.getUsername() ); assertNull( usrInfo.getPassword() ); } @Test public void testExtractEmptyUserNameEmptyPwd() throws Exception { ContinuumUrlValidator continuumUrlValidator = new ContinuumUrlValidator(); URLUserInfo usrInfo = continuumUrlValidator.extractURLUserInfo( "https://svn.apache.org/repos/asf/continuum/trunk/pom.xml" ); assertNull( usrInfo.getUsername() ); assertNull( usrInfo.getPassword() ); } }
5,438
0
Create_ds/continuum/continuum-commons/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/test/java/org/apache/maven/continuum/utils/DefaultWorkingDirectoryServiceTest.java
package org.apache.maven.continuum.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.maven.continuum.PlexusSpringTestCase; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.Project; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a> */ public class DefaultWorkingDirectoryServiceTest extends PlexusSpringTestCase { private DefaultWorkingDirectoryService workingDirectoryService; private ConfigurationService configurationService; private File baseWorkingDirectory; @Before public void setUp() throws Exception { configurationService = mock( ConfigurationService.class ); baseWorkingDirectory = new File( getBasedir(), "target" + File.separator + "working-directory" ); when( configurationService.getWorkingDirectory() ).thenReturn( baseWorkingDirectory ); workingDirectoryService = (DefaultWorkingDirectoryService) lookup( WorkingDirectoryService.class ); workingDirectoryService.setConfigurationService( configurationService ); } private Project createProject( int id, String groupId, String artifactId, String version, String scmUrl, boolean checkedOutInSingleDirectory ) { Project project = new Project(); project.setId( id ); project.setGroupId( groupId ); project.setArtifactId( artifactId ); project.setVersion( version ); project.setScmUrl( scmUrl ); project.setCheckedOutInSingleDirectory( checkedOutInSingleDirectory ); return project; } @Test public void testGetWorkingDirectoryOfSingleCheckoutFlatMultiModules() throws Exception { List<Project> projects = new ArrayList<Project>(); Project project = createProject( 7, "org.apache.continuum", "module-a", "1.0-SNAPSHOT", "scm:local:src/test-projects:flat-multi-module/module-a", true ); projects.add( project ); projects.add( createProject( 8, "org.apache.continuum", "module-b", "1.0-SNAPSHOT", "scm:local:src/test-projects:flat-multi-module/module-b", true ) ); projects.add( createProject( 6, "org.apache.continuum", "parent-project", "1.0-SNAPSHOT", "scm:local:src/test-projects:flat-multi-module/parent-project", true ) ); File projectWorkingDirectory = workingDirectoryService.getWorkingDirectory( project, "scm:local:src/test-projects:flat-multi-module", projects ); assertEquals( "Incorrect working directory for flat multi-module project", baseWorkingDirectory + File.separator + "6" + File.separator + "module-a", projectWorkingDirectory.getPath() ); // test if separator is appended at the end of the scm root url projectWorkingDirectory = workingDirectoryService.getWorkingDirectory( project, "scm:local:src/test-projects:flat-multi-module/", projects ); assertEquals( "Incorrect working directory for flat multi-module project", baseWorkingDirectory + File.separator + "6" + File.separator + "module-a", projectWorkingDirectory.getPath() ); } @Test public void testGetWorkingDirectoryOfSingleCheckoutRegularMultiModules() throws Exception { List<Project> projects = new ArrayList<Project>(); Project project = createProject( 10, "org.apache.continuum", "module-a", "1.0-SNAPSHOT", "scm:local:src/test-projects:regular-multi-module/module-a", true ); projects.add( project ); projects.add( createProject( 11, "org.apache.continuum", "module-b", "1.0-SNAPSHOT", "scm:local:src/test-projects:regular-multi-module/module-b", true ) ); projects.add( createProject( 9, "org.apache.continuum", "parent-project", "1.0-SNAPSHOT", "scm:local:src/test-projects:regular-multi-module/", true ) ); File projectWorkingDirectory = workingDirectoryService.getWorkingDirectory( project, "scm:local:src/test-projects:regular-multi-module", projects ); assertEquals( "Incorrect working directory for regular multi-module project", baseWorkingDirectory + File.separator + "9" + File.separator + "module-a", projectWorkingDirectory.getPath() ); // test if separator is appended at the end of the scm root url projectWorkingDirectory = workingDirectoryService.getWorkingDirectory( project, "scm:local:src/test-projects:regular-multi-module/", projects ); assertEquals( "Incorrect working directory for regular multi-module project", baseWorkingDirectory + File.separator + "9" + File.separator + "module-a", projectWorkingDirectory.getPath() ); // test generated path of parent project project = createProject( 9, "org.apache.continuum", "parent-project", "1.0-SNAPSHOT", "scm:local:src/test-projects:regular-multi-module", true ); projectWorkingDirectory = workingDirectoryService.getWorkingDirectory( project, "scm:local:src/test-projects:regular-multi-module", projects ); assertEquals( "Incorrect working directory for regular multi-module project", baseWorkingDirectory + File.separator + "9", projectWorkingDirectory.getPath() ); } }
5,439
0
Create_ds/continuum/continuum-commons/src/test/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/test/java/org/apache/continuum/utils/ContinuumUtilsTest.java
package org.apache.continuum.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.junit.Test; import static org.junit.Assert.assertEquals; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class ContinuumUtilsTest { @Test public void testThrowableMessagesToString() { Throwable a = new Exception( "bar" ); Throwable b = new Exception( "foo", a ); assertEquals( "bar", ContinuumUtils.throwableMessagesToString( a ) ); assertEquals( "foo" + ContinuumUtils.EOL + "bar", ContinuumUtils.throwableMessagesToString( b ) ); } }
5,440
0
Create_ds/continuum/continuum-commons/src/test/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/test/java/org/apache/continuum/installation/DefaultInstallationServiceTest.java
package org.apache.continuum.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.continuum.dao.DaoUtils; import org.apache.maven.continuum.AbstractContinuumTest; import org.apache.maven.continuum.execution.ExecutorConfigurator; import org.apache.maven.continuum.installation.AlreadyExistsInstallationException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.ProfileService; import org.codehaus.plexus.util.StringUtils; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * @since 13 juin 07 */ public class DefaultInstallationServiceTest extends AbstractContinuumTest { private static final String NEW_INSTALLATION_NAME = "newInstallation"; @Before public void setUp() throws Exception { DaoUtils daoUtils = lookup( DaoUtils.class ); daoUtils.eraseDatabase(); } private InstallationService getInstallationService() throws Exception { //Continuum continuum = (Continuum) lookup( Continuum.ROLE ); //return continuum.getInstallationService(); return lookup( InstallationService.class ); } private Installation addInstallation( String name, String varName, String varValue, String type ) throws Exception { Installation installation = new Installation(); installation.setType( type ); installation.setName( name ); installation.setVarName( varName ); installation.setVarValue( varValue ); return getInstallationService().add( installation ); } @Test public void testAddInstallation() throws Exception { Installation added = this.addInstallation( NEW_INSTALLATION_NAME, null, "bar", InstallationService.JDK_TYPE ); Installation getted = getInstallationService().getInstallation( added.getInstallationId() ); assertNotNull( getted ); assertEquals( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), getted.getVarName() ); assertEquals( "bar", getted.getVarValue() ); assertEquals( 1, getInstallationService().getAllInstallations().size() ); assertNotNull( getInstallationService().getInstallation( NEW_INSTALLATION_NAME ) ); } @Test public void testAddDuplicateInstallation() throws Exception { Installation added = this.addInstallation( NEW_INSTALLATION_NAME, null, "bar", InstallationService.JDK_TYPE ); Installation getted = getInstallationService().getInstallation( added.getInstallationId() ); assertNotNull( getted ); assertEquals( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), getted.getVarName() ); assertEquals( "bar", getted.getVarValue() ); try { this.addInstallation( NEW_INSTALLATION_NAME, null, "bar", InstallationService.JDK_TYPE ); fail( "not in AlreadyExistsInstallationException" ); } catch ( AlreadyExistsInstallationException e ) { // we must be here } assertEquals( 1, getInstallationService().getAllInstallations().size() ); } @Test public void testRemove() throws Exception { String name = "toremove"; Installation added = this.addInstallation( name, "foo", "bar", InstallationService.JDK_TYPE ); Installation getted = getInstallationService().getInstallation( added.getInstallationId() ); assertNotNull( getted ); getInstallationService().delete( getted ); getted = getInstallationService().getInstallation( added.getInstallationId() ); assertNull( getted ); } @Test public void testUpdate() throws Exception { String name = "toupdate"; Installation added = this.addInstallation( name, "foo", "bar", InstallationService.JDK_TYPE ); Installation getted = getInstallationService().getInstallation( added.getInstallationId() ); assertNotNull( getted ); assertEquals( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), getted.getVarName() ); assertEquals( "bar", getted.getVarValue() ); getted.setVarName( "updatefoo" ); getted.setVarValue( "updatedbar" ); getInstallationService().update( getted ); getted = getInstallationService().getInstallation( added.getInstallationId() ); assertNotNull( getted ); assertEquals( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), getted.getVarName() ); assertEquals( "updatedbar", getted.getVarValue() ); } @Test public void testGetDefaultJavaVersionInfo() throws Exception { InstallationService installationService = (InstallationService) lookup( InstallationService.ROLE, "default" ); List<String> infos = installationService.getDefaultJavaVersionInfo(); assertNotNull( infos ); } @Test public void testGetJavaVersionInfo() throws Exception { InstallationService installationService = (InstallationService) lookup( InstallationService.ROLE, "default" ); String javaHome = System.getenv( "JAVA_HOME" ); if ( StringUtils.isEmpty( javaHome ) ) { javaHome = System.getProperty( "java.home" ); } Installation installation = new Installation(); installation.setName( "test" ); installation.setType( InstallationService.JDK_TYPE ); installation.setVarValue( javaHome ); List<String> infos = installationService.getJavaVersionInfo( installation ); assertNotNull( infos ); } @Test public void testGetJavaVersionInfoWithCommonMethod() throws Exception { InstallationService installationService = (InstallationService) lookup( InstallationService.ROLE, "default" ); ExecutorConfigurator java = installationService.getExecutorConfigurator( InstallationService.JDK_TYPE ); String javaHome = System.getenv( "JAVA_HOME" ); if ( StringUtils.isEmpty( javaHome ) ) { javaHome = System.getProperty( "java.home" ); } List<String> infos = installationService.getExecutorVersionInfo( javaHome, java, null ); System.out.println( infos ); assertNotNull( infos ); } /* CONTINUUM-2559 - test may fail even in a valid environment public void testgetMvnVersionWithCommonMethod() throws Exception { InstallationService installationService = (InstallationService) lookup( InstallationService.ROLE, "default" ); ExecutorConfigurator java = installationService.getExecutorConfigurator( InstallationService.MAVEN2_TYPE ); List<String> infos = installationService.getExecutorVersionInfo( null, java, null ); assertNotNull( infos ); } */ @Test public void testAddInstallationAutomaticProfile() throws Exception { Installation installation = new Installation(); installation.setType( InstallationService.JDK_TYPE ); installation.setName( "automaticJdk" ); installation.setVarName( "automaticvarName" ); installation.setVarValue( "automaticvarValue" ); getInstallationService().add( installation, true ); ProfileService profileService = (ProfileService) lookup( ProfileService.ROLE, "default" ); List<Profile> profiles = profileService.getAllProfiles(); assertEquals( 1, profiles.size() ); Profile profile = profiles.get( 0 ); assertEquals( "automaticJdk", profile.getName() ); Installation jdk = profile.getJdk(); assertNotNull( jdk ); assertEquals( "automaticJdk", jdk.getName() ); } @Test public void testUpdateName() throws Exception { Installation installation = new Installation(); installation.setType( InstallationService.JDK_TYPE ); installation.setName( "automatic" ); installation.setVarName( "automaticvarName" ); installation.setVarValue( "automaticvarValue" ); installation = getInstallationService().add( installation, true ); installation.setName( "new name here" ); getInstallationService().update( installation ); Installation getted = getInstallationService().getInstallation( installation.getInstallationId() ); assertEquals( "new name here", getted.getName() ); } }
5,441
0
Create_ds/continuum/continuum-commons/src/test/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/test/java/org/apache/continuum/profile/DefaultProfileServiceTest.java
package org.apache.continuum.profile; /* * 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.maven.continuum.AbstractContinuumTest; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.AlreadyExistsProfileException; import org.apache.maven.continuum.profile.ProfileService; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * @since 15 juin 07 */ public class DefaultProfileServiceTest extends AbstractContinuumTest { Installation jdk1; private static final String jdk1Name = "jdk1"; private Installation jdk2; private static final String jdk2Name = "jdk2"; Installation mvn205; private static final String mvn205Name = "mvn 2.0.5"; Installation mvn206; private static final String mvn206Name = "mvn 2.0.6"; Profile jdk1mvn205; private static final String jdk1mvn205Name = "jdk1 mvn 2.0.5"; Profile jdk2mvn206; private static final String jdk2mvn206Name = "jdk2 mvn 2.0.6"; Installation mvnOpts1; private static final String mvnOpts1Name = "mvnOpts1"; Installation mvnOpts2; private static final String mvnOpts2Name = "mvnOpts2"; @Before public void setUp() throws Exception { DaoUtils daoUtils = lookup( DaoUtils.class ); daoUtils.eraseDatabase(); jdk1 = new Installation(); jdk1.setType( InstallationService.JDK_TYPE ); jdk1.setVarValue( "/foo/bar" ); jdk1.setName( jdk1Name ); jdk1 = getInstallationService().add( jdk1 ); jdk2 = new Installation(); jdk2.setType( InstallationService.JDK_TYPE ); jdk2.setVarValue( "/foo/bar/zloug" ); jdk2.setName( jdk2Name ); jdk2 = getInstallationService().add( jdk2 ); mvn205 = new Installation(); mvn205.setType( InstallationService.MAVEN2_TYPE ); mvn205.setVarValue( "/users/maven-2.0.5" ); mvn205.setName( mvn205Name ); mvn205 = getInstallationService().add( mvn205 ); mvn206 = new Installation(); mvn206.setType( InstallationService.MAVEN2_TYPE ); mvn206.setVarValue( "/users/maven-2.0.6" ); mvn206.setName( mvn206Name ); mvn206 = getInstallationService().add( mvn206 ); jdk1mvn205 = new Profile(); jdk1mvn205.setJdk( jdk1 ); jdk1mvn205.setBuilder( mvn205 ); jdk1mvn205.setName( jdk1mvn205Name ); getProfileService().addProfile( jdk1mvn205 ); jdk2mvn206 = new Profile(); jdk2mvn206.setJdk( jdk2 ); jdk2mvn206.setBuilder( mvn206 ); jdk2mvn206.setName( jdk2mvn206Name ); getProfileService().addProfile( jdk2mvn206 ); mvnOpts1 = new Installation(); mvnOpts1.setType( InstallationService.ENVVAR_TYPE ); mvnOpts1.setVarName( "MAVEN_OPTS" ); mvnOpts1.setVarValue( "-Xmx256m -Djava.awt.headless=true" ); mvnOpts1.setName( mvnOpts1Name ); mvnOpts1 = getInstallationService().add( mvnOpts1 ); mvnOpts2 = new Installation(); mvnOpts2.setType( InstallationService.ENVVAR_TYPE ); mvnOpts2.setVarName( "MAVEN_OPTS" ); mvnOpts2.setVarValue( "-Xmx1024m -Xms1024m" ); mvnOpts2.setName( mvnOpts2Name ); mvnOpts2 = getInstallationService().add( mvnOpts2 ); } public InstallationService getInstallationService() throws Exception { return (InstallationService) lookup( InstallationService.ROLE, "default" ); } public ProfileService getProfileService() throws Exception { return (ProfileService) lookup( ProfileService.ROLE, "default" ); } @Test public void testAddProfile() throws Exception { Profile defaultProfile = new Profile(); String name = "default profile"; defaultProfile.setName( name ); Profile getted = getProfileService().addProfile( defaultProfile ); assertNotNull( getProfileService().getProfile( getted.getId() ) ); assertEquals( name, getProfileService().getProfile( getted.getId() ).getName() ); assertEquals( 3, getProfileService().getAllProfiles().size() ); } @Test public void testAddDuplicateProfile() throws Exception { Profile defaultProfile = new Profile(); String name = "default profile"; defaultProfile.setName( name ); Profile getted = getProfileService().addProfile( defaultProfile ); assertNotNull( getProfileService().getProfile( getted.getId() ) ); assertEquals( name, getProfileService().getProfile( getted.getId() ).getName() ); assertEquals( 3, getProfileService().getAllProfiles().size() ); defaultProfile = new Profile(); defaultProfile.setName( name ); try { getProfileService().addProfile( defaultProfile ); fail( "no AlreadyExistsProfileException with an already exist name " ); } catch ( AlreadyExistsProfileException e ) { // we must be here } assertEquals( 3, getProfileService().getAllProfiles().size() ); } @Test public void testDeleteProfile() throws Exception { Profile defaultProfile = new Profile(); defaultProfile.setName( "default profile" ); Profile getted = getProfileService().addProfile( defaultProfile ); int id = getted.getId(); assertNotNull( getProfileService().getProfile( id ) ); getProfileService().deleteProfile( id ); assertNull( getProfileService().getProfile( id ) ); } @Test public void testGetAllProfile() throws Exception { List<Profile> all = getProfileService().getAllProfiles(); assertNotNull( all ); assertFalse( all.isEmpty() ); assertEquals( 2, all.size() ); } @Test public void testUpdateProfile() throws Exception { Profile profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertEquals( jdk1mvn205Name, profile.getName() ); String newName = "new name"; profile.setName( newName ); getProfileService().updateProfile( profile ); Profile getted = getProfileService().getProfile( jdk1mvn205.getId() ); assertNotNull( getted ); assertEquals( newName, getted.getName() ); } @Test public void testUpdateProfileDuplicateName() throws Exception { int profileId = jdk1mvn205.getId(); Profile profile = getProfileService().getProfile( profileId ); assertEquals( jdk1mvn205Name, profile.getName() ); profile.setName( jdk2mvn206Name ); try { getProfileService().updateProfile( profile ); fail( "no AlreadyExistsProfileException with duplicate name" ); } catch ( AlreadyExistsProfileException e ) { // we must be here } Profile getted = getProfileService().getProfile( profileId ); assertNotNull( getted ); assertEquals( jdk1mvn205Name, getted.getName() ); } @Test public void testSetJdkInProfile() throws Exception { Profile profile = getProfileService().getProfile( jdk1mvn205.getId() ); getProfileService().setJdkInProfile( profile, jdk2 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertEquals( jdk2.getName(), profile.getJdk().getName() ); assertEquals( jdk2.getVarValue(), profile.getJdk().getVarValue() ); } @Test public void testSetBuilderInProfile() throws Exception { Profile profile = getProfileService().getProfile( jdk1mvn205.getId() ); getProfileService().setBuilderInProfile( profile, mvn206 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertEquals( mvn206.getName(), profile.getBuilder().getName() ); assertEquals( mvn206.getVarValue(), profile.getBuilder().getVarValue() ); } @Test public void testAddEnvVarInProfile() throws Exception { Profile profile = getProfileService().getProfile( jdk1mvn205.getId() ); getProfileService().setBuilderInProfile( profile, mvn206 ); getProfileService().addEnvVarInProfile( profile, mvnOpts1 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertFalse( profile.getEnvironmentVariables().isEmpty() ); assertEquals( 1, profile.getEnvironmentVariables().size() ); } @Test public void testRemoveInstallationLinkedToAProfile() throws Exception { Profile profile = getProfileService().getProfile( jdk1mvn205.getId() ); getProfileService().setJdkInProfile( profile, jdk2 ); getProfileService().getProfile( jdk1mvn205.getId() ); InstallationService installationService = lookup( InstallationService.class, "default" ); installationService.delete( jdk2 ); } @Test public void testRemoveEnvVarFromProfile() throws Exception { Profile profile = getProfileService().getProfile( jdk1mvn205.getId() ); getProfileService().setJdkInProfile( profile, jdk2 ); getProfileService().addEnvVarInProfile( profile, mvnOpts1 ); getProfileService().addEnvVarInProfile( profile, mvnOpts2 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertNotNull( profile.getJdk() ); assertEquals( 2, profile.getEnvironmentVariables().size() ); getProfileService().removeInstallationFromProfile( profile, mvnOpts1 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertNotNull( profile.getJdk() ); assertEquals( 1, profile.getEnvironmentVariables().size() ); getProfileService().removeInstallationFromProfile( profile, jdk2 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertNull( profile.getJdk() ); assertEquals( 1, profile.getEnvironmentVariables().size() ); getProfileService().removeInstallationFromProfile( profile, mvnOpts2 ); profile = getProfileService().getProfile( jdk1mvn205.getId() ); assertNull( profile.getJdk() ); assertEquals( 0, profile.getEnvironmentVariables().size() ); } }
5,442
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum/configuration/DefaultConfigurationService.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.BuildQueueService; import org.apache.continuum.buildqueue.BuildQueueServiceException; import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.configuration.ContinuumConfiguration; import org.apache.continuum.configuration.ContinuumConfigurationException; import org.apache.continuum.configuration.GeneralConfiguration; import org.apache.continuum.dao.ScheduleDao; import org.apache.continuum.dao.SystemConfigurationDao; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.model.project.BuildQueue; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.model.system.SystemConfiguration; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public class DefaultConfigurationService implements ConfigurationService { private static final Logger log = LoggerFactory.getLogger( DefaultConfigurationService.class ); // when adding a requirement, the template in spring-context.xml must be updated CONTINUUM-1207 @Configuration( "${plexus.home}" ) private File applicationHome; @Resource private ScheduleDao scheduleDao; @Resource private SystemConfigurationDao systemConfigurationDao; @Resource private BuildQueueService buildQueueService; @Resource private ContinuumConfiguration configuration; @Resource private FileSystemManager fsManager; private GeneralConfiguration generalConfiguration; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private SystemConfiguration systemConf; private boolean loaded = false; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public void initialize() throws ConfigurationLoadingException, ContinuumConfigurationException { loadData(); } public ScheduleDao getScheduleDao() { return scheduleDao; } public void setScheduleDao( ScheduleDao scheduleDao ) { this.scheduleDao = scheduleDao; } public BuildQueueService getBuildQueueService() { return buildQueueService; } public void setBuildQueueService( BuildQueueService buildQueueService ) { this.buildQueueService = buildQueueService; } public SystemConfigurationDao getSystemConfigurationDao() { return systemConfigurationDao; } public void setSystemConfigurationDao( SystemConfigurationDao systemConfigurationDao ) { this.systemConfigurationDao = systemConfigurationDao; } public ContinuumConfiguration getConfiguration() { return configuration; } public void setConfiguration( ContinuumConfiguration configuration ) { this.configuration = configuration; } public File getApplicationHome() { return applicationHome; } public void setApplicationHome( File applicationHome ) { this.applicationHome = applicationHome; } public void setInitialized( boolean initialized ) { generalConfiguration.setInitialized( initialized ); } public boolean isInitialized() { return systemConf.isInitialized() || generalConfiguration.isInitialized(); } public String getUrl() { String baseUrl = generalConfiguration.getBaseUrl(); if ( StringUtils.isEmpty( baseUrl ) ) { baseUrl = systemConf.getBaseUrl(); setUrl( baseUrl ); } return baseUrl != null ? baseUrl : ""; } public void setUrl( String url ) { generalConfiguration.setBaseUrl( url ); } /** * @see org.apache.maven.continuum.configuration.ConfigurationService#getBuildOutputDirectory() */ public File getBuildOutputDirectory() { File buildOutputDirectory = generalConfiguration.getBuildOutputDirectory(); if ( buildOutputDirectory == null ) { buildOutputDirectory = getFile( systemConf.getBuildOutputDirectory() ); setBuildOutputDirectory( buildOutputDirectory ); } return buildOutputDirectory; } public void setBuildOutputDirectory( File buildOutputDirectory ) { File f = buildOutputDirectory; try { f = f.getCanonicalFile(); } catch ( IOException e ) { } generalConfiguration.setBuildOutputDirectory( f ); } public File getWorkingDirectory() { File workingDirectory = generalConfiguration.getWorkingDirectory(); if ( workingDirectory == null ) { workingDirectory = getFile( systemConf.getWorkingDirectory() ); setWorkingDirectory( workingDirectory ); } return workingDirectory; } public void setWorkingDirectory( File workingDirectory ) { File f = workingDirectory; try { f = f.getCanonicalFile(); } catch ( IOException e ) { } generalConfiguration.setWorkingDirectory( f ); } public File getDeploymentRepositoryDirectory() { File deploymentDirectory = generalConfiguration.getDeploymentRepositoryDirectory(); if ( deploymentDirectory == null ) { deploymentDirectory = getFile( systemConf.getDeploymentRepositoryDirectory() ); setDeploymentRepositoryDirectory( deploymentDirectory ); } return deploymentDirectory; } public void setDeploymentRepositoryDirectory( File deploymentRepositoryDirectory ) { generalConfiguration.setDeploymentRepositoryDirectory( deploymentRepositoryDirectory ); } public String getBuildOutput( int buildId, int projectId ) throws ConfigurationException { File file = getBuildOutputFile( buildId, 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 build '" + buildId + "'.", e ); return null; } } public File getReleaseOutputDirectory() { File releaseOutputDirectory = generalConfiguration.getReleaseOutputDirectory(); if ( releaseOutputDirectory == null ) { releaseOutputDirectory = getFile( systemConf.getReleaseOutputDirectory() ); setReleaseOutputDirectory( releaseOutputDirectory ); } return releaseOutputDirectory; } public void setReleaseOutputDirectory( File releaseOutputDirectory ) { if ( releaseOutputDirectory == null ) { generalConfiguration.setReleaseOutputDirectory( releaseOutputDirectory ); return; } File f = releaseOutputDirectory; try { f = f.getCanonicalFile(); } catch ( IOException e ) { } generalConfiguration.setReleaseOutputDirectory( f ); } public List<BuildAgentConfiguration> getBuildAgents() { return generalConfiguration.getBuildAgents(); } public void addBuildAgent( BuildAgentConfiguration buildAgent ) throws ConfigurationException { // trim trailing space buildAgent.setUrl( buildAgent.getUrl().trim() ); List<BuildAgentConfiguration> buildAgents = generalConfiguration.getBuildAgents(); if ( buildAgents == null ) { buildAgents = new ArrayList<BuildAgentConfiguration>(); } for ( BuildAgentConfiguration agent : buildAgents ) { if ( agent.getUrl().trim().equals( buildAgent.getUrl() ) ) { throw new ConfigurationException( "Unable to add build agent: build agent already exist" ); } } buildAgents.add( buildAgent ); generalConfiguration.setBuildAgents( buildAgents ); } public void removeBuildAgent( BuildAgentConfiguration buildAgent ) { List<BuildAgentConfiguration> buildAgents = getBuildAgents(); if ( buildAgents != null ) { for ( BuildAgentConfiguration agent : buildAgents ) { if ( agent.getUrl().equals( buildAgent.getUrl() ) ) { buildAgents.remove( agent ); break; } } generalConfiguration.setBuildAgents( buildAgents ); } } public void updateBuildAgent( BuildAgentConfiguration buildAgent ) { // trim trailing space buildAgent.setUrl( buildAgent.getUrl().trim() ); List<BuildAgentConfiguration> buildAgents = getBuildAgents(); if ( buildAgents != null ) { for ( BuildAgentConfiguration agent : buildAgents ) { if ( agent.getUrl().trim().equals( buildAgent.getUrl() ) ) { agent.setDescription( buildAgent.getDescription() ); agent.setEnabled( buildAgent.isEnabled() ); agent.setUrl( buildAgent.getUrl() ); return; } } } } public boolean isDistributedBuildEnabled() { return generalConfiguration.isDistributedBuildEnabled(); } public void setDistributedBuildEnabled( boolean distributedBuildEnabled ) { generalConfiguration.setDistributedBuildEnabled( distributedBuildEnabled ); } public void addBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException { List<BuildAgentGroupConfiguration> buildAgentGroups = generalConfiguration.getBuildAgentGroups(); if ( buildAgentGroups == null ) { buildAgentGroups = new ArrayList<BuildAgentGroupConfiguration>(); } for ( BuildAgentGroupConfiguration groups : buildAgentGroups ) { if ( groups.getName().equals( buildAgentGroup.getName() ) ) { throw new ConfigurationException( "Unable to add build agent group: build agent group already exist" ); } } buildAgentGroups.add( buildAgentGroup ); generalConfiguration.setBuildAgentGroups( buildAgentGroups ); } public void removeBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException { List<BuildAgentGroupConfiguration> buildAgentGroups = generalConfiguration.getBuildAgentGroups(); if ( buildAgentGroups != null ) { for ( BuildAgentGroupConfiguration groups : buildAgentGroups ) { if ( groups.getName().equals( buildAgentGroup.getName() ) ) { buildAgentGroups.remove( groups ); break; } } generalConfiguration.setBuildAgentGroups( buildAgentGroups ); } } public void updateBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException { List<BuildAgentGroupConfiguration> buildAgentGroups = generalConfiguration.getBuildAgentGroups(); if ( buildAgentGroups != null ) { for ( BuildAgentGroupConfiguration groups : buildAgentGroups ) { if ( groups.getName().equals( buildAgentGroup.getName() ) ) { groups.setName( buildAgentGroup.getName() ); groups.setBuildAgents( buildAgentGroup.getBuildAgents() ); return; } } } } public void addBuildAgent( BuildAgentGroupConfiguration buildAgentGroup, BuildAgentConfiguration buildAgent ) throws ConfigurationException { List<BuildAgentGroupConfiguration> buildAgentGroupConfiguration = generalConfiguration.getBuildAgentGroups(); if ( buildAgentGroupConfiguration != null ) { for ( BuildAgentGroupConfiguration group : buildAgentGroupConfiguration ) { if ( group.getName().equals( buildAgentGroup.getName() ) ) { List<BuildAgentConfiguration> agents = group.getBuildAgents(); for ( BuildAgentConfiguration agent : agents ) { if ( agent.getUrl().equals( buildAgent.getUrl() ) ) { throw new ConfigurationException( "Unable to add build agent : build agent already exist" ); } } group.addBuildAgent( buildAgent ); break; } } generalConfiguration.setBuildAgentGroups( buildAgentGroupConfiguration ); } } public void removeBuildAgent( BuildAgentGroupConfiguration buildAgentGroup, BuildAgentConfiguration buildAgent ) throws ConfigurationException { List<BuildAgentGroupConfiguration> buildAgentGroupConfiguration = generalConfiguration.getBuildAgentGroups(); if ( buildAgentGroupConfiguration != null ) { for ( BuildAgentGroupConfiguration group : buildAgentGroupConfiguration ) { if ( group.getName().equals( buildAgentGroup.getName() ) ) { List<BuildAgentConfiguration> agents = group.getBuildAgents(); for ( BuildAgentConfiguration agent : agents ) { if ( agent.getUrl().equals( buildAgent.getUrl() ) ) { group.removeBuildAgent( agent ); break; } } } } generalConfiguration.setBuildAgentGroups( buildAgentGroupConfiguration ); } } public BuildAgentGroupConfiguration getBuildAgentGroup( String name ) { List<BuildAgentGroupConfiguration> buildAgentGroupConfiguration = generalConfiguration.getBuildAgentGroups(); if ( buildAgentGroupConfiguration != null ) { for ( BuildAgentGroupConfiguration buildAgentGroup : buildAgentGroupConfiguration ) { if ( buildAgentGroup.getName().equals( name ) ) { return buildAgentGroup; } } } return null; } public BuildAgentConfiguration getBuildAgent( String url ) { List<BuildAgentConfiguration> buildAgents = generalConfiguration.getBuildAgents(); if ( buildAgents == null ) { buildAgents = new ArrayList<BuildAgentConfiguration>(); } for ( BuildAgentConfiguration agent : buildAgents ) { if ( agent.getUrl().equals( url ) ) { return agent; } } return null; } public List<BuildAgentGroupConfiguration> getBuildAgentGroups() { return generalConfiguration.getBuildAgentGroups(); } public boolean containsBuildAgentUrl( String buildAgentUrl, BuildAgentGroupConfiguration buildAgentGroup ) { BuildAgentGroupConfiguration group = this.getBuildAgentGroup( buildAgentGroup.getName() ); List<BuildAgentConfiguration> buildAgents = group.getBuildAgents(); if ( buildAgents == null ) { buildAgents = new ArrayList<BuildAgentConfiguration>(); } for ( BuildAgentConfiguration agent : buildAgents ) { if ( agent.getUrl().equals( buildAgentUrl ) ) { return true; } } return false; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public File getBuildOutputDirectory( int projectId ) { File dir = new File( getBuildOutputDirectory(), Integer.toString( projectId ) ); try { dir = dir.getCanonicalFile(); } catch ( IOException e ) { } return dir; } public File getTestReportsDirectory( int buildId, int projectId ) throws ConfigurationException { File outputDirectory = getBuildOutputDirectory( projectId ); File testDir = new File( outputDirectory.getPath() + File.separator + buildId + File.separator + "surefire-reports" ); if ( !testDir.exists() && !testDir.mkdirs() ) { throw new ConfigurationException( String.format( "Could not make the test reports directory: '%s'.", testDir.getAbsolutePath() ) ); } return testDir; } 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 getReleaseOutputDirectory( int projectGroupId ) { if ( getReleaseOutputDirectory() == null ) { return null; } File dir = new File( getReleaseOutputDirectory(), Integer.toString( projectGroupId ) ); try { dir = dir.getCanonicalFile(); } catch ( IOException e ) { } return dir; } public File getReleaseOutputFile( int projectGroupId, String name ) throws ConfigurationException { File dir = getReleaseOutputDirectory( projectGroupId ); if ( dir == null ) { return null; } if ( !dir.exists() && !dir.mkdirs() ) { throw new ConfigurationException( "Could not make the release output directory: " + "'" + dir.getAbsolutePath() + "'." ); } return new File( dir, name + ".log.txt" ); } public String getReleaseOutput( int projectGroupId, String name ) throws ConfigurationException { File file = getReleaseOutputFile( projectGroupId, name ); try { if ( file.exists() ) { return fsManager.fileContents( file ); } else { return "There is no output for this release."; } } catch ( IOException e ) { log.warn( "Error reading release output for release '" + name + "'.", e ); return null; } } public int getNumberOfBuildsInParallel() { return generalConfiguration.getNumberOfBuildsInParallel(); } public void setNumberOfBuildsInParallel( int num ) { generalConfiguration.setNumberOfBuildsInParallel( num ); } public String getSharedSecretPassword() { return generalConfiguration.getSharedSecretPassword(); } public void setSharedSecretPassword( String sharedSecretPassword ) { generalConfiguration.setSharedSecretPassword( sharedSecretPassword ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public File getFile( String filename ) { if ( filename == null ) { return null; } File f = null; if ( filename.length() != 0 ) { f = new File( filename ); if ( !f.isAbsolute() ) { f = new File( applicationHome, filename ); } } try { if ( f != null ) { return f.getCanonicalFile(); } return null; } catch ( IOException e ) { return f; } } // ---------------------------------------------------------------------- // Load and Store // ---------------------------------------------------------------------- public boolean isLoaded() { return loaded; } private void loadData() throws ConfigurationLoadingException, ContinuumConfigurationException { generalConfiguration = configuration.getGeneralConfiguration(); try { systemConf = getSystemConfigurationDao().getSystemConfiguration(); if ( systemConf == null ) { systemConf = new SystemConfiguration(); systemConf = getSystemConfigurationDao().addSystemConfiguration( systemConf ); } loaded = true; } catch ( ContinuumStoreException e ) { throw new ConfigurationLoadingException( "Error reading configuration from database.", e ); } } public void reload() throws ConfigurationLoadingException, ContinuumConfigurationException { configuration.reload(); loadData(); } public void store() throws ConfigurationStoringException, ContinuumConfigurationException { configuration.setGeneralConfiguration( generalConfiguration ); configuration.save(); } public Schedule getDefaultSchedule() throws ContinuumStoreException, ConfigurationLoadingException, ContinuumConfigurationException, BuildQueueServiceException { // Schedule Schedule defaultSchedule = scheduleDao.getScheduleByName( DEFAULT_SCHEDULE_NAME ); if ( defaultSchedule == null ) { defaultSchedule = createDefaultSchedule(); defaultSchedule = scheduleDao.addSchedule( defaultSchedule ); } return defaultSchedule; } public BuildQueue getDefaultBuildQueue() throws BuildQueueServiceException { BuildQueue defaultBuildQueue = buildQueueService.getBuildQueueByName( DEFAULT_BUILD_QUEUE_NAME ); if ( defaultBuildQueue == null ) { defaultBuildQueue = createDefaultBuildQueue(); defaultBuildQueue = buildQueueService.addBuildQueue( defaultBuildQueue ); } return defaultBuildQueue; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private Schedule createDefaultSchedule() throws ConfigurationLoadingException, ContinuumConfigurationException, ContinuumStoreException, BuildQueueServiceException { log.info( "create Default Schedule" ); Schedule schedule = new Schedule(); schedule.setName( DEFAULT_SCHEDULE_NAME ); //It shouldn't be possible if ( systemConf == null ) { this.reload(); } schedule.setDescription( systemConf.getDefaultScheduleDescription() ); schedule.setCronExpression( systemConf.getDefaultScheduleCronExpression() ); schedule.setActive( true ); BuildQueue buildQueue = getDefaultBuildQueue(); schedule.addBuildQueue( buildQueue ); return schedule; } private BuildQueue createDefaultBuildQueue() { log.info( "create Default Build Queue" ); BuildQueue buildQueue = new BuildQueue(); buildQueue.setName( DEFAULT_BUILD_QUEUE_NAME ); return buildQueue; } }
5,443
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum/utils/URLUserInfo.java
package org.apache.maven.continuum.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. */ /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 1.2 */ public class URLUserInfo { private String username; private String password; /** * */ public URLUserInfo() { // } public String getUsername() { return username; } public void setUsername( String username ) { this.username = username; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } }
5,444
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum/utils/ChrootJailWorkingDirectoryService.java
package org.apache.maven.continuum.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.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.codehaus.plexus.component.annotations.Configuration; import org.springframework.stereotype.Service; import java.io.File; import java.util.List; import javax.annotation.Resource; /** * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a> */ @Service( "workingDirectoryService#chrootJail" ) public class ChrootJailWorkingDirectoryService implements WorkingDirectoryService { @Resource private ConfigurationService configurationService; @Configuration( "" ) private File chrootJailDirectory; public void setConfigurationService( ConfigurationService configurationService ) { this.configurationService = configurationService; } public ConfigurationService getConfigurationService() { return configurationService; } public void setChrootJailDirectory( File chrootJailDirectory ) { this.chrootJailDirectory = chrootJailDirectory; } public File getChrootJailDirectory() { return chrootJailDirectory; } public File getWorkingDirectory( Project project ) { return getWorkingDirectory( project, true ); } public File getWorkingDirectory( Project project, boolean shouldSet ) { ProjectGroup projectGroup = project.getProjectGroup(); File f = new File( getChrootJailDirectory(), projectGroup.getGroupId() ); f = new File( f, getConfigurationService().getWorkingDirectory().getPath() ); return new File( f, Integer.toString( project.getId() ) ); } public File getWorkingDirectory( Project project, String projectScmRoot, List<Project> projects ) { return getWorkingDirectory( project, true ); } public File getWorkingDirectory( Project project, String projectScmRoot, List<Project> projects, boolean shouldSet ) { return getWorkingDirectory( project, shouldSet ); } }
5,445
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum/utils/ContinuumUrlValidator.java
package org.apache.maven.continuum.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.commons.lang.StringUtils; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Configurable; import org.springframework.stereotype.Service; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 27 mars 2008 */ @Service( "continuumUrlValidator#continuumUrl" ) @Component( role = org.apache.maven.continuum.utils.ContinuumUrlValidator.class, hint = "continuumUrl" ) public class ContinuumUrlValidator implements Configurable { /** * The set of schemes that are allowed to be in a URL. */ private Set<String> allowedSchemes = new HashSet<String>(); /** * If no schemes are provided, default to this set. */ protected String[] defaultSchemes = { "http", "https", "ftp" }; /** * Create a UrlValidator with default properties. */ public ContinuumUrlValidator() { this( null ); } /** * Behavior of validation is modified by passing in several strings options: * * @param schemes Pass in one or more url schemes to consider valid, passing in * a null will default to "http,https,ftp" being valid. * If a non-null schemes is specified then all valid schemes must * be specified. */ public ContinuumUrlValidator( String[] schemes ) { if ( schemes == null && this.allowedSchemes.isEmpty() ) { schemes = this.defaultSchemes; } this.allowedSchemes.addAll( Arrays.asList( schemes ) ); } /** * <p>Checks if a field has a valid url address.</p> * * @param value The value validation is being performed on. A <code>null</code> * value is considered invalid. * @return true if the url is valid. */ public boolean validate( String value ) { return isValid( value ); } /** * <p>Checks if a field has a valid url address.</p> * * @param value The value validation is being performed on. A <code>null</code> * value is considered valid. * @return true if the url is valid. */ public boolean isValid( String value ) { if ( StringUtils.isEmpty( value ) ) { return true; } try { URI uri = new URI( value ); return this.allowedSchemes.contains( uri.getScheme() ); } catch ( URISyntaxException e ) { return false; } } /** * @param url * @return URLUserInfo cannot be null * @throws URISyntaxException */ public URLUserInfo extractURLUserInfo( String url ) throws URISyntaxException { URI uri = new URI( url ); // can contains user:password String userInfoRaw = uri.getUserInfo(); URLUserInfo urlUserInfo = new URLUserInfo(); if ( !StringUtils.isEmpty( userInfoRaw ) ) { int index = userInfoRaw.indexOf( ':' ); if ( index >= 0 ) { urlUserInfo.setUsername( userInfoRaw.substring( 0, index ) ); urlUserInfo.setPassword( userInfoRaw.substring( index + 1, userInfoRaw.length() ) ); } else { urlUserInfo.setUsername( userInfoRaw ); } } return urlUserInfo; } public void configure( PlexusConfiguration plexusConfiguration ) throws PlexusConfigurationException { PlexusConfiguration allowedSchemesElement = plexusConfiguration.getChild( "allowedSchemes" ); if ( allowedSchemesElement != null ) { PlexusConfiguration[] allowedSchemeElements = allowedSchemesElement.getChildren( "allowedScheme" ); for ( int i = 0, size = allowedSchemeElements.length; i < size; i++ ) { this.allowedSchemes.add( allowedSchemeElements[i].getValue() ); } } } }
5,446
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/maven/continuum/utils/DefaultWorkingDirectoryService.java
package org.apache.maven.continuum.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.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.Project; import org.codehaus.plexus.util.StringUtils; import org.springframework.stereotype.Service; import java.io.File; import java.util.List; import javax.annotation.Resource; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Service( "workingDirectoryService" ) public class DefaultWorkingDirectoryService implements WorkingDirectoryService { @Resource private ConfigurationService configurationService; public void setConfigurationService( ConfigurationService configurationService ) { this.configurationService = configurationService; } public ConfigurationService getConfigurationService() { return configurationService; } // ---------------------------------------------------------------------- // WorkingDirectoryService Implementation // ---------------------------------------------------------------------- public File getWorkingDirectory( Project project ) { return getWorkingDirectory( project, null, null ); } public File getWorkingDirectory( Project project, boolean shouldSet ) { return getWorkingDirectory( project, null, null, shouldSet ); } /** * @param project * @param projectScmRoot * @param projects projects under the same projectScmRoot * @return */ public File getWorkingDirectory( Project project, String projectScmRoot, List<Project> projects ) { return getWorkingDirectory( project, projectScmRoot, projects, true ); } /** * @param project * @param projectScmRoot * @param projects projects under the same projectScmRoot * @param shouldSet * @return */ public File getWorkingDirectory( Project project, String projectScmRoot, List<Project> projects, boolean shouldSet ) { // TODO: Enable, this is what we really want // ContinuumProjectGroup projectGroup = project.getProjectGroup(); // // return new File( projectGroup.getWorkingDirectory(), // project.getPath() ); String workingDirectory = project.getWorkingDirectory(); if ( project.getWorkingDirectory() == null || "".equals( project.getWorkingDirectory() ) ) { if ( project.isCheckedOutInSingleDirectory() && projectScmRoot != null && !"".equals( projectScmRoot ) ) { Project rootProject = project; if ( projects != null ) { // the root project should have the lowest id since it's always added first for ( Project projectUnderScmRoot : projects ) { if ( projectUnderScmRoot.getId() < rootProject.getId() ) { rootProject = projectUnderScmRoot; } } } // determine the path String projectScmUrl = project.getScmUrl(); int indexDiff = StringUtils.differenceAt( projectScmUrl, projectScmRoot ); String pathToProject = ""; if ( indexDiff != -1 ) { pathToProject = projectScmUrl.substring( indexDiff ); } if ( pathToProject.startsWith( "\\" ) || pathToProject.startsWith( "/" ) ) { workingDirectory = Integer.toString( rootProject.getId() ) + pathToProject; } else { workingDirectory = Integer.toString( rootProject.getId() ) + File.separatorChar + pathToProject; } } else { workingDirectory = Integer.toString( project.getId() ); } } if ( shouldSet ) { project.setWorkingDirectory( workingDirectory ); } File workDir; File projectWorkingDirectory = new File( workingDirectory ); if ( projectWorkingDirectory.isAbsolute() ) { // clean the project working directory path if it's a subdirectory of the global working directory if ( projectWorkingDirectory.getAbsolutePath().startsWith( getConfigurationService().getWorkingDirectory().getAbsolutePath() ) ) { String pwd = projectWorkingDirectory.getAbsolutePath().substring( getConfigurationService().getWorkingDirectory().getAbsolutePath().length() ); if ( pwd.startsWith( "/" ) || pwd.startsWith( "\\" ) ) { pwd = pwd.substring( 1 ); } if ( shouldSet ) { project.setWorkingDirectory( pwd ); } } workDir = projectWorkingDirectory; } else { File baseWorkingDir = getConfigurationService().getWorkingDirectory(); workDir = new File( baseWorkingDir, workingDirectory ); } return workDir; } }
5,447
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum/utils/ContinuumUtils.java
package org.apache.continuum.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 java.io.PrintWriter; import java.io.StringWriter; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class ContinuumUtils { public static final String EOL = System.getProperty( "line.separator" ); 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(); } }
5,448
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum/installation/DefaultInstallationService.java
package org.apache.continuum.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.continuum.dao.InstallationDao; import org.apache.continuum.utils.shell.ExecutionResult; import org.apache.continuum.utils.shell.ListOutputConsumer; import org.apache.continuum.utils.shell.OutputConsumer; import org.apache.continuum.utils.shell.ShellCommandHelper; import org.apache.maven.continuum.execution.ExecutorConfigurator; import org.apache.maven.continuum.installation.AlreadyExistsInstallationException; import org.apache.maven.continuum.installation.InstallationException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.AlreadyExistsProfileException; import org.apache.maven.continuum.profile.ProfileException; import org.apache.maven.continuum.profile.ProfileService; import org.apache.maven.continuum.store.ContinuumStoreException; 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 org.springframework.stereotype.Service; 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; import javax.annotation.Resource; /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * TODO use some cache mechanism to prevent always reading from store ? * @since 13 juin 07 */ @Service( "installationService" ) public class DefaultInstallationService implements InstallationService, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultInstallationService.class ); @Resource private InstallationDao installationDao; @Resource private ProfileService profileService; @Resource private ShellCommandHelper shellCommandHelper; private Map<String, ExecutorConfigurator> typesValues; // --------------------------------------------- // Plexus lifecycle // --------------------------------------------- public void initialize() throws InitializationException { this.typesValues = new HashMap<String, ExecutorConfigurator>(); this.typesValues.put( InstallationService.ANT_TYPE, new ExecutorConfigurator( "ant", "bin", "ANT_HOME", "-version" ) ); this.typesValues.put( InstallationService.ENVVAR_TYPE, null ); this.typesValues.put( InstallationService.JDK_TYPE, new ExecutorConfigurator( "java", "bin", "JAVA_HOME", "-version" ) ); this.typesValues.put( InstallationService.MAVEN1_TYPE, new ExecutorConfigurator( "maven", "bin", "MAVEN_HOME", "-v" ) ); this.typesValues.put( InstallationService.MAVEN2_TYPE, new ExecutorConfigurator( "mvn", "bin", "M2_HOME", "-v" ) ); } /** * @see org.apache.maven.continuum.installation.InstallationService#add(org.apache.maven.continuum.model.system.Installation) */ public Installation add( Installation installation ) throws InstallationException, AlreadyExistsInstallationException { try { return this.add( installation, false ); } catch ( AlreadyExistsProfileException e ) { // normally cannot happend here but anyway we throw the exception throw new InstallationException( e.getMessage(), e ); } } public Installation add( Installation installation, boolean automaticProfile ) throws InstallationException, AlreadyExistsProfileException, AlreadyExistsInstallationException { if ( alreadyExistInstallationName( installation ) ) { throw new AlreadyExistsInstallationException( "Installation with name " + installation.getName() + " already exists" ); } // TODO must be done in the same transaction Installation storedOne; try { String envVarName = this.getEnvVar( installation.getType() ); // override with the defined var name for defined types if ( StringUtils.isNotEmpty( envVarName ) ) { installation.setVarName( envVarName ); } storedOne = installationDao.addInstallation( installation ); } catch ( ContinuumStoreException e ) { throw new InstallationException( e.getMessage(), e ); } try { if ( automaticProfile ) { Profile profile = new Profile(); profile.setName( storedOne.getName() ); profile = profileService.addProfile( profile ); profileService.addInstallationInProfile( profile, storedOne ); } } catch ( ProfileException e ) { throw new InstallationException( "failed to create automatic Profile " + e.getMessage(), e ); } return storedOne; } /** * @see org.apache.maven.continuum.installation.InstallationService#delete(org.apache.maven.continuum.model.system.Installation) */ public void delete( Installation installation ) throws InstallationException { try { installationDao.removeInstallation( installation ); } catch ( ContinuumStoreException e ) { throw new InstallationException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.installation.InstallationService#getAllInstallations() */ @SuppressWarnings( "unchecked" ) public List<Installation> getAllInstallations() throws InstallationException { try { List<Installation> installations = installationDao.getAllInstallations(); return installations == null ? Collections.EMPTY_LIST : installations; } catch ( ContinuumStoreException e ) { throw new InstallationException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.installation.InstallationService#getInstallation(int) */ public Installation getInstallation( int installationId ) throws InstallationException { try { return installationDao.getInstallation( installationId ); } catch ( ContinuumStoreException e ) { throw new InstallationException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.installation.InstallationService#getInstallation(String) */ public Installation getInstallation( String installationName ) throws InstallationException { try { return installationDao.getInstallation( installationName ); } catch ( ContinuumStoreException e ) { throw new InstallationException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.installation.InstallationService#update(org.apache.maven.continuum.model.system.Installation) */ public void update( Installation installation ) throws InstallationException, AlreadyExistsInstallationException { try { Installation stored = getInstallation( installation.getInstallationId() ); if ( stored == null ) { throw new InstallationException( "installation with name " + installation.getName() + " not exists" ); } stored.setName( installation.getName() ); if ( alreadyExistInstallationName( installation ) ) { throw new AlreadyExistsInstallationException( "Installation with name " + installation.getName() + " already exists" ); } stored.setType( installation.getType() ); String envVarName = this.getEnvVar( installation.getType() ); // override with the defined var name for defined types if ( StringUtils.isNotEmpty( envVarName ) ) { installation.setVarName( envVarName ); } else { stored.setVarName( installation.getVarName() ); } stored.setVarValue( installation.getVarValue() ); installationDao.updateInstallation( stored ); } catch ( ContinuumStoreException e ) { throw new InstallationException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.installation.InstallationService#getExecutorConfigurator(java.lang.String) */ public ExecutorConfigurator getExecutorConfigurator( String type ) { return this.typesValues.get( type ); } /** * @see org.apache.maven.continuum.installation.InstallationService#getEnvVar(java.lang.String) */ public String getEnvVar( String type ) { ExecutorConfigurator executorConfigurator = this.typesValues.get( type ); return executorConfigurator == null ? null : executorConfigurator.getEnvVar(); } // ------------------------------------------------------------- // versions informations on jdk and builders (mvn, maven, ant ) // ------------------------------------------------------------- /** * TODO replace with calling getExecutorVersionInfo * * @see org.apache.maven.continuum.installation.InstallationService#getDefaultJavaVersionInfo() */ public List<String> getDefaultJavaVersionInfo() throws InstallationException { try { Properties systemEnvVars = shellCommandHelper.getSystemEnvVars(); String javaHome = (String) systemEnvVars.get( "JAVA_HOME" ); // olamy : JAVA_HOME may not exist for mac users if ( StringUtils.isEmpty( javaHome ) ) { return getJavaVersionInfo( System.getProperty( "java.home" ) ); } return getJavaVersionInfo( javaHome ); } catch ( Exception e ) { throw new InstallationException( e.getMessage(), e ); } } /** * TODO replace with calling getExecutorVersionInfo * * @see org.apache.maven.continuum.installation.InstallationService#getJavaVersionInfo(org.apache.maven.continuum.model.system.Installation) */ public List<String> getJavaVersionInfo( Installation installation ) throws InstallationException { if ( installation == null ) { return getDefaultJavaVersionInfo(); } if ( StringUtils.isEmpty( installation.getVarValue() ) ) { return getDefaultJavaVersionInfo(); } try { return getJavaVersionInfo( installation.getVarValue() ); } catch ( Exception e ) { throw new InstallationException( e.getMessage(), e ); } } /** * @param homePath * @return * @throws Exception */ private List<String> getJavaVersionInfo( String homePath ) throws Exception { String executable = homePath + File.separator + "bin" + File.separator + "java"; ListOutputConsumer outputConsumer = new ListOutputConsumer(); ExecutionResult result = shellCommandHelper.executeShellCommand( null, executable, new String[] { "-version" }, outputConsumer, -1, null ); int exitCode = result.getExitCode(); if ( exitCode != 0 ) { throw new Exception( String.format( "failed to get java version information, %s returned exit code %s", executable, exitCode ) ); } return outputConsumer.getList(); } private Map<String, String> getEnvVars( Profile profile ) { Map<String, String> environnments = new HashMap<String, String>(); if ( profile == null ) { return environnments; } if ( profile.getBuilder() != null ) { environnments.put( profile.getBuilder().getVarName(), profile.getBuilder().getVarValue() ); } if ( profile.getJdk() != null ) { environnments.put( profile.getJdk().getVarName(), profile.getJdk().getVarValue() ); } if ( profile.getEnvironmentVariables() != null ) { for ( Installation installation : (List<Installation>) profile.getEnvironmentVariables() ) { environnments.put( installation.getVarName(), installation.getVarValue() ); } } return environnments; } /** * @see org.apache.maven.continuum.installation.InstallationService#getExecutorVersionInfo(java.lang.String, org.apache.maven.continuum.execution.ExecutorConfigurator, Profile) */ public List<String> getExecutorVersionInfo( String path, ExecutorConfigurator executorConfigurator, Profile profile ) throws InstallationException { if ( executorConfigurator == null || executorConfigurator.getExecutable() == null ) { return Collections.EMPTY_LIST; } StringBuilder executable = new StringBuilder(); Map<String, String> env = new HashMap<String, String>(); if ( StringUtils.isNotEmpty( path ) ) { executable.append( path ).append( File.separator ); executable.append( executorConfigurator.getRelativePath() ).append( File.separator ); env.put( executorConfigurator.getEnvVar(), path ); } executable = executable.append( executorConfigurator.getExecutable() ); env.putAll( getEnvVars( profile ) ); ListOutputConsumer outputConsumer = new ListOutputConsumer(); ExecutionResult result; try { result = shellCommandHelper.executeShellCommand( null, executable.toString(), new String[] { executorConfigurator.getVersionArgument() }, outputConsumer, -1, null ); } catch ( Exception e ) { log.error( "failed to get executor version info", e ); throw new InstallationException( e.getMessage(), e ); } int exitCode = result.getExitCode(); if ( exitCode != 0 ) { throw new InstallationException( String.format( "failed to get executor version info, %s returned exit code %s", executable, exitCode ) ); } return outputConsumer.getList(); } private boolean alreadyExistInstallationName( Installation installation ) throws InstallationException { List<Installation> all = getAllInstallations(); for ( Installation install : all ) { if ( org.apache.commons.lang.StringUtils.equals( installation.getName(), install.getName() ) && ( installation.getInstallationId() == 0 || installation.getInstallationId() != install.getInstallationId() ) ) { return true; } } return false; } }
5,449
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum/profile/DefaultProfileService.java
package org.apache.continuum.profile; /* * 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.StringUtils; import org.apache.continuum.dao.ProfileDao; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.AlreadyExistsProfileException; import org.apache.maven.continuum.profile.ProfileException; import org.apache.maven.continuum.profile.ProfileService; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * TODO use some cache mechanism to prevent always reading from store ? * @since 15 juin 07 */ @Service( "profileService" ) public class DefaultProfileService implements ProfileService { @Resource private ProfileDao profileDao; /** * @see org.apache.maven.continuum.profile.ProfileService#updateProfile(org.apache.maven.continuum.model.system.Profile) */ public void updateProfile( Profile profile ) throws ProfileException, AlreadyExistsProfileException { // already exists check should be done in the same transaction // but we assume we don't have a huge load and a lot of concurrent access ;-) if ( alreadyExistsProfileName( profile ) ) { throw new AlreadyExistsProfileException( "profile with name " + profile.getName() + " already exists" ); } try { Profile stored = getProfile( profile.getId() ); stored.setActive( profile.isActive() ); stored.setBuilder( profile.getBuilder() ); stored.setBuildWithoutChanges( profile.isBuildWithoutChanges() ); stored.setDescription( profile.getDescription() ); stored.setJdk( profile.getJdk() ); stored.setName( profile.getName() ); stored.setEnvironmentVariables( profile.getEnvironmentVariables() ); stored.setBuildAgentGroup( profile.getBuildAgentGroup() ); profileDao.updateProfile( stored ); } catch ( ContinuumStoreException e ) { throw new ProfileException( e.getMessage(), e ); } } public void updateProfileCheckDuplicateName( Profile profile, boolean checkDuplicateName ) throws ProfileException, AlreadyExistsProfileException { if ( checkDuplicateName ) { // already exists check should be done in the same transaction // but we assume we don't have a huge load and a lot of concurrent access ;-) if ( alreadyExistsProfileName( profile ) ) { throw new AlreadyExistsProfileException( "profile with name " + profile.getName() + " already exists" ); } } try { Profile stored = getProfile( profile.getId() ); stored.setActive( profile.isActive() ); stored.setBuilder( profile.getBuilder() ); stored.setBuildWithoutChanges( profile.isBuildWithoutChanges() ); stored.setDescription( profile.getDescription() ); stored.setJdk( profile.getJdk() ); stored.setName( profile.getName() ); stored.setEnvironmentVariables( profile.getEnvironmentVariables() ); stored.setBuildAgentGroup( profile.getBuildAgentGroup() ); profileDao.updateProfile( stored ); } catch ( ContinuumStoreException e ) { throw new ProfileException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.profile.ProfileService#addProfile(org.apache.maven.continuum.model.system.Profile) */ public Profile addProfile( Profile profile ) throws ProfileException, AlreadyExistsProfileException { // already exists check should be done in the same transaction // but we assume we don't have a huge load and a lot of concurrent access ;-) if ( alreadyExistsProfileName( profile ) ) { throw new AlreadyExistsProfileException( "profile with name " + profile.getName() + " already exists" ); } profile.setBuilder( null ); profile.setJdk( null ); profile.setEnvironmentVariables( null ); return profileDao.addProfile( profile ); } /** * @see org.apache.maven.continuum.profile.ProfileService#deleteProfile(int) */ public void deleteProfile( int profileId ) throws ProfileException { try { profileDao.removeProfile( getProfile( profileId ) ); } catch ( Exception e ) { throw new ProfileException( "Cannot remove the profile", e ); } } /** * @see org.apache.maven.continuum.profile.ProfileService#getAllProfiles() */ public List<Profile> getAllProfiles() throws ProfileException { return profileDao.getAllProfilesByName(); } /** * @see org.apache.maven.continuum.profile.ProfileService#getProfile(int) */ public Profile getProfile( int profileId ) throws ProfileException { try { return profileDao.getProfile( profileId ); } catch ( ContinuumObjectNotFoundException e ) { // really ignore ? return null; } catch ( ContinuumStoreException e ) { throw new ProfileException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.profile.ProfileService#setBuilderInProfile(org.apache.maven.continuum.model.system.Profile, org.apache.maven.continuum.model.system.Installation) */ public void setBuilderInProfile( Profile profile, Installation builder ) throws ProfileException { Profile stored = getProfile( profile.getId() ); stored.setBuilder( builder ); try { profileDao.updateProfile( stored ); } catch ( ContinuumStoreException e ) { throw new ProfileException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.profile.ProfileService#setJdkInProfile(org.apache.maven.continuum.model.system.Profile, org.apache.maven.continuum.model.system.Installation) */ public void setJdkInProfile( Profile profile, Installation jdk ) throws ProfileException { Profile stored = getProfile( profile.getId() ); stored.setJdk( jdk ); try { profileDao.updateProfile( stored ); } catch ( ContinuumStoreException e ) { throw new ProfileException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.profile.ProfileService#addEnvVarInProfile(org.apache.maven.continuum.model.system.Profile, org.apache.maven.continuum.model.system.Installation) */ public void addEnvVarInProfile( Profile profile, Installation envVar ) throws ProfileException { Profile stored = getProfile( profile.getId() ); stored.addEnvironmentVariable( envVar ); try { profileDao.updateProfile( stored ); } catch ( ContinuumStoreException e ) { throw new ProfileException( e.getMessage(), e ); } } public void addInstallationInProfile( Profile profile, Installation installation ) throws ProfileException { if ( InstallationService.JDK_TYPE.equals( installation.getType() ) ) { setJdkInProfile( profile, installation ); } else if ( InstallationService.MAVEN1_TYPE.equals( installation.getType() ) || InstallationService.MAVEN2_TYPE.equals( installation.getType() ) || InstallationService.ANT_TYPE.equals( installation.getType() ) ) { setBuilderInProfile( profile, installation ); } else { addEnvVarInProfile( profile, installation ); } } public void removeInstallationFromProfile( Profile profile, Installation installation ) throws ProfileException { Profile stored = getProfile( profile.getId() ); if ( InstallationService.JDK_TYPE.equals( installation.getType() ) ) { stored.setJdk( null ); } else if ( InstallationService.MAVEN1_TYPE.equals( installation.getType() ) || InstallationService.MAVEN2_TYPE.equals( installation.getType() ) || InstallationService.ANT_TYPE.equals( installation.getType() ) ) { stored.setBuilder( null ); } else { // remove one List<Installation> storedEnvVars = stored.getEnvironmentVariables(); List<Installation> newEnvVars = new ArrayList<Installation>(); for ( Installation storedInstallation : storedEnvVars ) { if ( !StringUtils.equals( storedInstallation.getName(), installation.getName() ) ) { newEnvVars.add( storedInstallation ); } } stored.setEnvironmentVariables( newEnvVars ); } try { updateProfileCheckDuplicateName( stored, false ); } catch ( AlreadyExistsProfileException e ) { // normally cannot happend here but anyway we throw the exception throw new ProfileException( e.getMessage(), e ); } } public Profile getProfileWithName( String profileName ) throws ProfileException { List<Profile> allProfiles = getAllProfiles(); for ( Profile profile : allProfiles ) { if ( StringUtils.equals( profile.getName(), profileName ) ) { return profile; } } return null; } /** * @param profile * @return true if profile with same name (<b>case sensitive</b>) exists * @throws ProfileException */ public boolean alreadyExistsProfileName( Profile profile ) throws ProfileException { Profile storedProfile = getProfileWithName( profile.getName() ); return ( storedProfile != null && storedProfile.getId() != profile.getId() ); } }
5,450
0
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-commons/src/main/java/org/apache/continuum/buildqueue/DefaultBuildQueueService.java
package org.apache.continuum.buildqueue; /* * 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.BuildQueueDao; import org.apache.continuum.dao.ScheduleDao; 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.util.List; import javax.annotation.Resource; /** * DefaultBuildQueueService * * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a> */ public class DefaultBuildQueueService implements BuildQueueService { @Resource private BuildQueueDao buildQueueDao; @Resource private ScheduleDao scheduleDao; public BuildQueue addBuildQueue( BuildQueue buildQueue ) throws BuildQueueServiceException { try { return buildQueueDao.addBuildQueue( buildQueue ); } catch ( ContinuumStoreException e ) { throw new BuildQueueServiceException( e ); } } public List<BuildQueue> getAllBuildQueues() throws BuildQueueServiceException { try { return buildQueueDao.getAllBuildQueues(); } catch ( ContinuumStoreException e ) { throw new BuildQueueServiceException( e ); } } public BuildQueue getBuildQueue( int buildQueueId ) throws BuildQueueServiceException { try { return buildQueueDao.getBuildQueue( buildQueueId ); } catch ( ContinuumStoreException e ) { throw new BuildQueueServiceException( e ); } } public BuildQueue getBuildQueueByName( String buildQueueName ) throws BuildQueueServiceException { try { return buildQueueDao.getBuildQueueByName( buildQueueName ); } catch ( ContinuumStoreException e ) { throw new BuildQueueServiceException( e ); } } public void removeBuildQueue( BuildQueue buildQueue ) throws BuildQueueServiceException { try { // detach from schedule(s) first List<Schedule> schedules = scheduleDao.getAllSchedulesByName(); for ( Schedule schedule : schedules ) { List<BuildQueue> buildQueues = schedule.getBuildQueues(); if ( buildQueues.contains( buildQueue ) ) { buildQueues.remove( buildQueue ); } schedule.setBuildQueues( buildQueues ); scheduleDao.updateSchedule( schedule ); } buildQueueDao.removeBuildQueue( buildQueue ); } catch ( ContinuumStoreException e ) { throw new BuildQueueServiceException( e ); } } public BuildQueue updateBuildQueue( BuildQueue buildQueue ) throws BuildQueueServiceException { try { return buildQueueDao.storeBuildQueue( buildQueue ); } catch ( ContinuumStoreException e ) { throw new BuildQueueServiceException( e ); } } public BuildQueueDao getBuildQueueDao() { return buildQueueDao; } public void setBuildQueueDao( BuildQueueDao buildQueueDao ) { this.buildQueueDao = buildQueueDao; } public ScheduleDao getScheduleDao() { return scheduleDao; } public void setScheduleDao( ScheduleDao scheduleDao ) { this.scheduleDao = scheduleDao; } }
5,451
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/AddMavenProjectActionTest.java
package org.apache.maven.continuum.web.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 com.opensymphony.xwork2.Action; import org.apache.continuum.web.action.AbstractActionTest; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.web.action.stub.AddMavenProjectStub; import org.junit.Before; import org.junit.Test; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Verifies {@link org.apache.maven.continuum.web.action.AddMavenProjectAction}. */ public class AddMavenProjectActionTest extends AbstractActionTest { private AddMavenProjectStub action; private HttpServletRequest request; @Before public void setUp() throws Exception { request = mock( HttpServletRequest.class ); action = new AddMavenProjectStub(); action.setServletRequest( request ); } @Test public void testHttpUrlConstructionWithCreds() throws BuildDefinitionServiceException, ContinuumException, MalformedURLException, UnsupportedEncodingException { String scheme = "http"; String host = "www.example.com"; String port = "8080"; String path = "/project/path/perhaps"; String query = "fileName=pom.xml&project=Project%20Name"; String username = "batkinson@apache.org"; String password = "p&s/W:rd"; String encoding = "UTF-8"; String urlToFetch = String.format( "%s://%s:%s%s?%s", scheme, host, port, path, query ); action.setPomUrl( urlToFetch ); action.setScmUsername( username ); action.setScmPassword( password ); when( request.getCharacterEncoding() ).thenReturn( encoding ); String result = action.execute(); assertEquals( "action should have succeeded", Action.SUCCESS, result ); URL builtUrl = new URL( action.getPom() ); String expectedUserInfo = String.format( "%s:%s", URLEncoder.encode( username, encoding ), URLEncoder.encode( password, encoding ) ); assertEquals( "url should include encoded user information", expectedUserInfo, builtUrl.getUserInfo() ); assertEquals( "url should include original protocol scheme", scheme, builtUrl.getProtocol() ); assertEquals( "url should include original host", host, builtUrl.getHost() ); assertEquals( "url should include original port", port, Integer.toString( builtUrl.getPort() ) ); assertEquals( "url should include original path ", path, builtUrl.getPath() ); assertEquals( "url should include original query params", query, builtUrl.getQuery() ); } }
5,452
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/ContinuumActionLoggingTest.java
package org.apache.maven.continuum.web.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.maven.continuum.PlexusSpringTestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import static org.junit.Assert.assertTrue; /** * TestContinuumActionLogging: * * @author jesse */ public class ContinuumActionLoggingTest extends PlexusSpringTestCase { StringBuffer testOutput = new StringBuffer(); @Before public void setUp() throws Exception { PrintStream systemPrintStream = new PrintStream( new FilteredStream( System.out ), true ); System.setOut( systemPrintStream ); } @After public void tearDown() { System.setOut( new PrintStream( new BufferedOutputStream( new FileOutputStream( java.io.FileDescriptor.out ), 128 ), true ) ); } @Test public void testActionLogging() throws Exception { TestAction testAction = (TestAction) lookup( "com.opensymphony.xwork2.Action", "testAction" ); String testString = "action test string"; testAction.setTestString( testString ); testAction.execute(); assertTrue( testOutput.toString().indexOf( testString ) != -1 ); } class FilteredStream extends FilterOutputStream { OutputStream stream; public FilteredStream( OutputStream stream ) { super( stream ); this.stream = stream; } public void write( byte byteArray[] ) throws IOException { testOutput.append( new String( byteArray ) ); stream.write( byteArray ); } public void write( byte byteArray[], int offset, int length ) throws IOException { testOutput.append( new String( byteArray, offset, length ) ); stream.write( byteArray, offset, length ); } } }
5,453
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/AddProjectActionTest.java
package org.apache.maven.continuum.web.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.web.action.AbstractActionTest; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.action.stub.AddProjectActionStub; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.*; /** * Test for {@link AddProjectAction} * * @author <a href="mailto:jzurbano@apache.org">jzurbano</a> */ public class AddProjectActionTest extends AbstractActionTest { private AddProjectActionStub action; private Continuum continuum; private static final String VALID_NAME_CHARACTER = "abcABC123whitespaces_.:-"; private static final String VALID_VERSION_CHARACTER = "abcABC123.-"; private static final String VALID_SCM_URL_CHARACTER = "abcABC123_.:-#~=@\\/|[]"; private static final String VALID_SCM_TAG_CHARACTER = "abcABC123_.:-#~=@\\/|[]"; private static final String VALID_DESCRIPTION_CHARACTER = "abcABC123whitespaces_.-"; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); action = new AddProjectActionStub(); action.setContinuum( continuum ); Collection<ProjectGroup> projectGroups = new ArrayList<ProjectGroup>(); ProjectGroup projectGroup = new ProjectGroup(); projectGroups.add( projectGroup ); action.setProjectGroups( projectGroups ); List<Project> projects = createProjectList(); when( continuum.getProjects() ).thenReturn( projects ); when( continuum.addProject( any( Project.class ), anyString(), anyInt(), anyInt() ) ).thenReturn( 3 ); } @Test public void testAddProjectNullValues() throws Exception { action.setProjectName( null ); action.setProjectVersion( null ); action.setProjectScmUrl( null ); action.validate(); } /** * Test add of Ant project * * @throws Exception */ @Test public void testAddAntProject() throws Exception { String scmUrl = "scm:svn:http://project/scm/url/test/build.xml"; action.setProjectName( "Ant Test Project" ); action.setProjectVersion( "1.0-SNAPSHOT" ); action.setProjectScmUrl( scmUrl ); action.setProjectType( "ant" ); action.setSelectedProjectGroup( 1 ); action.setBuildDefintionTemplateId( 1 ); action.validate(); action.add(); } @Test public void testAddAntProjectWithValidValues() throws Exception { action.setProjectName( VALID_NAME_CHARACTER ); action.setProjectDescription( VALID_DESCRIPTION_CHARACTER ); action.setProjectVersion( VALID_VERSION_CHARACTER ); action.setProjectScmUrl( VALID_SCM_URL_CHARACTER ); action.setProjectScmTag( VALID_SCM_TAG_CHARACTER ); action.setProjectType( "ant" ); action.setSelectedProjectGroup( 1 ); action.setBuildDefintionTemplateId( 1 ); // validate action.validate(); // verify assertFalse( action.hasActionErrors() ); assertEquals( 0, action.getActionErrors().size() ); // add action.add(); } /** * Test add of Shell project * * @throws Exception */ @Test public void testAddShellProject() throws Exception { String scmUrl = "scm:svn:http://project/scm/url/test/run.sh"; action.setProjectName( "Shell Test Project" ); action.setProjectVersion( "1.0-SNAPSHOT" ); action.setProjectScmUrl( scmUrl ); action.setProjectType( "shell" ); action.setSelectedProjectGroup( 1 ); action.setBuildDefintionTemplateId( 1 ); action.validate(); action.add(); } @Test public void testAddShellProjectWithValidValues() throws Exception { action.setProjectName( VALID_NAME_CHARACTER ); action.setProjectDescription( VALID_DESCRIPTION_CHARACTER ); action.setProjectVersion( VALID_VERSION_CHARACTER ); action.setProjectScmUrl( VALID_SCM_URL_CHARACTER ); action.setProjectScmTag( VALID_SCM_TAG_CHARACTER ); action.setProjectType( "shell" ); action.setSelectedProjectGroup( 1 ); action.setBuildDefintionTemplateId( 1 ); // validate action.validate(); // verify assertFalse( action.hasActionErrors() ); assertEquals( 0, action.getActionErrors().size() ); // add action.add(); } private List<Project> createProjectList() { List<Project> projects = new ArrayList<Project>(); Project project1 = createProject( "scm:svn:http://project/scm/url/test-1/run.sh", "Shell Test Project 1", "1.0-SNAPSHOT", 1 ); Project project2 = createProject( "scm:svn:http://project/scm/url/test-2/build.xml", "Ant Test Project 1", "1.0-SNAPSHOT", 2 ); projects.add( project1 ); projects.add( project2 ); return projects; } private Project createProject( String scmUrl, String name, String version, int id ) { Project project = new Project(); project.setId( id ); project.setName( name ); project.setVersion( version ); project.setScmUrl( scmUrl ); return project; } }
5,454
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/BuildResultActionTest.java
package org.apache.maven.continuum.web.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 com.opensymphony.xwork2.Action; import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.model.project.ProjectRunSummary; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.web.action.AbstractActionTest; import org.apache.maven.continuum.Continuum; 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.project.ContinuumProjectState; import org.apache.maven.continuum.web.action.stub.BuildResultActionStub; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class BuildResultActionTest extends AbstractActionTest { private BuildResultActionStub action; private Continuum continuum; private ConfigurationService configurationService; private DistributedBuildManager distributedBuildManager; private BuildsManager buildsManager; private Project project; private BuildResult buildResult; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); configurationService = mock( ConfigurationService.class ); distributedBuildManager = mock( DistributedBuildManager.class ); buildsManager = mock( BuildsManager.class ); action = new BuildResultActionStub(); action.setContinuum( continuum ); action.setDistributedBuildManager( distributedBuildManager ); project = createProject( "stub-project" ); when( continuum.getProject( anyInt() ) ).thenReturn( project ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( continuum.getBuildsManager() ).thenReturn( buildsManager ); buildResult = createBuildResult( project ); when( continuum.getBuildResult( anyInt() ) ).thenReturn( buildResult ); } @Test public void testViewPreviousBuild() throws Exception { when( configurationService.isDistributedBuildEnabled() ).thenReturn( false ); when( configurationService.getTestReportsDirectory( anyInt(), anyInt() ) ).thenReturn( new File( "testReportsDir" ) ); when( continuum.getChangesSinceLastSuccess( anyInt(), anyInt() ) ).thenReturn( null ); when( configurationService.getBuildOutputFile( anyInt(), anyInt() ) ).thenReturn( new File( "buildOutputFile" ) ); when( buildsManager.getCurrentBuilds() ).thenReturn( new HashMap<String, BuildProjectTask>() ); assertEquals( Action.SUCCESS, action.execute() ); } @Test public void testViewCurrentBuildInDistributedBuildAgent() throws Exception { int expectedResultId = 777; action.setBuildId( expectedResultId ); buildResult.setState( org.apache.maven.continuum.project.ContinuumProjectState.BUILDING ); ProjectRunSummary runSummary = new ProjectRunSummary(); runSummary.setBuildResultId( expectedResultId ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( true ); when( distributedBuildManager.getBuildResult( anyInt() ) ).thenReturn( new HashMap<String, Object>() ); when( distributedBuildManager.getCurrentRun( anyInt(), anyInt() ) ).thenReturn( runSummary ); assertEquals( Action.SUCCESS, action.execute() ); verify( distributedBuildManager ).getBuildResult( anyInt() ); } @Test public void testSuccessfulWhenTestDirThrows() throws Exception { when( configurationService.getTestReportsDirectory( anyInt(), anyInt() ) ).thenThrow( new ConfigurationException( "failed creating dir" ) ); when( configurationService.getBuildOutputFile( anyInt(), anyInt() ) ).thenReturn( new File( "non-existent" ) ); assertEquals( Action.SUCCESS, action.execute() ); } @Test public void testSuccessfulWhenBuildOutputDirThrows() throws Exception { when( configurationService.getTestReportsDirectory( anyInt(), anyInt() ) ).thenReturn( new File( "non-existent" ) ); when( configurationService.getBuildOutputFile( anyInt(), anyInt() ) ).thenThrow( new ConfigurationException( "failed creating dir" ) ); assertEquals( Action.SUCCESS, action.execute() ); } private Project createProject( String name ) { Project project = new Project(); project.setId( 1 ); project.setName( name ); project.setArtifactId( "foo:bar" ); project.setVersion( "1.0" ); project.setState( ContinuumProjectState.BUILDING ); return project; } private BuildResult createBuildResult( Project project ) { BuildResult buildResult = new BuildResult(); buildResult.setId( 1 ); buildResult.setProject( project ); buildResult.setBuildDefinition( new BuildDefinition() ); return buildResult; } }
5,455
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/SummaryActionTest.java
package org.apache.maven.continuum.web.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.buildmanager.BuildsManager; import org.apache.continuum.web.action.AbstractActionTest; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.configuration.ConfigurationService; 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.web.action.stub.SummaryActionStub; import org.apache.maven.continuum.web.model.ProjectSummary; import org.apache.maven.continuum.xmlrpc.project.ContinuumProjectState; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.opensymphony.xwork2.Action.SUCCESS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.*; public class SummaryActionTest extends AbstractActionTest { private SummaryActionStub action; private Continuum continuum; private ConfigurationService configurationService; private BuildsManager buildsManager; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); configurationService = mock( ConfigurationService.class ); buildsManager = mock( BuildsManager.class ); action = new SummaryActionStub(); action.setContinuum( continuum ); action.setParallelBuildsManager( buildsManager ); } @Test public void testLatestBuildIdInDistributedBuild() throws Exception { Collection<Project> projectsInGroup = createProjectsInGroup( 1, ContinuumProjectState.OK ); Map<Integer, BuildResult> buildResults = createBuildResults( 1, ContinuumProjectState.OK ); Map<Integer, BuildResult> buildResultsInSuccess = new HashMap<Integer, BuildResult>(); when( continuum.getProjectsInGroup( anyInt() ) ).thenReturn( projectsInGroup ); when( continuum.getLatestBuildResults( anyInt() ) ).thenReturn( buildResults ); when( continuum.getBuildResultsInSuccess( anyInt() ) ).thenReturn( buildResultsInSuccess ); when( buildsManager.isInAnyBuildQueue( anyInt() ) ).thenReturn( false ); when( buildsManager.isInPrepareBuildQueue( anyInt() ) ).thenReturn( false ); when( buildsManager.isInAnyCheckoutQueue( anyInt() ) ).thenReturn( false ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( true ); assertEquals( SUCCESS, action.browse() ); List<ProjectSummary> projects = action.getProjects(); assertNotNull( projects ); assertEquals( 1, projects.size() ); ProjectSummary summary = projects.get( 0 ); assertEquals( 1, summary.getLatestBuildId() ); } @Test public void testLatestBuildIdWhenCurrentlyBuilding() throws Exception { Collection<Project> projectsInGroup = createProjectsInGroup( 1, ContinuumProjectState.BUILDING ); Map<Integer, BuildResult> buildResults = createBuildResults( 1, ContinuumProjectState.BUILDING ); Map<Integer, BuildResult> buildResultsInSuccess = new HashMap<Integer, BuildResult>(); when( continuum.getProjectsInGroup( anyInt() ) ).thenReturn( projectsInGroup ); when( continuum.getLatestBuildResults( anyInt() ) ).thenReturn( buildResults ); when( continuum.getBuildResultsInSuccess( anyInt() ) ).thenReturn( buildResultsInSuccess ); when( buildsManager.isInAnyBuildQueue( anyInt() ) ).thenReturn( false ); when( buildsManager.isInPrepareBuildQueue( anyInt() ) ).thenReturn( false ); when( buildsManager.isInAnyCheckoutQueue( anyInt() ) ).thenReturn( false ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( false ); assertEquals( SUCCESS, action.browse() ); List<ProjectSummary> projects = action.getProjects(); assertNotNull( projects ); assertEquals( 1, projects.size() ); ProjectSummary summary = projects.get( 0 ); assertEquals( 1, summary.getLatestBuildId() ); } private Collection<Project> createProjectsInGroup( int projectId, int state ) { Collection<Project> projectsInGroup = new ArrayList<Project>(); ProjectGroup group = new ProjectGroup(); group.setId( 1 ); group.setName( "test-group" ); Project project = new Project(); project.setId( projectId ); project.setName( "test-project" ); project.setVersion( "1.0" ); project.setBuildNumber( 1 ); project.setState( state ); project.setExecutorId( "maven2" ); project.setProjectGroup( group ); projectsInGroup.add( project ); return projectsInGroup; } private Map<Integer, BuildResult> createBuildResults( int projectId, int state ) { Map<Integer, BuildResult> buildResults = new HashMap<Integer, BuildResult>(); BuildResult br = new BuildResult(); br.setId( 1 ); br.setStartTime( System.currentTimeMillis() ); br.setEndTime( System.currentTimeMillis() ); br.setState( state ); buildResults.put( projectId, br ); return buildResults; } }
5,456
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/ProjectGroupActionTest.java
package org.apache.maven.continuum.web.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 com.opensymphony.xwork2.Action; import org.apache.continuum.web.action.AbstractActionTest; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.action.stub.ProjectGroupActionStub; import org.apache.maven.continuum.web.bean.ProjectGroupUserBean; import org.codehaus.plexus.redback.rbac.RBACManager; import org.codehaus.plexus.redback.rbac.Role; import org.codehaus.plexus.redback.rbac.UserAssignment; import org.codehaus.plexus.redback.rbac.jdo.JdoRole; import org.codehaus.plexus.redback.rbac.jdo.JdoUserAssignment; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class ProjectGroupActionTest extends AbstractActionTest { private ProjectGroupActionStub action; private Continuum continuum; private RBACManager rbac; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); rbac = mock( RBACManager.class ); action = new ProjectGroupActionStub(); action.setContinuum( continuum ); action.setRbacManager( rbac ); } @Test public void testViewMembersWithProjectAdminRole() throws Exception { ProjectGroup group = new ProjectGroup(); group.setName( "Project A" ); List<Role> roles = new ArrayList<Role>(); Role role1 = new JdoRole(); role1.setName( "Project User - Project A" ); roles.add( role1 ); Role role2 = new JdoRole(); role2.setName( "Continuum Manage Scheduling" ); roles.add( role2 ); Role role3 = new JdoRole(); role3.setName( "Project Developer - Project A" ); roles.add( role3 ); Role role4 = new JdoRole(); role4.setName( "Project Administrator - Project A" ); roles.add( role4 ); List<UserAssignment> userAssignments = new ArrayList<UserAssignment>(); UserAssignment ua1 = new JdoUserAssignment(); ua1.setPrincipal( "user1" ); userAssignments.add( ua1 ); List<Role> eRoles = roles; when( continuum.getProjectGroupWithProjects( anyInt() ) ).thenReturn( group ); when( rbac.getAllRoles() ).thenReturn( roles ); when( rbac.getUserAssignmentsForRoles( anyCollection() ) ).thenReturn( userAssignments ); when( rbac.getEffectivelyAssignedRoles( anyString() ) ).thenReturn( eRoles ); assertEquals( Action.SUCCESS, action.members() ); List<ProjectGroupUserBean> users = action.getProjectGroupUsers(); assertEquals( 1, users.size() ); assertTrue( users.get( 0 ).isAdministrator() ); assertTrue( users.get( 0 ).isDeveloper() ); assertTrue( users.get( 0 ).isUser() ); } @Test public void testViewMembersWithProjectUserRole() throws Exception { ProjectGroup group = new ProjectGroup(); group.setName( "Project A" ); List<Role> roles = new ArrayList<Role>(); Role role1 = new JdoRole(); role1.setName( "Project User - Project A" ); roles.add( role1 ); Role role2 = new JdoRole(); role2.setName( "Continuum Manage Scheduling" ); roles.add( role2 ); Role role3 = new JdoRole(); role3.setName( "Project Developer - test-group" ); roles.add( role3 ); Role role4 = new JdoRole(); role4.setName( "Project Administrator - test-group" ); roles.add( role4 ); Role role5 = new JdoRole(); role5.setName( "Project Administrator - Project C" ); roles.add( role5 ); List<UserAssignment> userAssignments = new ArrayList<UserAssignment>(); UserAssignment ua1 = new JdoUserAssignment(); ua1.setPrincipal( "user1" ); userAssignments.add( ua1 ); List<Role> eRoles = new ArrayList<Role>(); eRoles.add( role1 ); eRoles.add( role2 ); eRoles.add( role5 ); when( continuum.getProjectGroupWithProjects( anyInt() ) ).thenReturn( group ); when( rbac.getAllRoles() ).thenReturn( roles ); when( rbac.getUserAssignmentsForRoles( anyCollection() ) ).thenReturn( userAssignments ); when( rbac.getEffectivelyAssignedRoles( anyString() ) ).thenReturn( eRoles ); assertEquals( Action.SUCCESS, action.members() ); List<ProjectGroupUserBean> users = action.getProjectGroupUsers(); assertEquals( 1, users.size() ); assertFalse( users.get( 0 ).isAdministrator() ); assertFalse( users.get( 0 ).isDeveloper() ); assertTrue( users.get( 0 ).isUser() ); } }
5,457
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/ReleasePrepareActionTest.java
package org.apache.maven.continuum.web.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.web.action.AbstractActionTest; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.model.project.Project; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; /** * Test for {@link ReleasePrepareAction} * * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a> */ public class ReleasePrepareActionTest extends AbstractActionTest { private ReleasePrepareAction action; private Continuum continuum; @Before public void setUp() throws Exception { action = new ReleasePrepareAction(); continuum = mock( Continuum.class ); //securitySessionMock = mock( SecuritySession.class ); //Map map = new HashMap(); //map.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySessionMock ); //action.setSession( map ); action.setContinuum( continuum ); } /** * Test that the tag base url for Subversion is correctly constructed * * @throws Exception */ @Test public void testScmTagBaseSvn() throws Exception { //commented out because of problems in authorization checks String svnUrl = "https://svn.apache.org/repos/asf/maven/continuum"; String scmUrl = "scm:svn:" + svnUrl + "/trunk/"; //ProjectGroup projectGroup = new ProjectGroup(); //continuum.expects( once() ).method( "getProjectGroupByProjectId" ).will( returnValue( projectGroup ) ); Project project = new Project(); project.setScmUrl( scmUrl ); project.setWorkingDirectory( "." ); when( continuum.getProject( anyInt() ) ).thenReturn( project ); action.input(); // expected result? assertEquals( svnUrl + "/tags", action.getScmTagBase() ); } /** * Test that tag base url for non Subverson SCMs is empty * * @throws Exception */ @Test public void testScmTagBaseNonSvn() throws Exception { //commented out because of problems in authorization checks Project project = new Project(); project.setScmUrl( "scm:cvs:xxx" ); project.setWorkingDirectory( "." ); when( continuum.getProject( anyInt() ) ).thenReturn( project ); action.input(); // expected result? assertEquals( "", action.getScmTagBase() ); } }
5,458
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/BuildAgentActionTest.java
package org.apache.maven.continuum.web.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.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.web.action.AbstractActionTest; import org.apache.continuum.web.action.admin.BuildAgentAction; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.configuration.ConfigurationService; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.*; public class BuildAgentActionTest extends AbstractActionTest { private BuildAgentAction action; private Continuum continuum; private ConfigurationService configurationService; private DistributedBuildManager distributedBuildManager; private List<BuildAgentConfiguration> buildAgents; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); configurationService = mock( ConfigurationService.class ); distributedBuildManager = mock( DistributedBuildManager.class ); action = new BuildAgentAction(); action.setContinuum( continuum ); buildAgents = new ArrayList<BuildAgentConfiguration>(); } @Test public void testAddBuildAgent() throws Exception { when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgents() ).thenReturn( buildAgents ); when( continuum.getDistributedBuildManager() ).thenReturn( distributedBuildManager ); BuildAgentConfiguration buildAgent = new BuildAgentConfiguration(); buildAgent.setUrl( "http://sample/agent" ); action.setBuildAgent( buildAgent ); action.save(); verify( configurationService ).addBuildAgent( any( BuildAgentConfiguration.class ) ); verify( configurationService ).store(); verify( distributedBuildManager ).update( any( BuildAgentConfiguration.class ) ); } @Test public void testDeleteBuildAgent() throws Exception { List<BuildAgentGroupConfiguration> buildAgentGroups = new ArrayList<BuildAgentGroupConfiguration>(); when( continuum.getDistributedBuildManager() ).thenReturn( distributedBuildManager ); when( distributedBuildManager.isBuildAgentBusy( anyString() ) ).thenReturn( false ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroups() ).thenReturn( buildAgentGroups ); when( configurationService.getBuildAgents() ).thenReturn( buildAgents ); BuildAgentConfiguration buildAgent = new BuildAgentConfiguration(); buildAgent.setUrl( "http://sample/agent" ); action.setConfirmed( true ); action.setBuildAgent( buildAgent ); action.delete(); verify( distributedBuildManager, never() ).removeDistributedBuildQueueOfAgent( anyString() ); verify( distributedBuildManager, never() ).reload(); verify( configurationService, never() ).removeBuildAgent( any( BuildAgentConfiguration.class ) ); verify( configurationService, never() ).store(); } }
5,459
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/TestAction.java
package org.apache.maven.continuum.web.action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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. */ /** * TestAction: * * @author jesse */ public class TestAction extends PlexusActionSupport { private static final Logger logger = LoggerFactory.getLogger( TestAction.class ); private String testString; public String execute() throws Exception { logger.info( testString ); return INPUT; } public String getTestString() { return testString; } public void setTestString( String testString ) { this.testString = testString; } }
5,460
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/stub/AddMavenProjectStub.java
package org.apache.maven.continuum.web.action.stub; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.continuum.web.action.AddMavenProjectAction; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; /** * A stubbed implementation of {@link org.apache.maven.continuum.web.action.AddMavenProjectAction} useful for testing * the abstract class's functionality. */ public class AddMavenProjectStub extends AddMavenProjectAction { @Override protected void checkAddProjectGroupAuthorization() throws AuthorizationRequiredException { // skip authorization check } @Override protected ContinuumProjectBuildingResult doExecute( String pomUrl, int selectedProjectGroup, boolean checkProtocol, boolean scmUseCache ) throws ContinuumException { return new ContinuumProjectBuildingResult(); } }
5,461
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/stub/AddProjectActionStub.java
package org.apache.maven.continuum.web.action.stub; /* * 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.web.action.AddProjectAction; /** * Stub for {@link AddProjectAction} * * @author <a href="mailto:jzurbano@apache.org">jzurbano</a> */ public class AddProjectActionStub extends AddProjectAction { public String input() { return INPUT; } private void initializeProjectGroupName() { setProjectGroupName( "Test Project Group" ); } private boolean isAuthorizedToAddProjectToGroup( String projectGroupName ) { return true; } protected void checkAddProjectGroupAuthorization() { // skip authorization check } protected void checkAddProjectToGroupAuthorization( String projectGroupName ) { // skip authorization check } }
5,462
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/stub/ProjectGroupActionStub.java
package org.apache.maven.continuum.web.action.stub; /* * 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.web.action.ProjectGroupAction; import org.codehaus.plexus.redback.users.User; import org.codehaus.plexus.redback.users.UserNotFoundException; import org.codehaus.plexus.redback.users.jdo.JdoUser; public class ProjectGroupActionStub extends ProjectGroupAction { public String getProjectGroupName() { return "test-group"; } protected void checkViewProjectGroupAuthorization( String resource ) { // skip authorization check } protected User getUser( String principal ) throws UserNotFoundException { User user = new JdoUser(); user.setUsername( principal ); return user; } }
5,463
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/stub/SummaryActionStub.java
package org.apache.maven.continuum.web.action.stub; /* * 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.web.action.SummaryAction; public class SummaryActionStub extends SummaryAction { public String getProjectGroupName() { return "test-group"; } protected void checkViewProjectGroupAuthorization( String resource ) { // skip authorization check } }
5,464
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/maven/continuum/web/action/stub/BuildResultActionStub.java
package org.apache.maven.continuum.web.action.stub; /* * 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.web.action.BuildResultAction; public class BuildResultActionStub extends BuildResultAction { public String getProjectGroupName() { return "test-group"; } protected void checkViewProjectGroupAuthorization( String resource ) { // skip authorization check } }
5,465
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action/AbstractActionTest.java
package org.apache.continuum.web.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 com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.config.ConfigurationManager; import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.util.ValueStackFactory; import org.junit.Before; import static org.junit.Assert.assertNotNull; public abstract class AbstractActionTest { @Before public void setUpActionContext() throws Exception { if ( ActionContext.getContext() == null ) { // This fix allow initialization of ActionContext.getContext() to avoid NPE ConfigurationManager configurationManager = new ConfigurationManager(); configurationManager.addContainerProvider( new XWorkConfigurationProvider() ); com.opensymphony.xwork2.config.Configuration config = configurationManager.getConfiguration(); Container container = config.getContainer(); ValueStack stack = container.getInstance( ValueStackFactory.class ).createValueStack(); stack.getContext().put( ActionContext.CONTAINER, container ); ActionContext.setContext( new ActionContext( stack.getContext() ) ); assertNotNull( ActionContext.getContext() ); } } }
5,466
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action/ViewBuildsReportActionTest.java
package org.apache.continuum.web.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 com.opensymphony.xwork2.Action; import org.apache.continuum.web.action.stub.ViewBuildsReportActionStub; import org.apache.maven.continuum.Continuum; 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.codehaus.plexus.redback.system.SecuritySession; import org.junit.Before; import org.junit.Test; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class ViewBuildsReportActionTest extends AbstractActionTest { private ViewBuildsReportActionStub action; private Continuum continuum; private List<BuildResult> buildResults = new ArrayList<BuildResult>(); private ProjectGroup allowedGroup; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); action = new ViewBuildsReportActionStub(); action.setSecuritySession( mock( SecuritySession.class ) ); action.setContinuum( continuum ); allowedGroup = new ProjectGroup(); allowedGroup.setId( 1 ); allowedGroup.setName( "Allowed Group" ); action.setAuthorizedGroups( Arrays.asList( allowedGroup ) ); action.prepare(); } @Test public void testEndDateBeforeStartDate() { action.setStartDate( "04/25/2010" ); action.setEndDate( "04/24/2010" ); String result = action.execute(); assertEquals( Action.INPUT, result ); assertTrue( action.hasFieldErrors() ); assertFalse( action.hasActionErrors() ); } @Test public void testMalformedStartDate() { action.setStartDate( "not a date" ); String result = action.execute(); assertEquals( Action.INPUT, result ); assertTrue( action.hasActionErrors() ); assertFalse( action.hasFieldErrors() ); } @Test public void testMalformedEndDate() { action.setEndDate( "not a date" ); String result = action.execute(); assertEquals( Action.INPUT, result ); assertTrue( action.hasActionErrors() ); assertFalse( action.hasFieldErrors() ); } @Test public void testStartDateSameWithEndDate() { when( continuum.getBuildResultsInRange( anyCollection(), any( Date.class ), any( Date.class ), anyInt(), anyString(), anyInt(), anyInt() ) ).thenReturn( buildResults ); action.setStartDate( "04/25/2010" ); action.setEndDate( "04/25/2010" ); String result = action.execute(); assertSuccessResult( result ); } @Test public void testEndDateWithNoStartDate() { when( continuum.getBuildResultsInRange( anyCollection(), any( Date.class ), any( Date.class ), anyInt(), anyString(), anyInt(), anyInt() ) ).thenReturn( buildResults ); action.setEndDate( "04/25/2010" ); String result = action.execute(); assertSuccessResult( result ); } @Test public void testExportToCsv() throws Exception { Calendar cal = Calendar.getInstance(); cal.set( 2010, 1, 1, 1, 1, 1 ); List<BuildResult> results = createBuildResult( cal.getTimeInMillis() ); when( continuum.getBuildResultsInRange( anyCollection(), any( Date.class ), any( Date.class ), anyInt(), anyString(), anyInt(), anyInt() ) ).thenReturn( results ); ByteArrayOutputStream out = new ByteArrayOutputStream(); HttpServletResponse response = mock( HttpServletResponse.class ); when( response.getWriter() ).thenReturn( new PrintWriter( out ) ); action.setServletResponse( response ); action.setProjectGroupId( 0 ); action.setBuildStatus( 0 ); action.setStartDate( "" ); action.setEndDate( "" ); action.setTriggeredBy( "" ); String result = action.downloadBuildsReport(); assertNull( "result should be null", result ); assertExportContents( results, out.toString() ); } private void assertSuccessResult( String result ) { assertEquals( Action.SUCCESS, result ); assertFalse( action.hasFieldErrors() ); assertFalse( action.hasActionErrors() ); } private List<BuildResult> createBuildResult( long timeInMillis ) { List<BuildResult> results = new ArrayList<BuildResult>(); BuildResult result = new BuildResult(); Project project = new Project(); project.setName( "Test Project" ); project.setProjectGroup( allowedGroup ); result.setProject( project ); result.setState( 2 ); result.setStartTime( timeInMillis ); result.setUsername( "test-admin" ); results.add( result ); return results; } private void assertExportContents( List<BuildResult> results, String actualContents ) { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ); String expectedContents = "Group,Project,ID,Build#,Started,Duration,Triggered By,Status\n"; for ( BuildResult result : results ) { Project p = result.getProject(); ProjectGroup pg = p.getProjectGroup(); expectedContents += String.format( "%s,%s,%s,%s,%s,%s,%s,%s\n", pg.getName(), p.getName(), result.getId(), result.getBuildNumber(), dateFormat.format( new Date( result.getStartTime() ) ), ( result.getEndTime() - result.getStartTime() ) / 1000, result.getUsername(), ViewBuildsReportAction.ResultState.fromId( result.getState() ).getTextKey() ); } assertEquals( expectedContents, actualContents ); } }
5,467
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action/AbstractReleaseActionTest.java
package org.apache.continuum.web.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.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.continuum.web.action.stub.ReleaseActionStub; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.system.Profile; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class AbstractReleaseActionTest extends AbstractActionTest { private ReleaseActionStub action; private Continuum continuum; private ConfigurationService configurationService; private String defaultBuildagentUrl = "http://localhost:8181/continuum-buildagent/xmlrpc"; @Before public void setUp() throws Exception { continuum = mock( Continuum.class ); configurationService = mock( ConfigurationService.class ); Profile profile = new Profile(); profile.setBuildAgentGroup( "BUILDAGENT_GROUP" ); action = new ReleaseActionStub(); action.setProfile( profile ); action.setDefaultBuildagent( defaultBuildagentUrl ); action.setContinuum( continuum ); } @Test public void testGetEnvironmentsDefaultAgentInGroup() throws Exception { BuildAgentGroupConfiguration buildAgentGroup = createBuildAgentGroupConfiguration( true ); buildAgentGroup.addBuildAgent( new BuildAgentConfiguration( defaultBuildagentUrl, "Default Build Agent", true ) ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroup( anyString() ) ).thenReturn( buildAgentGroup ); action.getEnvironments(); Map<String, String> envVars = action.getEnvironmentVariables(); String buildagent = envVars.get( DistributedReleaseUtil.KEY_BUILD_AGENT_URL ); assertNotNull( envVars ); assertTrue( "Default build agent is expected to be used.", defaultBuildagentUrl.equals( buildagent ) ); } @Test public void testGetEnvironmentsDefaultAgentNotInGroup() throws Exception { BuildAgentGroupConfiguration buildAgentGroup = createBuildAgentGroupConfiguration( true ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroup( anyString() ) ).thenReturn( buildAgentGroup ); action.getEnvironments(); Map<String, String> envVars = action.getEnvironmentVariables(); String buildagent = envVars.get( DistributedReleaseUtil.KEY_BUILD_AGENT_URL ); assertNotNull( envVars ); assertFalse( "Default build agent is not expected to be used.", defaultBuildagentUrl.equals( buildagent ) ); } @Test public void testGetEnvironmentsNoEnabledAgentInGroup() throws Exception { BuildAgentGroupConfiguration buildAgentGroup = createBuildAgentGroupConfiguration( false ); buildAgentGroup.addBuildAgent( new BuildAgentConfiguration( defaultBuildagentUrl, "Default Build Agent", false ) ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroup( anyString() ) ).thenReturn( buildAgentGroup ); action.getEnvironments(); Map<String, String> envVars = action.getEnvironmentVariables(); String buildagent = envVars.get( DistributedReleaseUtil.KEY_BUILD_AGENT_URL ); assertNotNull( envVars ); assertFalse( "Default build agent is not expected to be used.", defaultBuildagentUrl.equals( buildagent ) ); assertNull( "Build agent should be empty.", buildagent ); } @Test public void testGetEnvironmentsNoAgentInGroup() throws Exception { BuildAgentGroupConfiguration buildAgentGroup = new BuildAgentGroupConfiguration(); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroup( anyString() ) ).thenReturn( buildAgentGroup ); action.getEnvironments(); Map<String, String> envVars = action.getEnvironmentVariables(); String buildagent = envVars.get( DistributedReleaseUtil.KEY_BUILD_AGENT_URL ); assertNotNull( envVars ); assertFalse( "Default build agent is not expected to be used.", defaultBuildagentUrl.equals( buildagent ) ); assertNull( "Build agent should be empty.", buildagent ); } private BuildAgentGroupConfiguration createBuildAgentGroupConfiguration( boolean isAgentEnabled ) { BuildAgentConfiguration buildagent1 = new BuildAgentConfiguration( "http://localhost:9191/continuum-buildagent/xmlrpc", "Other Build Agent", isAgentEnabled ); BuildAgentConfiguration buildagent2 = new BuildAgentConfiguration( "http://localhost:9292/continuum-buildagent/xmlrpc", "Other Build Agent", isAgentEnabled ); List<BuildAgentConfiguration> buildAgents = new ArrayList<BuildAgentConfiguration>(); buildAgents.add( buildagent1 ); buildAgents.add( buildagent2 ); BuildAgentGroupConfiguration buildAgentGroup = new BuildAgentGroupConfiguration( "BUILDAGENT_GROUP", buildAgents ); return buildAgentGroup; } }
5,468
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action/stub/ReleaseActionStub.java
package org.apache.continuum.web.action.stub; /* * 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.web.action.AbstractReleaseAction; import org.apache.maven.continuum.model.system.Profile; import java.util.HashMap; import java.util.Map; public class ReleaseActionStub extends AbstractReleaseAction { private Map<String, String> environmentVariables; private Profile profile; private String defaultBuildagent; public ReleaseActionStub() { this.environmentVariables = new HashMap<String, String>(); } public void getEnvironments() { this.environmentVariables = getEnvironments( profile, defaultBuildagent ); } public Map<String, String> getEnvironmentVariables() { return this.environmentVariables; } public void setProfile( Profile profile ) { this.profile = profile; } public void setDefaultBuildagent( String defaultBuildagent ) { this.defaultBuildagent = defaultBuildagent; } }
5,469
0
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/test/java/org/apache/continuum/web/action/stub/ViewBuildsReportActionStub.java
package org.apache.continuum.web.action.stub; /* * 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.web.action.ViewBuildsReportAction; import org.apache.maven.continuum.model.project.ProjectGroup; import org.codehaus.plexus.redback.system.SecuritySession; import java.util.Collection; import java.util.Collections; public class ViewBuildsReportActionStub extends ViewBuildsReportAction { Collection<ProjectGroup> authorizedGroups = Collections.EMPTY_LIST; public void setSecuritySession( SecuritySession securitySession ) { super.setSecuritySession( securitySession ); } @Override protected Collection<ProjectGroup> getAuthorizedGroups() { return authorizedGroups; } public void setAuthorizedGroups( Collection<ProjectGroup> authorizedGroups ) { this.authorizedGroups = authorizedGroups; } protected void checkViewProjectGroupAuthorization( String resource ) { // skip authorization check } protected void checkViewReportsAuthorization() { // skip authorization check } }
5,470
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/validator/WagonUrlValidator.java
package org.apache.maven.continuum.web.validator; /* * 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.opensymphony.xwork2.validator.ValidationException; import com.opensymphony.xwork2.validator.validators.ValidatorSupport; import java.net.MalformedURLException; import java.net.URL; /** * Validator class for Wagon URLs * * @author <a href="mailto:hisidro@exist.com">Henry Isidro</a> */ public class WagonUrlValidator extends ValidatorSupport { public void validate( Object object ) throws ValidationException { String url = (String) getFieldValue( "url", object ); if ( ( url == null ) || ( url.length() == 0 ) ) { return; } if ( url.startsWith( "dav:" ) ) { url = url.substring( 4 ); } if ( ( url.startsWith( "scp://" ) ) || ( url.startsWith( "sftp://" ) ) ) { // URL doesn't understand these protocols, hack it url = "http://" + url.substring( url.indexOf( "://" ) + 3 ); } try { new URL( url ); } catch ( MalformedURLException m ) { addFieldError( "url", object ); } } }
5,471
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/validator/InstallationValidator.java
package org.apache.maven.continuum.web.validator; /* * 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.opensymphony.xwork2.validator.ValidationException; import com.opensymphony.xwork2.validator.validators.ValidatorSupport; import org.apache.maven.continuum.execution.ExecutorConfigurator; import org.apache.maven.continuum.installation.InstallationException; import org.apache.maven.continuum.installation.InstallationService; 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; /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * @since 19 juin 07 */ @Component( role = com.opensymphony.xwork2.validator.Validator.class, hint = "org.apache.maven.continuum.web.validator.InstallationValidator", instantiationStrategy = "per-lookup" ) public class InstallationValidator extends ValidatorSupport { private String fieldName; private static final Logger logger = LoggerFactory.getLogger( InstallationValidator.class ); @Requirement( hint = "default" ) private InstallationService installationService; /** * @see com.opensymphony.xwork2.validator.Validator#validate(java.lang.Object) */ public void validate( Object object ) throws ValidationException { String name = (String) this.getFieldValue( "installation.name", object ); if ( StringUtils.isEmpty( name ) ) { return; } String varValue = (String) this.getFieldValue( "installation.varValue", object ); if ( StringUtils.isEmpty( varValue ) ) { return; } // TODO validating varValue != null depending on type (not null for envVar) String type = (String) this.getFieldValue( "installation.type", object ); ExecutorConfigurator executorConfigurator = installationService.getExecutorConfigurator( type ); try { if ( executorConfigurator != null ) { if ( executorConfigurator.getVersionArgument() != null ) { // just try to get version infos to validate path is valid installationService.getExecutorVersionInfo( varValue, executorConfigurator, null ); } } } catch ( InstallationException e ) { String message = getMessage( getMessageKey() ) + e.getMessage(); logger.error( message ); addFieldError( "installation.varValue", message ); } } public String getFieldName() { return fieldName; } public void setFieldName( String fieldName ) { this.fieldName = fieldName; } }
5,472
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/validator/CronExpressionValidator.java
package org.apache.maven.continuum.web.validator; /* * 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.opensymphony.xwork2.validator.ValidationException; import com.opensymphony.xwork2.validator.ValidatorContext; import com.opensymphony.xwork2.validator.validators.ValidatorSupport; /** * Validator class for the cron expression in the continuum schedules. */ public class CronExpressionValidator extends ValidatorSupport { public void validate( Object object ) throws ValidationException { String second = (String) getFieldValue( "second", object ); String minute = (String) getFieldValue( "minute", object ); String hour = (String) getFieldValue( "hour", object ); String dayOfMonth = (String) getFieldValue( "dayOfMonth", object ); String month = (String) getFieldValue( "month", object ); String dayOfWeek = (String) getFieldValue( "dayOfWeek", object ); String year = (String) getFieldValue( "year", object ); String cronExpression = ( second + " " + minute + " " + hour + " " + dayOfMonth + " " + month + " " + dayOfWeek + " " + year ).trim(); org.codehaus.plexus.scheduler.CronExpressionValidator validator = new org.codehaus.plexus.scheduler.CronExpressionValidator(); ValidatorContext ctxt = getValidatorContext(); if ( !validator.validate( cronExpression ) ) { // FIXME i18n ctxt.addActionError( "Invalid cron expression value(s)" ); } } }
5,473
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/appareance/AppareanceConfiguration.java
package org.apache.maven.continuum.web.appareance; /* * 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.registry.RegistryException; import java.io.IOException; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 10 nov. 07 */ public interface AppareanceConfiguration { /** * @param footerHtmlContent * @throws RegistryException */ public void saveFooter( String footerHtmlContent ) throws IOException; /** * If no user configuration a default one will be user * with Apache copyright content * * @return htmlFooter */ public String getFooter(); }
5,474
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/appareance/DefaultAppareanceConfiguration.java
package org.apache.maven.continuum.web.appareance; /* * 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.web.appearance.ContinuumAppearance; import org.apache.continuum.web.appearance.io.xpp3.ContinuumAppearanceModelsXpp3Reader; import org.apache.continuum.web.appearance.io.xpp3.ContinuumAppearanceModelsXpp3Writer; 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 org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 10 nov. 07 */ @Component( role = org.apache.maven.continuum.web.appareance.AppareanceConfiguration.class, hint = "default" ) public class DefaultAppareanceConfiguration implements AppareanceConfiguration, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultAppareanceConfiguration.class ); private String footer; public static final String APPEARANCE_FILE_NAME = "continuum-appearance.xml"; private ContinuumAppearance continuumAppearance = new ContinuumAppearance(); // ------------------------------------------------ // Plexus Lifecycle // ------------------------------------------------ public void initialize() throws InitializationException { File appearanceConfFile = getAppearanceConfigurationFile(); if ( appearanceConfFile.exists() ) { try { ContinuumAppearanceModelsXpp3Reader appearanceReader = new ContinuumAppearanceModelsXpp3Reader(); this.continuumAppearance = appearanceReader.read( ReaderFactory.newXmlReader( appearanceConfFile ) ); if ( continuumAppearance != null ) { this.footer = continuumAppearance.getFooter(); } } catch ( IOException e ) { log.warn( "skip IOException reading appearance file " + APPEARANCE_FILE_NAME + ", msg " + e.getMessage() ); } catch ( XmlPullParserException e ) { log.warn( "skip XmlPullParserException reading appearance file " + APPEARANCE_FILE_NAME + ", msg " + e.getMessage() ); } } if ( StringUtils.isEmpty( this.footer ) ) { // initiate with default footer (save in registry ?) this.footer = getDefaultFooter(); } } /** * @see org.apache.maven.continuum.web.appareance.AppareanceConfiguration#getFooter() */ public String getFooter() { return this.footer; } /** * @see org.apache.maven.continuum.web.appareance.AppareanceConfiguration#saveFooter(java.lang.String) */ public void saveFooter( String footerHtmlContent ) throws IOException { String safeFooterHtmlContent = Jsoup.clean( footerHtmlContent, Whitelist.basic() ); continuumAppearance.setFooter( safeFooterHtmlContent ); ContinuumAppearanceModelsXpp3Writer writer = new ContinuumAppearanceModelsXpp3Writer(); File confFile = getAppearanceConfigurationFile(); if ( !confFile.exists() ) { confFile.getParentFile().mkdirs(); } FileWriter fileWriter = new FileWriter( confFile ); writer.write( fileWriter, continuumAppearance ); fileWriter.close(); this.footer = safeFooterHtmlContent; } private String getDefaultFooter() { int inceptionYear = 2005; int currentYear = Calendar.getInstance().get( Calendar.YEAR ); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "<div class=\"xright\">" ); stringBuilder.append( "Copyright &copy; " ); stringBuilder.append( String.valueOf( inceptionYear ) ).append( "-" ).append( String.valueOf( currentYear ) ); stringBuilder.append( "&nbsp;The Apache Software Foundation" ); stringBuilder.append( "</div> <div class=\"clear\"><hr/></div>" ); return stringBuilder.toString(); } private File getAppearanceConfigurationFile() { return new File( System.getProperty( "appserver.base" ) + File.separator + "conf" + File.separator + APPEARANCE_FILE_NAME ); } }
5,475
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/util/WorkingCopyContentGenerator.java
package org.apache.maven.continuum.web.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.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; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class WorkingCopyContentGenerator { private File basedir; private String urlParamSeparator; private static final DecimalFormat decFormatter = new DecimalFormat( "###.##" ); 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(); } }
5,476
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/util/UrlHelperFactory.java
package org.apache.maven.continuum.web.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.struts2.views.util.DefaultUrlHelper; import org.apache.struts2.views.util.UrlHelper; public class UrlHelperFactory { private UrlHelperFactory() {} public static UrlHelper getInstance() { return new DefaultUrlHelper(); } }
5,477
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/util/StateGenerator.java
package org.apache.maven.continuum.web.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.project.ContinuumProjectState; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class StateGenerator { public static final String NEW = "NEW"; public static final String SUCCESS = "Success"; public static final String FAILED = "Failed"; public static final String ERROR = "Error"; public static final String CANCELLED = "Canceled"; public static final String BUILDING = "Building"; public static final String UPDATING = "Updating"; public static final String UPDATED = "Updated"; public static final String CHECKING_OUT = "Checking Out"; public static final String CHECKED_OUT = "Checked Out"; public static final int UNKNOWN_STATE = Integer.MIN_VALUE; public static final String UNKNOWN = "Unknown"; public static final Map<Integer, String[]> stateIconArgs = new HashMap<Integer, String[]>(); static { stateIconArgs.put( ContinuumProjectState.NEW, new String[] { "/images/icon_new_sml.png", NEW } ); stateIconArgs.put( ContinuumProjectState.OK, new String[] { "/images/icon_success_sml.gif", SUCCESS } ); stateIconArgs.put( ContinuumProjectState.UPDATED, new String[] { "/images/icon_success_sml.gif", UPDATED } ); stateIconArgs.put( ContinuumProjectState.FAILED, new String[] { "/images/icon_warning_sml.gif", FAILED } ); stateIconArgs.put( ContinuumProjectState.ERROR, new String[] { "/images/icon_error_sml.gif", ERROR } ); stateIconArgs.put( ContinuumProjectState.BUILDING, new String[] { "/images/building.gif", BUILDING } ); stateIconArgs.put( ContinuumProjectState.UPDATING, new String[] { "/images/checkingout.gif", UPDATING } ); stateIconArgs.put( ContinuumProjectState.CHECKING_OUT, new String[] { "/images/checkingout.gif", CHECKING_OUT } ); stateIconArgs.put( ContinuumProjectState.CHECKEDOUT, new String[] { "/images/icon_new_sml.png", CHECKED_OUT } ); stateIconArgs.put( ContinuumProjectState.CANCELLED, new String[] { "/images/icon_unknown_sml.gif", CANCELLED } ); } public static String generate( int state, String contextPath ) { String iconFmt = "<img src=\"" + contextPath + "%s\" alt=\"%2$s\" title=\"%2$s\" border=\"0\" />"; if ( stateIconArgs.containsKey( state ) ) { return String.format( iconFmt, stateIconArgs.get( state ) ); } return String.format( iconFmt, "/images/icon_unknown_sml.gif", UNKNOWN ); } }
5,478
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/checks
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/checks/security/RoleProfileEnvironmentCheck.java
package org.apache.maven.continuum.web.checks.security; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.model.project.ProjectGroup; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.role.RoleManager; import org.codehaus.plexus.redback.role.RoleManagerException; import org.codehaus.plexus.redback.system.check.EnvironmentCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; /** * RoleProfileEnvironmentCheck: * * @author: Jesse McConnell <jmcconnell@apache.org> */ @Component( role = org.codehaus.plexus.redback.system.check.EnvironmentCheck.class, hint = "continuum-role-profile-check" ) public class RoleProfileEnvironmentCheck implements EnvironmentCheck { private static final Logger log = LoggerFactory.getLogger( RoleProfileEnvironmentCheck.class ); @Requirement( hint = "default" ) private RoleManager roleManager; @Requirement private Continuum continuum; public void validateEnvironment( List list ) { try { log.info( "Checking roles list." ); Collection<ProjectGroup> projectGroups = continuum.getAllProjectGroups(); for ( ProjectGroup group : projectGroups ) { // gets the role, making it if it doesn't exist //TODO: use continuum.executeAction( "add-assignable-roles", context ); or something like that to avoid code duplication if ( !roleManager.templatedRoleExists( "project-administrator", group.getName() ) ) { roleManager.createTemplatedRole( "project-administrator", group.getName() ); } if ( !roleManager.templatedRoleExists( "project-developer", group.getName() ) ) { roleManager.createTemplatedRole( "project-developer", group.getName() ); } if ( !roleManager.templatedRoleExists( "project-user", group.getName() ) ) { roleManager.createTemplatedRole( "project-user", group.getName() ); } } } catch ( RoleManagerException rpe ) { rpe.printStackTrace(); list.add( "error checking existence of roles for groups" ); } } }
5,479
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/bean/BuildProjectQueue.java
package org.apache.maven.continuum.web.bean; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.taskqueue.BuildProjectTask; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class BuildProjectQueue extends Queue { private BuildProjectTask task; public BuildProjectTask getTask() { return task; } public void setTask( BuildProjectTask task ) { this.task = task; } }
5,480
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/bean/CheckoutQueue.java
package org.apache.maven.continuum.web.bean; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.taskqueue.CheckOutTask; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class CheckoutQueue extends Queue { private CheckOutTask task; public CheckOutTask getTask() { return task; } public void setTask( CheckOutTask task ) { this.task = task; } }
5,481
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/bean/Queue.java
package org.apache.maven.continuum.web.bean; /* * 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 Queue { private String name; public String getName() { return name; } public void setName( String name ) { this.name = name; } }
5,482
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/bean/ProjectGroupUserBean.java
package org.apache.maven.continuum.web.bean; /* * 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.ProjectGroup; import org.codehaus.plexus.redback.rbac.Role; import org.codehaus.plexus.redback.users.User; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class ProjectGroupUserBean { public static final String ROLE_ADMINISTRATOR = "Project Administrator"; public static final String ROLE_DEVELOPER = "Project Developer"; public static final String ROLE_USER = "Project User"; private User user; private ProjectGroup projectGroup; private Collection roles; /* * these booleans should be set on the addition of roles to this bean, see setRoles and addRole */ boolean isAdministrator = false; boolean isDeveloper = false; boolean isUser = false; public boolean isAdministrator() { return isAdministrator; } public boolean isDeveloper() { return isDeveloper; } public boolean isUser() { return isUser; } public ProjectGroup getProjectGroup() { return projectGroup; } public void setProjectGroup( ProjectGroup projectGroup ) { this.projectGroup = projectGroup; } public void addRole( Role role ) { if ( roles == null ) { roles = new ArrayList(); } roles.add( role ); if ( role.getName().indexOf( ROLE_ADMINISTRATOR ) != -1 ) { isAdministrator = true; } if ( role.getName().indexOf( ROLE_DEVELOPER ) != -1 ) { isDeveloper = true; } if ( role.getName().indexOf( ROLE_USER ) != -1 ) { isUser = true; } } public Collection getRoles() { return roles; } public void setRoles( Collection roles ) { this.roles = roles; for ( Iterator i = roles.iterator(); i.hasNext(); ) { Role role = (Role) i.next(); if ( role.getName().indexOf( ROLE_ADMINISTRATOR ) != -1 ) { isAdministrator = true; } if ( role.getName().indexOf( ROLE_DEVELOPER ) != -1 ) { isDeveloper = true; } if ( role.getName().indexOf( ROLE_USER ) != -1 ) { isUser = true; } } } public User getUser() { return user; } public void setUser( User user ) { this.user = user; } public String getUsername() { return user.getUsername(); } public String getUserFullName() { return user.getFullName(); } public String getUserEmail() { return user.getEmail(); } public String toString() { return user.getUsername() + ": " + roles + ": " + ( isAdministrator() ? "A" : "-" ) + ( isDeveloper() ? "D" : "-" ) + ( isUser() ? "U" : "-" ); } }
5,483
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ContinuumActionSupport.java
package org.apache.maven.continuum.web.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 com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.Preparable; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.exception.AuthenticationRequiredException; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.authorization.AuthorizationException; import org.codehaus.plexus.redback.system.SecuritySession; import org.codehaus.plexus.redback.system.SecuritySystem; import org.codehaus.plexus.redback.system.SecuritySystemConstants; import org.codehaus.plexus.redback.users.User; import org.codehaus.plexus.redback.users.UserNotFoundException; import org.codehaus.plexus.util.StringUtils; import java.text.SimpleDateFormat; import java.util.ResourceBundle; /** * ContinuumActionSupport * * @author Jesse McConnell <jesse@codehaus.org> */ public class ContinuumActionSupport extends PlexusActionSupport implements Preparable { private SecuritySession securitySession; @Requirement private SecuritySystem securitySystem; protected static final String REQUIRES_AUTHENTICATION = "requires-authentication"; protected static final String REQUIRES_AUTHORIZATION = "requires-authorization"; protected static final String RELEASE_ERROR = "releaseError"; protected static final String ERROR_MSG_AUTHORIZATION_REQUIRED = "You are not authorized to access this page. " + "Please contact your administrator to be granted the appropriate permissions."; protected static final String ERROR_MSG_PROCESSING_AUTHORIZATION = "An error occurred while performing authorization."; @Requirement private Continuum continuum; protected final SimpleDateFormat dateFormatter = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aaa z" ); public void prepare() throws Exception { if ( securitySession == null ) { securitySession = (SecuritySession) getContext().getSession().get( SecuritySystemConstants.SECURITY_SESSION_KEY ); } } /** * Here for unit testing support, it allows configuring a mock security session. * * @param securitySession */ protected void setSecuritySession( SecuritySession securitySession ) { this.securitySession = securitySession; } public Continuum getContinuum() { return continuum; } public void setContinuum( Continuum continuum ) { this.continuum = continuum; } public String doDefault() throws Exception { return REQUIRES_AUTHORIZATION; } public String input() throws Exception { return REQUIRES_AUTHORIZATION; } public String execute() throws Exception { return REQUIRES_AUTHORIZATION; } /** * Check if the current user is authorized to do the action * * @param role the role * @throws AuthorizationRequiredException if the user isn't authorized */ protected void checkAuthorization( String role ) throws AuthorizationRequiredException { checkAuthorization( role, null, false ); } /** * Check if the current user is authorized to do the action * * @param role the role * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized */ protected void checkAuthorization( String role, String resource ) throws AuthorizationRequiredException { checkAuthorization( role, resource, true ); } /** * Check if the current user is authorized to do the action * * @param role the role * @param resource the operation resource * @param requiredResource true if resource can't be null * @throws AuthorizationRequiredException if the user isn't authorized */ protected void checkAuthorization( String role, String resource, boolean requiredResource ) throws AuthorizationRequiredException { try { if ( resource != null && StringUtils.isNotEmpty( resource.trim() ) ) { if ( !getSecuritySystem().isAuthorized( getSecuritySession(), role, resource ) ) { throw new AuthorizationRequiredException( ERROR_MSG_AUTHORIZATION_REQUIRED ); } } else { if ( requiredResource || !getSecuritySystem().isAuthorized( getSecuritySession(), role ) ) { throw new AuthorizationRequiredException( ERROR_MSG_AUTHORIZATION_REQUIRED ); } } } catch ( AuthorizationException ae ) { throw new AuthorizationRequiredException( ERROR_MSG_PROCESSING_AUTHORIZATION ); } } /** * Check if the current user is authorized to view the specified project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkViewProjectGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_VIEW_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to add a project group * * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectGroupAuthorization() throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_OPERATION ); } /** * Check if the current user is authorized to delete the specified project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to build the specified project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkBuildProjectGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_BUILD_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to modify the specified project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to add a project to a specific project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectToGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_TO_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to delete a project from a specified group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectFromGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_PROJECT_FROM_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to modify a project in the specified group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectInGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_PROJECT_IN_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to build a project in the specified group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkBuildProjectInGroupAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_BUILD_PROJECT_IN_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to add a build definition for the specified * project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkAddGroupBuildDefinitionAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_BUILD_DEFINTION_OPERATION, resource ); } /** * Check if the current user is authorized to delete a build definition in the specified * project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveGroupBuildDefinitionAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_GROUP_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to modify a build definition in the specified * project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkModifyGroupBuildDefinitionAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_GROUP_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to add a group build definition to a specific * project * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectBuildDefinitionAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_BUILD_DEFINTION_OPERATION, resource ); } /** * Check if the current user is authorized to modify a build definition of a specific project * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectBuildDefinitionAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_PROJECT_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to delete a build definition of a specific * project * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectBuildDefinitionAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_PROJECT_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to add a notifier to the specified * project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectGroupNotifierAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to delete a notifier in the specified * project group * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectGroupNotifierAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_GROUP_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to modify a notifier in the specified * project group * * @param resource the operartion resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectGroupNotifierAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_GROUP_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to add a notifier to a specific project * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectNotifierAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to delete a notifier in a specific project * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectNotifierAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_PROJECT_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to modify a notifier in a specific project * * @param resource the operation resource * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectNotifierAuthorization( String resource ) throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_PROJECT_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to manage the application's configuration * * @throws AuthenticationRequiredException if the user isn't authorized if the user isn't authenticated * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkManageConfigurationAuthorization() throws AuthenticationRequiredException, AuthorizationRequiredException { if ( !isAuthenticated() ) { throw new AuthenticationRequiredException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_CONFIGURATION ); } /** * Check if the current user is authorized to manage the project build schedules * * @throws AuthenticationRequiredException if the user isn't authorized if the user isn't authenticated * @throws AuthorizationRequiredException if the user isn't authorized if the user isn't authorized */ protected void checkManageSchedulesAuthorization() throws AuthenticationRequiredException, AuthorizationRequiredException { if ( !isAuthenticated() ) { throw new AuthenticationRequiredException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_SCHEDULES ); } /** * Check if the current user is authorized to manage queues * * @throws AuthenticationRequiredException if the user isn't authenticated * @throws AuthorizationRequiredException if the user isn't authorized */ protected void checkManageQueuesAuthorization() throws AuthenticationRequiredException, AuthorizationRequiredException { if ( !isAuthenticated() ) { throw new AuthenticationRequiredException( "Authentication required" ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_QUEUES ); } protected void checkManageLocalRepositoriesAuthorization() throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_REPOSITORIES ); } protected void checkViewReportsAuthorization() throws AuthorizationRequiredException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_VIEW_REPORT ); } /** * Get the security session * * @return current SecuritySession */ private SecuritySession getSecuritySession() { return securitySession; } /** * Get the action context * * @return action context */ private ActionContext getContext() { return ActionContext.getContext(); } /** * Get the security system * * @return the security system */ protected SecuritySystem getSecuritySystem() { return securitySystem; } protected boolean requiresAuthentication() { return true; } /** * Check if the current user is already authenticated * * @return true if the user is authenticated */ public boolean isAuthenticated() { if ( requiresAuthentication() ) { if ( getSecuritySession() == null || !getSecuritySession().isAuthenticated() ) { return false; } } return true; } protected ResourceBundle getResourceBundle() { return getTexts( "localization/Continuum" ); } protected String getPrincipal() { String principal = "guest"; if ( getSecuritySession() != null ) { if ( getSecuritySession().getUser() != null ) { principal = (String) getSecuritySession().getUser().getPrincipal(); } } else { principal = "unknown-user"; } return principal; } protected User getUser( String principal ) throws UserNotFoundException { return getSecuritySystem().getUserManager().findUser( principal ); } /** * Convenience method to determine whether a build is a maven build. We could call the static method directly, * but for struts2 validator access, we would need to enable static method invocation. * * @param buildType * @return true if the build type is will result in a maven 1 or 2+ build. */ public boolean isMavenBuildType( String buildType ) { return ContinuumBuildExecutorConstants.isMaven( buildType ); } }
5,484
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AddProjectGroupAction.java
package org.apache.maven.continuum.web.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.commons.lang.StringEscapeUtils; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.repository.RepositoryServiceException; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * @author Henry Isidro <hisidro@exist.com> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "addProjectGroup", instantiationStrategy = "per-lookup" ) public class AddProjectGroupAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( AddProjectGroupAction.class ); private String name; private String groupId; private String description; private int repositoryId; private List<LocalRepository> repositories; public void prepare() throws Exception { super.prepare(); repositories = getContinuum().getRepositoryService().getAllLocalRepositories(); } public String execute() { try { checkAddProjectGroupAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } for ( ProjectGroup projectGroup : getContinuum().getAllProjectGroups() ) { if ( name.equals( projectGroup.getName() ) ) { addActionError( getText( "projectGroup.error.name.already.exists" ) ); break; } } try { if ( getContinuum().getProjectGroupByGroupId( groupId ) != null ) { addActionError( getText( "projectGroup.error.groupId.already.exists" ) ); } } catch ( ContinuumException e ) { //since we want to add a new project group, we should be getting //this exception } if ( hasActionErrors() ) { return INPUT; } ProjectGroup projectGroup = new ProjectGroup(); projectGroup.setName( name.trim() ); projectGroup.setGroupId( groupId.trim() ); projectGroup.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( description ) ) ); try { if ( repositoryId > 0 ) { LocalRepository repository = getContinuum().getRepositoryService().getLocalRepository( repositoryId ); projectGroup.setLocalRepository( repository ); } } catch ( RepositoryServiceException e ) { logger.error( "Error adding project group" + e.getLocalizedMessage() ); return ERROR; } try { getContinuum().addProjectGroup( projectGroup ); } catch ( ContinuumException e ) { logger.error( "Error adding project group: " + e.getLocalizedMessage() ); return ERROR; } AuditLog event = new AuditLog( "Project Group id=" + projectGroup.getId(), AuditLogConstants.ADD_PROJECT_GROUP ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } public String input() { try { checkAddProjectGroupAuthorization(); return INPUT; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } public String getGroupId() { return groupId; } public void setGroupId( String groupId ) { this.groupId = groupId; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public int getRepositoryId() { return repositoryId; } public void setRepositoryId( int repositoryId ) { this.repositoryId = repositoryId; } public List<LocalRepository> getRepositories() { return repositories; } public void setRepositories( List<LocalRepository> repositories ) { this.repositories = repositories; } }
5,485
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AddMavenTwoProjectAction.java
package org.apache.maven.continuum.web.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.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Add a Maven 2 project to Continuum. * * @author Nick Gonzalez * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "addMavenTwoProject", instantiationStrategy = "per-lookup" ) public class AddMavenTwoProjectAction extends AddMavenProjectAction { @Override public void prepare() throws Exception { super.prepare(); setImportType( ImportType.SEPARATE_SCM ); } public enum ImportType { SEPARATE_SCM( "add.m2.project.importType.projectPerModuleSeparateScm", true, false ), SINGLE_SCM( "add.m2.project.importType.projectPerModuleSingleScm", true, true ), SINGLE_MULTI_MODULE( "add.m2.project.importType.singleMultiModule", false, false ); private String textKey; private boolean recursiveImport; private boolean singleDirCheckout; ImportType( String textKey, boolean recursiveImport, boolean singleCheckout ) { this.textKey = textKey; this.recursiveImport = recursiveImport; this.singleDirCheckout = singleCheckout; } public String getTextKey() { return textKey; } public boolean isSingleCheckout() { return singleDirCheckout; } public boolean isRecursiveImport() { return recursiveImport; } } /** * Generates locale-sensitive import options. */ public Map<ImportType, String> getImportOptions() { Map<ImportType, String> options = new LinkedHashMap<ImportType, String>(); for ( ImportType type : ImportType.values() ) { options.put( type, getText( type.getTextKey() ) ); } return options; } // TODO: remove this part once uploading of an m2 project with modules is supported ( CONTINUUM-1098 ) public static final String ERROR_UPLOADING_M2_PROJECT_WITH_MODULES = "add.m2.project.upload.modules.error"; public static final String ERROR_READING_POM_EXCEPTION_MESSAGE = "Error reading POM"; public static final String FILE_SCHEME = "file:/"; private ImportType importType; protected ContinuumProjectBuildingResult doExecute( String pomUrl, int selectedProjectGroup, boolean checkProtocol, boolean scmUseCache ) throws ContinuumException { ContinuumProjectBuildingResult result = null; ImportType importType = getImportType(); boolean recursiveImport = importType.isRecursiveImport(); boolean checkoutInSingleDirectory = importType.isSingleCheckout(); // TODO: remove this part once uploading of an m2 project with modules is supported ( CONTINUUM-1098 ) boolean preventModulesInFileUpload = !checkProtocol && recursiveImport; if ( preventModulesInFileUpload ) { List modules = fileToModel( urlToFile( pomUrl ) ).getModules(); if ( modules != null && modules.size() != 0 ) { result = new ContinuumProjectBuildingResult(); result.addError( ERROR_UPLOADING_M2_PROJECT_WITH_MODULES ); } } if ( result == null ) { result = getContinuum().addMavenTwoProject( pomUrl, selectedProjectGroup, checkProtocol, scmUseCache, recursiveImport, this.getBuildDefinitionTemplateId(), checkoutInSingleDirectory ); } AuditLog event = new AuditLog( hidePasswordInUrl( pomUrl ), AuditLogConstants.ADD_M2_PROJECT ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); if ( result == null || result.hasErrors() ) { event.setAction( AuditLogConstants.ADD_M2_PROJECT_FAILED ); } event.log(); return result; } private Model fileToModel( File pomFile ) throws ContinuumException { MavenXpp3Reader m2pomReader = new MavenXpp3Reader(); try { return m2pomReader.read( ReaderFactory.newXmlReader( pomFile ) ); } catch ( FileNotFoundException e ) { throw new ContinuumException( ERROR_READING_POM_EXCEPTION_MESSAGE, e ); } catch ( IOException e ) { throw new ContinuumException( ERROR_READING_POM_EXCEPTION_MESSAGE, e ); } catch ( XmlPullParserException e ) { throw new ContinuumException( ERROR_READING_POM_EXCEPTION_MESSAGE, e ); } } private File urlToFile( String url ) { if ( !url.startsWith( FILE_SCHEME + "/" ) && url.startsWith( FILE_SCHEME ) ) { //Little hack for linux (CONTINUUM-1169) url = StringUtils.replace( url, FILE_SCHEME, FILE_SCHEME + "/" ); } if ( url.startsWith( FILE_SCHEME ) ) { url = url.substring( FILE_SCHEME.length() ); } return new File( url ); } /** * @deprecated Use {@link #getPomFile()} instead */ public File getM2PomFile() { return getPomFile(); } /** * @deprecated Use {@link #setPomFile(File)} instead */ public void setM2PomFile( File pomFile ) { setPomFile( pomFile ); } /** * @deprecated Use {@link #getPomUrl()} instead */ public String getM2PomUrl() { return getPomUrl(); } /** * @deprecated Use {@link #setPomUrl(String)} instead */ public void setM2PomUrl( String pomUrl ) { setPomUrl( pomUrl ); } public ImportType getImportType() { return importType; } public void setImportType( ImportType importType ) { this.importType = importType; } }
5,486
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AbstractBuildAction.java
package org.apache.maven.continuum.web.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.buildmanager.BuildManagerException; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.project.ContinuumProjectState; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 5 oct. 07 */ public abstract class AbstractBuildAction extends ContinuumConfirmAction { private int projectId; private boolean canDelete = true; protected boolean canRemoveBuildResult( BuildResult buildResult ) throws BuildManagerException { BuildsManager buildsManager = getContinuum().getBuildsManager(); Map<String, BuildProjectTask> currentBuilds = buildsManager.getCurrentBuilds(); Set<String> keySet = currentBuilds.keySet(); for ( String key : keySet ) { BuildProjectTask buildProjectTask = currentBuilds.get( key ); if ( buildProjectTask != null && buildResult != null ) { return !( buildResult.getState() == ContinuumProjectState.BUILDING && ( buildProjectTask.getBuildDefinitionId() == buildResult.getBuildDefinition().getId() && buildProjectTask.getProjectId() == this.getProjectId() ) ); } } return true; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public boolean isCanDelete() { return canDelete; } public void setCanDelete( boolean canDelete ) { this.canDelete = canDelete; } }
5,487
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AbstractBuildDefinitionAction.java
package org.apache.maven.continuum.web.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.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.web.model.BuildDefinitionSummary; import java.util.LinkedList; import java.util.List; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 16 sept. 07 */ public abstract class AbstractBuildDefinitionAction extends ContinuumConfirmAction { protected BuildDefinitionSummary generateBuildDefinitionSummary( BuildDefinition buildDefinition ) { BuildDefinitionSummary bds = new BuildDefinitionSummary(); bds.setGoals( buildDefinition.getGoals() ); bds.setId( buildDefinition.getId() ); bds.setArguments( buildDefinition.getArguments() ); bds.setBuildFile( buildDefinition.getBuildFile() ); bds.setScheduleId( buildDefinition.getSchedule().getId() ); bds.setScheduleName( buildDefinition.getSchedule().getName() ); bds.setIsDefault( buildDefinition.isDefaultForProject() ); bds.setIsBuildFresh( buildDefinition.isBuildFresh() ); if ( buildDefinition.getProfile() != null ) { bds.setProfileName( buildDefinition.getProfile().getName() ); bds.setProfileId( buildDefinition.getProfile().getId() ); } bds.setDescription( buildDefinition.getDescription() ); bds.setType( buildDefinition.getType() ); bds.setAlwaysBuild( buildDefinition.isAlwaysBuild() ); return bds; } protected List<BuildDefinitionSummary> generateBuildDefinitionSummaries( List<BuildDefinition> buildDefinitions ) { List<BuildDefinitionSummary> buildDefinitionSummaries = new LinkedList<BuildDefinitionSummary>(); for ( BuildDefinition buildDefinition : buildDefinitions ) { buildDefinitionSummaries.add( generateBuildDefinitionSummary( buildDefinition ) ); } return buildDefinitionSummaries; } }
5,488
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectsListAction.java
package org.apache.maven.continuum.web.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.NoBuildAgentException; import org.apache.continuum.buildagent.NoBuildAgentInGroupException; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.build.BuildException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "projects", instantiationStrategy = "per-lookup" ) public class ProjectsListAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( ProjectsListAction.class ); private List<String> selectedProjects; private List<String> selectedProjectsNames; private String projectGroupName = ""; private int projectGroupId; private String methodToCall; private int buildDefinitionId; public String execute() throws Exception { if ( StringUtils.isEmpty( methodToCall ) ) { return SUCCESS; } if ( "build".equals( methodToCall ) ) { return build(); } else if ( "remove".equals( methodToCall ) ) { return remove(); } else if ( "confirmRemove".equals( methodToCall ) ) { return confirmRemove(); } return SUCCESS; } private String remove() throws ContinuumException { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( selectedProjects != null && !selectedProjects.isEmpty() ) { for ( String selectedProject : selectedProjects ) { int projectId = Integer.parseInt( selectedProject ); try { AuditLog event = new AuditLog( "Project id=" + projectId, AuditLogConstants.REMOVE_PROJECT ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); getContinuum().removeProject( projectId ); } catch ( ContinuumException e ) { logger.error( "Error removing Project with id=" + projectId ); addActionError( getText( "deleteProject.error", "Unable to delete project", new Integer( projectId ).toString() ) ); } } } return SUCCESS; } public String confirmRemove() throws ContinuumException { if ( selectedProjects != null && !selectedProjects.isEmpty() ) { this.selectedProjectsNames = new ArrayList<String>(); for ( String selectedProject : selectedProjects ) { int projectId = Integer.parseInt( selectedProject ); selectedProjectsNames.add( getContinuum().getProject( projectId ).getName() ); } } return "confirmRemove"; } private String build() throws ContinuumException { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( selectedProjects != null && !selectedProjects.isEmpty() ) { ArrayList<Project> projectsList = new ArrayList<Project>(); for ( String pId : selectedProjects ) { int projectId = Integer.parseInt( pId ); Project p = getContinuum().getProjectWithAllDetails( projectId ); projectsList.add( p ); AuditLog event = new AuditLog( "Project id=" + projectId, AuditLogConstants.FORCE_BUILD ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); } List<Project> sortedProjects = getContinuum().getProjectsInBuildOrder( projectsList ); try { if ( this.getBuildDefinitionId() <= 0 ) { List<BuildDefinition> groupDefaultBDs = getContinuum().getDefaultBuildDefinitionsForProjectGroup( projectGroupId ); getContinuum().buildProjectsWithBuildDefinition( sortedProjects, groupDefaultBDs ); } else { getContinuum().buildProjectsWithBuildDefinition( sortedProjects, buildDefinitionId ); } addActionMessage( getText( "build.projects.success" ) ); } catch ( BuildException be ) { addActionError( be.getLocalizedMessage() ); } catch ( NoBuildAgentException e ) { addActionError( getText( "projectGroup.build.error.noBuildAgent" ) ); } catch ( NoBuildAgentInGroupException e ) { addActionError( getText( "projectGroup.build.error.noBuildAgentInGroup" ) ); } } return SUCCESS; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } return projectGroupName; } public List<String> getSelectedProjects() { return selectedProjects; } public void setSelectedProjects( List<String> selectedProjects ) { this.selectedProjects = selectedProjects; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public void setMethodToCall( String methodToCall ) { this.methodToCall = methodToCall; } public int getBuildDefinitionId() { return buildDefinitionId; } public void setBuildDefinitionId( int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public List<String> getSelectedProjectsNames() { return selectedProjectsNames; } public void setSelectedProjectsNames( List<String> selectedProjectsNames ) { this.selectedProjectsNames = selectedProjectsNames; } }
5,489
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ReleasePrepareAction.java
package org.apache.maven.continuum.web.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.configuration.BuildAgentConfigurationException; import org.apache.continuum.model.release.ReleaseListenerSummary; import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.continuum.release.utils.ReleaseHelper; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.continuum.web.action.AbstractReleaseAction; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.system.Profile; 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.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.scm.provider.svn.repository.SvnScmProviderRepository; import org.apache.maven.shared.release.ReleaseResult; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author Edwin Punzalan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releasePrepare", instantiationStrategy = "per-lookup" ) public class ReleasePrepareAction extends AbstractReleaseAction { private static final String SCM_SVN_PROTOCOL_PREFIX = "scm:svn"; private static final String SNAPSHOT_VERSION_SUFFIX = "-SNAPSHOT"; private int projectId; private String releaseId; private String name; private String scmUsername; private String scmPassword; private String scmTag; private String scmTagBase; private String scmCommentPrefix; private boolean scmUseEditMode = false; private List<Map<String, String>> projects = new ArrayList<Map<String, String>>(); private List<String> projectKeys; private List<String> devVersions; private List<String> relVersions; private String prepareGoals; private String arguments; private ReleaseResult result; private ContinuumReleaseManagerListener listener; private String projectGroupName = ""; private List<Profile> profiles; private int profileId; private boolean autoVersionSubmodules = false; private boolean addSchema = true; private ReleaseListenerSummary listenerSummary; @Requirement private ReleaseHelper releaseHelper; @Requirement private LocalRepositoryHelper localRepositoryHelper; public String input() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } Project project = getContinuum().getProject( projectId ); scmUsername = project.getScmUsername(); scmPassword = project.getScmPassword(); scmTag = project.getScmTag(); if ( scmTag == null ) { String version = project.getVersion(); int idx = version.indexOf( SNAPSHOT_VERSION_SUFFIX ); if ( idx >= 0 ) { // strip the snapshot version suffix scmTag = project.getArtifactId() + "-" + version.substring( 0, idx ); } else { scmTag = project.getArtifactId() + "-" + version; } } String scmUrl = project.getScmUrl(); if ( scmUrl.startsWith( SCM_SVN_PROTOCOL_PREFIX ) ) { scmTagBase = new SvnScmProviderRepository( scmUrl, scmUsername, scmPassword ).getTagBase(); // strip the Maven scm protocol prefix scmTagBase = scmTagBase.substring( SCM_SVN_PROTOCOL_PREFIX.length() + 1 ); } else { scmTagBase = ""; } ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); //CONTINUUM-1503 releaseManager.sanitizeTagName( scmUrl, scmTag ); prepareGoals = "clean integration-test"; String defaultPomName = "pom.xml"; if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager distributedReleaseManager = getContinuum().getDistributedReleaseManager(); try { getReleasePluginParameters( distributedReleaseManager.getReleasePluginParameters( projectId, defaultPomName ) ); projects = distributedReleaseManager.processProject( projectId, defaultPomName, autoVersionSubmodules ); } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releasePrepare.input.error", args ) ); return RELEASE_ERROR; } } else { try { String workingDirectory = getContinuum().getWorkingDirectory( project.getId() ).getPath(); ArtifactRepository localRepo = localRepositoryHelper.getLocalRepository( project.getProjectGroup().getLocalRepository() ); getReleasePluginParameters( localRepo, workingDirectory, defaultPomName ); releaseHelper.buildVersionParams( localRepo, workingDirectory, defaultPomName, autoVersionSubmodules, projects ); } catch ( Exception e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "releasePrepare.input.error", args ) ); return RELEASE_ERROR; } } profiles = this.getContinuum().getProfileService().getAllProfiles(); return SUCCESS; } private void getReleasePluginParameters( ArtifactRepository localRepo, String workingDirectory, String pomFilename ) throws Exception { Map<String, Object> params = releaseHelper.extractPluginParameters( localRepo, workingDirectory, pomFilename ); // TODO: use constants for this if ( params.get( "scm-tag" ) != null ) { scmTag = (String) params.get( "scm-tag" ); } if ( params.get( "scm-tagbase" ) != null ) { scmTagBase = (String) params.get( "scm-tagbase" ); } if ( params.get( "preparation-goals" ) != null ) { prepareGoals = (String) params.get( "preparation-goals" ); } if ( params.get( "arguments" ) != null ) { arguments = (String) params.get( "arguments" ); } if ( params.get( "scm-comment-prefix" ) != null ) { scmCommentPrefix = (String) params.get( "scm-comment-prefix" ); } if ( params.get( "auto-version-submodules" ) != null ) { autoVersionSubmodules = (Boolean) params.get( "auto-version-submodules" ); } if ( params.get( "add-schema" ) != null ) { addSchema = (Boolean) params.get( "add-schema" ); } } public String execute() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } Project project = getContinuum().getProject( projectId ); name = project.getName(); if ( name == null ) { name = project.getArtifactId(); } Profile profile = null; if ( profileId != -1 ) { profile = getContinuum().getProfileService().getProfile( profileId ); } String username = getPrincipal(); Map<String, String> environments = new HashMap<String, String>(); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager distributedReleaseManager = getContinuum().getDistributedReleaseManager(); environments = getEnvironments( profile, distributedReleaseManager.getDefaultBuildagent( projectId ) ); try { releaseId = distributedReleaseManager.releasePrepare( project, getReleaseProperties(), getRelVersionMap(), getDevVersionMap(), environments, username ); if ( releaseId == null ) { addActionError( "Failed to release project" ); return RELEASE_ERROR; } } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releasePrepare.release.error", args ) ); return RELEASE_ERROR; } } else { environments = getEnvironments( profile, null ); listener = new DefaultReleaseManagerListener(); listener.setUsername( username ); String workingDirectory = getContinuum().getWorkingDirectory( projectId ).getPath(); ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); String executable = getContinuum().getInstallationService().getExecutorConfigurator( InstallationService.MAVEN2_TYPE ).getExecutable(); if ( environments != null ) { String m2Home = environments.get( getContinuum().getInstallationService().getEnvVar( InstallationService.MAVEN2_TYPE ) ); if ( StringUtils.isNotEmpty( m2Home ) ) { executable = m2Home + File.separator + "bin" + File.separator + executable; } } releaseId = releaseManager.prepare( project, getReleaseProperties(), getRelVersionMap(), getDevVersionMap(), listener, workingDirectory, environments, executable ); } AuditLog event = new AuditLog( "Release id=" + releaseId, AuditLogConstants.PREPARE_RELEASE ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( username ); event.log(); return SUCCESS; } public String viewResult() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager distributedReleaseManager = getContinuum().getDistributedReleaseManager(); try { result = distributedReleaseManager.getReleaseResult( releaseId ); } catch ( BuildAgentConfigurationException e ) { addActionError( "release" ); return "viewResultError"; } } else { result = (ReleaseResult) getContinuum().getReleaseManager().getReleaseResults().get( releaseId ); } return "viewResult"; } public String checkProgress() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } String status; listenerSummary = new ReleaseListenerSummary(); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager distributedReleaseManager = getContinuum().getDistributedReleaseManager(); Map listenerMap; try { listenerMap = distributedReleaseManager.getListener( releaseId ); } catch ( BuildAgentConfigurationException e ) { addActionError( "Failed to retrieve listener for release: " + releaseId ); return ""; } if ( listenerMap != null && !listenerMap.isEmpty() ) { int state = DistributedReleaseUtil.getReleaseState( listenerMap ); if ( state == ContinuumReleaseManagerListener.FINISHED ) { distributedReleaseManager.removeListener( releaseId ); result = distributedReleaseManager.getReleaseResult( releaseId ); status = "finished"; } else { status = "inProgress"; } listenerSummary.setPhases( DistributedReleaseUtil.getReleasePhases( listenerMap ) ); listenerSummary.setCompletedPhases( DistributedReleaseUtil.getCompletedReleasePhases( listenerMap ) ); listenerSummary.setInProgress( DistributedReleaseUtil.getReleaseInProgress( listenerMap ) ); listenerSummary.setError( DistributedReleaseUtil.getReleaseError( listenerMap ) ); } else { throw new Exception( "There is no release on-going or finished with id: " + releaseId ); } } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); listenerSummary = releaseManager.getListener( releaseId ); if ( listenerSummary != null ) { if ( listenerSummary.getState() == ContinuumReleaseManagerListener.FINISHED ) { releaseManager.getListeners().remove( releaseId ); result = (ReleaseResult) releaseManager.getReleaseResults().get( releaseId ); status = "finished"; } else { status = "inProgress"; } } else { throw new Exception( "There is no release on-going or finished with id: " + releaseId ); } } return status; } private Map<String, String> getDevVersionMap() { return getVersionMap( projectKeys, devVersions ); } private Map<String, String> getRelVersionMap() { return getVersionMap( projectKeys, relVersions ); } private Map<String, String> getVersionMap( List<String> keys, List<String> versions ) { Map<String, String> versionMap = new HashMap<String, String>(); for ( int idx = 0; idx < keys.size(); idx++ ) { String key = keys.get( idx ); String version; if ( !autoVersionSubmodules ) { version = versions.get( idx ); } else { version = versions.get( 0 ); } versionMap.put( key, version ); } return versionMap; } private Properties getReleaseProperties() { Properties p = new Properties(); if ( StringUtils.isNotEmpty( scmUsername ) ) { p.setProperty( "scm-username", scmUsername ); } if ( StringUtils.isNotEmpty( scmPassword ) ) { p.setProperty( "scm-password", scmPassword ); } if ( StringUtils.isNotEmpty( scmTagBase ) ) { p.setProperty( "scm-tagbase", scmTagBase ); } if ( StringUtils.isNotEmpty( scmCommentPrefix ) ) { // CONTINUUM-2619 p.setProperty( "scm-comment-prefix", scmCommentPrefix.trim() + " " ); } p.setProperty( "scm-tag", scmTag ); p.setProperty( "preparation-goals", prepareGoals ); p.setProperty( "arguments", arguments ); p.setProperty( "use-edit-mode", Boolean.toString( scmUseEditMode ) ); p.setProperty( "add-schema", Boolean.toString( addSchema ) ); p.setProperty( "auto-version-submodules", Boolean.toString( autoVersionSubmodules ) ); return p; } private void getReleasePluginParameters( Map context ) { if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getScmTag( context, scmTag ) ) ) { scmTag = DistributedReleaseUtil.getScmTag( context, scmTag ); } if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getScmTagBase( context, scmTagBase ) ) ) { scmTagBase = DistributedReleaseUtil.getScmTagBase( context, scmTagBase ); } if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getPrepareGoals( context, prepareGoals ) ) ) { prepareGoals = DistributedReleaseUtil.getPrepareGoals( context, prepareGoals ); } if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getArguments( context, "" ) ) ) { arguments = DistributedReleaseUtil.getArguments( context, "" ); } if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getScmCommentPrefix( context, "" ) ) ) { scmCommentPrefix = DistributedReleaseUtil.getScmCommentPrefix( context, "" ); } autoVersionSubmodules = DistributedReleaseUtil.getAutoVersionSubmodules( context, false ); addSchema = DistributedReleaseUtil.getAddSchema( context, true ); } public List<String> getProjectKeys() { return projectKeys; } public void setProjectKeys( List<String> projectKeys ) { this.projectKeys = projectKeys; } public List<String> getDevVersions() { return devVersions; } public void setDevVersions( List<String> devVersions ) { this.devVersions = devVersions; } public List<String> getRelVersions() { return relVersions; } public void setRelVersions( List<String> relVersions ) { this.relVersions = relVersions; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } 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 String getScmTagBase() { return scmTagBase; } public void setScmTagBase( String scmTagBase ) { this.scmTagBase = scmTagBase; } public List<Map<String, String>> getProjects() { return projects; } public void setProjects( List<Map<String, String>> projects ) { this.projects = projects; } public ContinuumReleaseManagerListener getListener() { return listener; } public void setListener( DefaultReleaseManagerListener listener ) { this.listener = listener; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getReleaseId() { return releaseId; } public void setReleaseId( String releaseId ) { this.releaseId = releaseId; } public ReleaseResult getResult() { return result; } public void setResult( ReleaseResult result ) { this.result = result; } public String getPrepareGoals() { return prepareGoals; } public void setPrepareGoals( String prepareGoals ) { this.prepareGoals = prepareGoals; } public String getArguments() { return arguments; } public void setArguments( String arguments ) { this.arguments = arguments; } public void validate() { } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public List<Profile> getProfiles() { return profiles; } public void setProfiles( List<Profile> profiles ) { this.profiles = profiles; } public int getProfileId() { return profileId; } public void setProfileId( int profileId ) { this.profileId = profileId; } public boolean isScmUseEditMode() { return scmUseEditMode; } public void setScmUseEditMode( boolean scmUseEditMode ) { this.scmUseEditMode = scmUseEditMode; } public String getScmCommentPrefix() { return scmCommentPrefix; } public void setScmCommentPrefix( String scmCommentPrefix ) { this.scmCommentPrefix = scmCommentPrefix; } public boolean isAutoVersionSubmodules() { return autoVersionSubmodules; } public void setAutoVersionSubmodules( boolean autoVersionSubmodules ) { this.autoVersionSubmodules = autoVersionSubmodules; } public boolean isAddSchema() { return addSchema; } public void setAddSchema( boolean addSchema ) { this.addSchema = addSchema; } public ReleaseListenerSummary getListenerSummary() { return listenerSummary; } public void setListenerSummary( ReleaseListenerSummary listenerSummary ) { this.listenerSummary = listenerSummary; } }
5,490
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ContinuumConfirmAction.java
package org.apache.maven.continuum.web.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. */ public class ContinuumConfirmAction extends ContinuumActionSupport { public static final String CONFIRM = "confirm"; protected boolean confirmed = false; protected String confirmedDisplay; protected String confirmationTitle; protected String confirmedName; protected String confirmedValue; protected String action; protected void setConfirmationInfo( String title, String actionName, String displayString, String propertyName, String propertyValue ) { action = actionName; confirmationTitle = title; confirmedDisplay = displayString; confirmedName = propertyName; confirmedValue = "" + propertyValue; } // setters and getters public void setConfirmedName( String name ) { confirmedName = name; } public String getConfirmedName() { return confirmedName; } public void setConfirmedValue( String value ) { confirmedValue = value; } public String getConfirmedValue() { return confirmedValue; } public void setConfirmationTitle( String title ) { confirmationTitle = title; } public String getConfirmationTitle() { return confirmationTitle; } public void setConfirmedDisplay( String display ) { confirmedDisplay = display; } public String getConfirmedDisplay() { return confirmedDisplay; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public boolean isConfirmed() { return confirmed; } public void setAction( String action ) { this.action = action; } public String getAction() { return action; } }
5,491
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/SummaryAction.java
package org.apache.maven.continuum.web.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.buildmanager.BuildManagerException; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.model.GroupSummary; import org.apache.maven.continuum.web.model.ProjectSummary; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; /** * Used to render the list of projects in the project group page. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "summary", instantiationStrategy = "per-lookup" ) public class SummaryAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( SummaryAction.class ); private int projectGroupId; private String projectGroupName; private List<ProjectSummary> summary; private GroupSummary groupSummary = new GroupSummary(); @Requirement( hint = "parallel" ) private BuildsManager parallelBuildsManager; public String browse() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } Collection<Project> projectsInGroup; //TODO: Create a summary jpox request so code will be more simple and performance will be better projectsInGroup = getContinuum().getProjectsInGroup( projectGroupId ); Map<Integer, BuildResult> buildResults = getContinuum().getLatestBuildResults( projectGroupId ); Map<Integer, BuildResult> buildResultsInSuccess = getContinuum().getBuildResultsInSuccess( projectGroupId ); summary = new ArrayList<ProjectSummary>(); groupSummary.setNumErrors( 0 ); groupSummary.setNumFailures( 0 ); groupSummary.setNumSuccesses( 0 ); groupSummary.setNumProjects( 0 ); for ( Project project : projectsInGroup ) { groupSummary.setNumProjects( groupSummary.getNumProjects() + 1 ); ProjectSummary model = new ProjectSummary(); model.setId( project.getId() ); model.setName( project.getName() ); model.setVersion( project.getVersion() ); model.setProjectGroupId( project.getProjectGroup().getId() ); model.setProjectGroupName( project.getProjectGroup().getName() ); model.setProjectType( project.getExecutorId() ); try { if ( parallelBuildsManager.isInAnyBuildQueue( project.getId() ) || parallelBuildsManager.isInPrepareBuildQueue( project.getId() ) ) { model.setInBuildingQueue( true ); } else if ( parallelBuildsManager.isInAnyCheckoutQueue( project.getId() ) ) { model.setInCheckoutQueue( true ); } else { model.setInBuildingQueue( false ); model.setInCheckoutQueue( false ); } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } model.setState( project.getState() ); model.setBuildNumber( project.getBuildNumber() ); if ( buildResultsInSuccess != null ) { BuildResult buildInSuccess = buildResultsInSuccess.get( project.getId() ); if ( buildInSuccess != null ) { model.setBuildInSuccessId( buildInSuccess.getId() ); } } if ( buildResults != null ) { BuildResult latestBuild = buildResults.get( project.getId() ); if ( latestBuild != null ) { model.setLatestBuildId( latestBuild.getId() ); populateGroupSummary( latestBuild ); model.setLastBuildDateTime( latestBuild.getEndTime() ); model.setLastBuildDuration( latestBuild.getDurationTime() ); } } summary.add( model ); } Comparator<ProjectSummary> projectComparator = new Comparator<ProjectSummary>() { public int compare( ProjectSummary ps1, ProjectSummary ps2 ) { return ps1.getName().compareTo( ps2.getName() ); } }; Collections.sort( summary, projectComparator ); return SUCCESS; } private void populateGroupSummary( BuildResult latestBuild ) { switch ( latestBuild.getState() ) { case ContinuumProjectState.ERROR: groupSummary.setNumErrors( groupSummary.getNumErrors() + 1 ); break; case ContinuumProjectState.OK: groupSummary.setNumSuccesses( groupSummary.getNumSuccesses() + 1 ); break; case ContinuumProjectState.FAILED: groupSummary.setNumFailures( groupSummary.getNumFailures() + 1 ); break; default: if ( latestBuild.getState() == 5 || latestBuild.getState() > 10 ) { logger.warn( "unknown buildState value " + latestBuild.getState() + " with build " + latestBuild.getId() ); } } } public List<ProjectSummary> getProjects() { return summary; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getProjectGroupName() { return projectGroupName; } public void setProjectGroupName( String projectGroupName ) { this.projectGroupName = projectGroupName; } public GroupSummary getGroupSummary() { return groupSummary; } public void setGroupSummary( GroupSummary groupSummary ) { this.groupSummary = groupSummary; } // test public void setParallelBuildsManager( BuildsManager parallelBuildsManager ) { this.parallelBuildsManager = parallelBuildsManager; } }
5,492
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AboutAction.java
package org.apache.maven.continuum.web.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.web.util.FixedBufferAppender; import org.apache.log4j.Logger; import org.apache.log4j.spi.AppenderAttachable; import org.apache.maven.continuum.web.exception.AuthenticationRequiredException; import org.codehaus.plexus.component.annotations.Component; import java.util.Properties; /** * AboutAction: * * @author: Jesse McConnell <jmcconnell@apache.org> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "about", instantiationStrategy = "per-lookup" ) public class AboutAction extends ContinuumActionSupport { private Properties systemProperties; private String logOutput; public String execute() throws Exception { try { checkManageConfigurationAuthorization(); systemProperties = System.getProperties(); logOutput = constructOutput(); } catch ( Exception e ) { // Ignore, just hide additional system information } return SUCCESS; } private String constructOutput() { StringBuilder buf = new StringBuilder(); Object async = Logger.getRootLogger().getAppender( "async" ); if ( async != null && async instanceof AppenderAttachable ) { Object webViewable = ( (AppenderAttachable) async ).getAppender( "webViewable" ); if ( webViewable != null && webViewable instanceof FixedBufferAppender ) { FixedBufferAppender appender = (FixedBufferAppender) webViewable; for ( String line : appender.getLines() ) { buf.append( line ); } } } return buf.toString(); } public Properties getSystemProperties() { return systemProperties; } public String getLogOutput() { return logOutput; } }
5,493
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectViewAction.java
package org.apache.maven.continuum.web.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.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.view.buildresults.StateCell; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "projectView", instantiationStrategy = "per-lookup" ) public class ProjectViewAction extends ContinuumActionSupport { private static final Logger log = LoggerFactory.getLogger( ProjectViewAction.class ); private Project project; private BuildResult latestResult; private int projectId; public String execute() throws ContinuumException { ProjectGroup projectGroup = getProjectGroup(); try { checkViewProjectGroupAuthorization( projectGroup.getName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } project = getContinuum().getProjectWithAllDetails( projectId ); int latestResultId = project.getLatestBuildId(); if ( latestResultId > 0 ) { try { latestResult = getContinuum().getBuildResult( latestResultId ); } catch ( ContinuumException e ) { log.debug( "project {} lists non-existent result {} as its latest", projectId, latestResult ); } } return SUCCESS; } public void setProjectId( int projectId ) { this.projectId = projectId; } public Project getProject() { return project; } public int getProjectId() { return projectId; } /** * Returns the {@link ProjectGroup} instance obtained for * the specified project group Id, or null if it were not set. * * @return the projectGroup */ public ProjectGroup getProjectGroup() throws ContinuumException { return getContinuum().getProjectGroupByProjectId( projectId ); } public BuildResult getLatestResult() { return latestResult; } /** * Maps the time to an alternative range. * * @param time the time to translate * @return current time in milliseconds if time == 0, otherwise original time value */ public long mapZeroTime( long time ) { if ( time == 0 ) return System.currentTimeMillis(); return time; } /** * Convenience method for using time values as dates in views. * * @param time the time to convert to a date * @return a {@link Date} created with the specified time */ public Date timeToDate( long time ) { return new Date( time ); } /** * Converts the specified result to an html icon. * * @param result the build result to convert. * @return icon as html, either an img or if appropriate, a clickable link containing the img */ public String resultIcon( BuildResult result ) { return StateCell.iconifyResult( result, result.getState() ); } }
5,494
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/WorkingCopyAction.java
package org.apache.maven.continuum.web.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.builder.distributed.manager.DistributedBuildManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.util.UrlHelperFactory; import org.apache.maven.continuum.web.util.WorkingCopyContentGenerator; import org.apache.struts2.ServletActionContext; import org.apache.struts2.views.util.UrlHelper; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.MimetypesFileTypeMap; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "workingCopy", instantiationStrategy = "per-lookup" ) public class WorkingCopyAction extends ContinuumActionSupport { @Requirement private WorkingCopyContentGenerator generator; @Requirement private DistributedBuildManager distributedBuildManager; private Project project; private int projectId; private String userDirectory; private String currentFile; private String currentFileContent; private String output; private String projectName; private File downloadFile; private String mimeType = "application/octet-stream"; private static final String FILE_SEPARATOR = System.getProperty( "file.separator" ); private String projectGroupName = ""; private String downloadFileName = ""; private String downloadFileLength = ""; private InputStream downloadFileInputStream; public String execute() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( "release.properties".equals( currentFile ) ) { throw new ContinuumException( "release.properties is not accessible." ); } project = getContinuum().getProject( projectId ); projectName = project.getName(); HashMap<String, Object> params = new HashMap<String, Object>(); params.put( "projectId", projectId ); params.put( "projectName", projectName ); UrlHelper urlHelper = UrlHelperFactory.getInstance(); String baseUrl = urlHelper.buildUrl( "/workingCopy.action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); String imagesBaseUrl = urlHelper.buildUrl( "/images/", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); imagesBaseUrl = imagesBaseUrl.substring( 0, imagesBaseUrl.indexOf( "/images/" ) + "/images/".length() ); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { output = distributedBuildManager.generateWorkingCopyContent( projectId, userDirectory, baseUrl, imagesBaseUrl ); if ( currentFile != null && !currentFile.equals( "" ) ) { Map<String, Object> projectFile = distributedBuildManager.getFileContent( projectId, userDirectory, currentFile ); if ( projectFile == null ) { currentFileContent = ""; } else { downloadFileInputStream = new ByteArrayInputStream( (byte[]) projectFile.get( "downloadFile" ) ); downloadFileLength = (String) projectFile.get( "downloadFileLength" ); downloadFileName = (String) projectFile.get( "downloadFileName" ); currentFileContent = (String) projectFile.get( "fileContent" ); mimeType = (String) projectFile.get( "mimeType" ); if ( (Boolean) projectFile.get( "isStream" ) ) { return "stream"; } } } else { currentFileContent = ""; } } else { List<File> files = getContinuum().getFiles( projectId, userDirectory ); output = generator.generate( files, baseUrl, imagesBaseUrl, getContinuum().getWorkingDirectory( projectId ) ); if ( currentFile != null && !currentFile.equals( "" ) ) { String dir; //TODO: maybe create a plexus component for this so that additional mimetypes can be easily added MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); mimeTypesMap.addMimeTypes( "application/java-archive jar war ear" ); mimeTypesMap.addMimeTypes( "application/java-class class" ); mimeTypesMap.addMimeTypes( "image/png png" ); if ( FILE_SEPARATOR.equals( userDirectory ) ) { dir = userDirectory; } else { dir = FILE_SEPARATOR + userDirectory + FILE_SEPARATOR; } downloadFile = new File( getContinuum().getWorkingDirectory( projectId ) + dir + currentFile ); mimeType = mimeTypesMap.getContentType( downloadFile ); downloadFileLength = Long.toString( downloadFile.length() ); downloadFileName = downloadFile.getName(); if ( ( mimeType.indexOf( "image" ) >= 0 ) || ( mimeType.indexOf( "java-archive" ) >= 0 ) || ( mimeType.indexOf( "java-class" ) >= 0 ) || ( downloadFile.length() > 100000 ) ) { return "stream"; } currentFileContent = getContinuum().getFileContent( projectId, userDirectory, currentFile ); } else { currentFileContent = ""; } } return SUCCESS; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectName() { return projectName; } public String getUserDirectory() { return userDirectory; } public void setUserDirectory( String userDirectory ) { this.userDirectory = userDirectory; } public void setFile( String currentFile ) { this.currentFile = currentFile; } public String getFile() { return currentFile; } public String getOutput() { return output; } public String getFileContent() { return currentFileContent; } public InputStream getInputStream() throws ContinuumException { if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { return downloadFileInputStream; } else { FileInputStream fis; try { fis = new FileInputStream( downloadFile ); } catch ( FileNotFoundException fne ) { throw new ContinuumException( "Error accessing file.", fne ); } return fis; } } public String getFileLength() { return downloadFileLength; } public String getDownloadFilename() { return downloadFileName; } public String getMimeType() { return this.mimeType; } public Project getProject() { return project; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } }
5,495
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ScheduleAction.java
package org.apache.maven.continuum.web.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 com.opensymphony.xwork2.Preparable; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildQueue; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.web.exception.AuthenticationRequiredException; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author Nik Gonzalez */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "schedule", instantiationStrategy = "per-lookup" ) public class ScheduleAction extends ContinuumConfirmAction implements Preparable { private static final Logger logger = LoggerFactory.getLogger( ScheduleAction.class ); private int id; private boolean active = false; private int delay; private String description; private String name; private Collection schedules; private Schedule schedule; private boolean confirmed; private int maxJobExecutionTime; private String second = "0"; private String minute = "0"; private String hour = "*"; private String dayOfMonth = "*"; private String month = "*"; private String dayOfWeek = "?"; private String year; private List<BuildQueue> availableBuildQueues; private List<BuildQueue> selectedBuildQueues = new ArrayList<BuildQueue>(); private List<String> selectedBuildQueuesIds = new ArrayList<String>(); public void prepare() throws Exception { super.prepare(); populateBuildQueues(); } private void populateBuildQueues() throws ContinuumException { if ( schedule != null ) { selectedBuildQueues = schedule.getBuildQueues(); for ( BuildQueue bq : selectedBuildQueues ) { this.selectedBuildQueuesIds.add( Integer.toString( bq.getId() ) ); } } availableBuildQueues = getContinuum().getAllBuildQueues(); // remove selected build queues from available build queues for ( BuildQueue buildQueue : selectedBuildQueues ) { if ( availableBuildQueues.contains( buildQueue ) ) { availableBuildQueues.remove( buildQueue ); } } } public String summary() throws ContinuumException { try { checkManageSchedulesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } schedules = getContinuum().getSchedules(); return SUCCESS; } public String input() throws ContinuumException { try { checkManageSchedulesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } if ( id != 0 ) { schedule = getContinuum().getSchedule( id ); active = schedule.isActive(); String[] cronEx = schedule.getCronExpression().split( " " ); second = cronEx[0]; minute = cronEx[1]; hour = cronEx[2]; dayOfMonth = cronEx[3]; month = cronEx[4]; dayOfWeek = cronEx[5]; if ( cronEx.length > 6 ) { year = cronEx[6]; } description = schedule.getDescription(); name = schedule.getName(); delay = schedule.getDelay(); maxJobExecutionTime = schedule.getMaxJobExecutionTime(); populateBuildQueues(); } else { // all new schedules should be active active = true; } return SUCCESS; } public String save() throws ContinuumException { try { checkManageSchedulesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } if ( StringUtils.isBlank( name ) ) { logger.error( "Can't create schedule. No schedule name was supplied." ); addActionError( getText( "buildDefinition.noname.save.error.message" ) ); } if ( !getContinuum().getConfiguration().isDistributedBuildEnabled() && ( selectedBuildQueuesIds == null || selectedBuildQueuesIds.isEmpty() ) ) { addActionError( getText( "schedule.buildqueues.empty.error" ) ); } if ( hasErrors() ) { return ERROR; } try { Schedule s = getContinuum().getScheduleByName( name ); if ( s != null && id != s.getId() ) { addActionError( getText( "schedule.name.already.exists" ) ); return ERROR; } } catch ( ContinuumException e ) { logger.debug( "Unexpected error getting schedule" ); } AuditLog event = new AuditLog( getName(), AuditLogConstants.ADD_SCHEDULE ); event.setCategory( AuditLogConstants.SCHEDULE ); event.setCurrentUser( getPrincipal() ); if ( id == 0 ) { try { getContinuum().addSchedule( setFields( new Schedule() ) ); event.log(); } catch ( ContinuumException e ) { addActionError( getText( "schedule.buildqueues.add.error" ) ); return ERROR; } return SUCCESS; } else { try { getContinuum().updateSchedule( setFields( getContinuum().getSchedule( id ) ) ); event.setAction( AuditLogConstants.MODIFY_SCHEDULE ); event.log(); } catch ( ContinuumException e ) { addActionError( getText( "schedule.buildqueues.add.error" ) ); return ERROR; } return SUCCESS; } } private Schedule setFields( Schedule schedule ) throws ContinuumException { schedule.setActive( active ); schedule.setCronExpression( getCronExpression() ); schedule.setDelay( delay ); schedule.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( description ) ) ); schedule.setName( name ); schedule.setMaxJobExecutionTime( maxJobExecutionTime ); if ( !getContinuum().getConfiguration().isDistributedBuildEnabled() ) { // if distributed build don't update schedules schedule.setBuildQueues( null ); for ( String id : selectedBuildQueuesIds ) { BuildQueue buildQueue = getContinuum().getBuildQueue( Integer.parseInt( id ) ); schedule.addBuildQueue( buildQueue ); } } return schedule; } public String confirm() throws ContinuumException { try { checkManageSchedulesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } schedule = getContinuum().getSchedule( id ); return SUCCESS; } public String remove() throws ContinuumException { try { checkManageSchedulesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } if ( confirmed ) { try { getContinuum().removeSchedule( id ); } catch ( ContinuumException e ) { addActionError( getText( "schedule.remove.error" ) ); return ERROR; } } else { setConfirmationInfo( "Schedule Removal", "removeSchedule", name, "id", "" + id ); name = getContinuum().getSchedule( id ).getName(); return CONFIRM; } AuditLog event = new AuditLog( name, AuditLogConstants.REMOVE_SCHEDULE ); event.setCategory( AuditLogConstants.SCHEDULE ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } public Collection getSchedules() { return schedules; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public boolean isActive() { return active; } public void setActive( boolean active ) { this.active = active; } public int getDelay() { return delay; } public void setDelay( int delay ) { this.delay = delay; } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public Schedule getSchedule() { return schedule; } public void setSchedule( Schedule schedule ) { this.schedule = schedule; } public boolean isConfirmed() { return confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public int getMaxJobExecutionTime() { return maxJobExecutionTime; } public void setMaxJobExecutionTime( int maxJobExecutionTime ) { this.maxJobExecutionTime = maxJobExecutionTime; } public String getSecond() { return second; } public void setSecond( String second ) { this.second = second; } public String getMinute() { return minute; } public void setMinute( String minute ) { this.minute = minute; } public String getHour() { return hour; } public void setHour( String hour ) { this.hour = hour; } public String getDayOfMonth() { return dayOfMonth; } public void setDayOfMonth( String dayOfMonth ) { this.dayOfMonth = dayOfMonth; } public String getYear() { return year; } public void setYear( String year ) { this.year = year; } public String getMonth() { return month; } public void setMonth( String month ) { this.month = month; } public String getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek( String dayOfWeek ) { this.dayOfWeek = dayOfWeek; } private String getCronExpression() { return ( second + " " + minute + " " + hour + " " + dayOfMonth + " " + month + " " + dayOfWeek + " " + year ).trim(); } public List<BuildQueue> getAvailableBuildQueues() { return availableBuildQueues; } public void setAvailableBuildQueues( List<BuildQueue> availableBuildQueues ) { this.availableBuildQueues = availableBuildQueues; } public List<BuildQueue> getSelectedBuildQueues() { return selectedBuildQueues; } public void setSelectedBuildQueues( List<BuildQueue> selectedBuildQueues ) { this.selectedBuildQueues = selectedBuildQueues; } public List<String> getSelectedBuildQueuesIds() { return selectedBuildQueuesIds; } public void setSelectedBuildQueuesIds( List<String> selectedBuildQueuesIds ) { this.selectedBuildQueuesIds = selectedBuildQueuesIds; } }
5,496
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/PlexusActionSupport.java
package org.apache.maven.continuum.web.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 com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.interceptor.SessionAware; import java.util.Map; /** * LogEnabled and SessionAware ActionSupport * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public abstract class PlexusActionSupport extends ActionSupport implements SessionAware { protected Map session; public void setSession( Map map ) { //noinspection AssignmentToCollectionOrArrayFieldFromParameter this.session = map; } }
5,497
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildResultsListAction.java
package org.apache.maven.continuum.web.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.buildmanager.BuildManagerException; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildResults", instantiationStrategy = "per-lookup" ) public class BuildResultsListAction extends AbstractBuildAction { private static final Logger logger = LoggerFactory.getLogger( BuildResultsListAction.class ); private static final int MAX_PAGE_LEN = 100; private static final int MIN_PAGE_LEN = 10; private Project project; private Collection<BuildResult> buildResults; private Collection<String> selectedBuildResults; private int projectId; private int projectGroupId; private String projectName; private String projectGroupName = ""; private int page; private int length = MAX_PAGE_LEN / 4; public String execute() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } project = getContinuum().getProject( projectId ); int adjPage = Math.max( 1, page ), adjLength = Math.max( MIN_PAGE_LEN, Math.min( MAX_PAGE_LEN, length ) ); page = adjPage; length = adjLength; buildResults = getContinuum().getBuildResultsForProject( projectId, ( page - 1 ) * length, length ); return SUCCESS; } public String remove() throws ContinuumException { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( this.isConfirmed() ) { if ( selectedBuildResults != null && !selectedBuildResults.isEmpty() ) { for ( String id : selectedBuildResults ) { int buildId = Integer.parseInt( id ); try { logger.info( "Removing BuildResult with id=" + buildId ); getContinuum().removeBuildResult( buildId ); AuditLog event = new AuditLog( "Build Result id=" + buildId, AuditLogConstants.REMOVE_BUILD_RESULT ); event.setCategory( AuditLogConstants.BUILD_RESULT ); event.setCurrentUser( getPrincipal() ); event.log(); } catch ( ContinuumException e ) { logger.error( "Error removing BuildResult with id=" + buildId ); addActionError( getText( "buildResult.delete.error", "Unable to delete build result", new Integer( buildId ).toString() ) ); } } } return SUCCESS; } else { List<String> buildResultsRemovable = new ArrayList<String>(); if ( selectedBuildResults != null && !selectedBuildResults.isEmpty() ) { for ( String id : selectedBuildResults ) { int buildId = Integer.parseInt( id ); try { if ( canRemoveBuildResult( getContinuum().getBuildResult( buildId ) ) ) { buildResultsRemovable.add( Integer.toString( buildId ) ); } else { this.addActionMessage( getResourceBundle().getString( "buildResult.cannot.delete" ) ); return SUCCESS; } } catch ( BuildManagerException e ) { logger.error( e.getMessage() ); throw new ContinuumException( e.getMessage(), e ); } } } this.setSelectedBuildResults( buildResultsRemovable ); } return CONFIRM; } public int getPage() { return page; } public void setPage( int page ) { this.page = page; } public int getLength() { return length; } public void setLength( int length ) { this.length = length; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public Collection<BuildResult> getBuildResults() { return buildResults; } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public Project getProject() { return project; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProject( projectId ).getProjectGroup().getName(); } return projectGroupName; } public Collection<String> getSelectedBuildResults() { return selectedBuildResults; } public void setSelectedBuildResults( Collection<String> selectedBuildResults ) { this.selectedBuildResults = selectedBuildResults; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } }
5,498
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ReleaseInProgressAction.java
package org.apache.maven.continuum.web.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.configuration.BuildAgentConfigurationException; import org.apache.continuum.model.release.ReleaseListenerSummary; import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.release.ContinuumReleaseManagerListener; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.shared.release.ReleaseResult; import org.codehaus.plexus.component.annotations.Component; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Edwin Punzalan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releaseInProgress", instantiationStrategy = "per-lookup" ) public class ReleaseInProgressAction extends ContinuumActionSupport { private int projectId; private String releaseId; private String releaseGoal; private ContinuumReleaseManagerListener listener; private ReleaseResult result; private String projectGroupName = ""; private ReleaseListenerSummary listenerSummary; private String username = ""; public String execute() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } String status = ""; listenerSummary = new ReleaseListenerSummary(); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); Map map; try { map = releaseManager.getListener( releaseId ); } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releaseInProgress.error", args ) ); return RELEASE_ERROR; } if ( map != null && !map.isEmpty() ) { int state = DistributedReleaseUtil.getReleaseState( map ); username = DistributedReleaseUtil.getUsername( map ); if ( state == ContinuumReleaseManagerListener.LISTENING ) { status = "inProgress"; } else if ( state == ContinuumReleaseManagerListener.FINISHED ) { status = SUCCESS; } else { status = "initialized"; } if ( status.equals( SUCCESS ) ) { getContinuum().addContinuumReleaseResult( projectId, releaseId, releaseGoal ); } listenerSummary.setPhases( DistributedReleaseUtil.getReleasePhases( map ) ); listenerSummary.setCompletedPhases( DistributedReleaseUtil.getCompletedReleasePhases( map ) ); listenerSummary.setInProgress( DistributedReleaseUtil.getReleaseInProgress( map ) ); listenerSummary.setError( DistributedReleaseUtil.getReleaseError( map ) ); } else { throw new Exception( "There is no on-going or finished release operation with id " + releaseId ); } } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); listenerSummary = releaseManager.getListener( releaseId ); if ( listenerSummary != null ) { username = listenerSummary.getUsername(); if ( listenerSummary.getState() == ContinuumReleaseManagerListener.LISTENING ) { status = "inProgress"; } else if ( listenerSummary.getState() == ContinuumReleaseManagerListener.FINISHED ) { status = SUCCESS; } else { status = "initialized"; } } else { throw new Exception( "There is no on-going or finished release operation with id " + releaseId ); } if ( status.equals( SUCCESS ) ) { getContinuum().addContinuumReleaseResult( projectId, releaseId, releaseGoal ); } } return status; } public String viewResult() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } listenerSummary = new ReleaseListenerSummary(); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); try { Map map = releaseManager.getListener( releaseId ); if ( map != null && !map.isEmpty() ) { int state = DistributedReleaseUtil.getReleaseState( map ); listenerSummary.setPhases( DistributedReleaseUtil.getReleasePhases( map ) ); listenerSummary.setCompletedPhases( DistributedReleaseUtil.getCompletedReleasePhases( map ) ); listenerSummary.setInProgress( DistributedReleaseUtil.getReleaseInProgress( map ) ); listenerSummary.setError( DistributedReleaseUtil.getReleaseError( map ) ); username = DistributedReleaseUtil.getUsername( map ); if ( state == ContinuumReleaseManagerListener.FINISHED ) { result = releaseManager.getReleaseResult( releaseId ); return SUCCESS; } else { throw new Exception( "The release operation with id " + releaseId + "has not finished yet." ); } } else { throw new Exception( "There is no finished release operation with id " + releaseId ); } } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "releaseViewResult.error", args ) ); return RELEASE_ERROR; } } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); listenerSummary = releaseManager.getListener( releaseId ); if ( listenerSummary != null ) { username = listenerSummary.getUsername(); if ( listenerSummary.getState() == ContinuumReleaseManagerListener.FINISHED ) { result = (ReleaseResult) releaseManager.getReleaseResults().get( releaseId ); return SUCCESS; } else { throw new Exception( "The release operation with id " + releaseId + "has not finished yet." ); } } else { throw new Exception( "There is no finished release operation with id " + releaseId ); } } } public String getReleaseId() { return releaseId; } public void setReleaseId( String releaseId ) { this.releaseId = releaseId; } public ContinuumReleaseManagerListener getListener() { return listener; } public void setListener( ContinuumReleaseManagerListener listener ) { this.listener = listener; } public ReleaseResult getResult() { return result; } public void setResult( ReleaseResult result ) { this.result = result; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getReleaseGoal() { return releaseGoal; } public void setReleaseGoal( String releaseGoal ) { this.releaseGoal = releaseGoal; } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public ReleaseListenerSummary getListenerSummary() { return listenerSummary; } public void setListenerSummary( ReleaseListenerSummary listenerSummary ) { this.listenerSummary = listenerSummary; } public String getProjectName() throws ContinuumException { return getProjectGroupName(); } public String getUsername() { return this.username; } }
5,499