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-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/ContinuumBuildAgentDavResourceTest.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.utils.file.FileSystemManager;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavResourceFactory;
import org.apache.jackrabbit.webdav.DavResourceLocator;
import org.apache.jackrabbit.webdav.DavServletRequest;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.DavSession;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import static org.junit.Assert.*;
public class ContinuumBuildAgentDavResourceTest
extends PlexusSpringTestCase
{
private DavSession session;
private DavResourceFactory resourceFactory;
private ContinuumBuildAgentDavResourceLocator resourceLocator;
private DavResource resource;
private MimetypesFileTypeMap mimeTypes;
private FileSystemManager fsManager;
private File baseDir;
private File resourceFile;
private final String RESOURCE_FILE = "resource.jar";
@Before
public void setUp()
throws Exception
{
session = new ContinuumBuildAgentDavSession();
mimeTypes = new MimetypesFileTypeMap();
mimeTypes.addMimeTypes( "application/java-archive jar war ear" );
mimeTypes.addMimeTypes( "application/java-class class" );
mimeTypes.addMimeTypes( "image/png png" );
fsManager = lookup( FileSystemManager.class );
baseDir = getTestFile( "target/DavResourceTest" );
baseDir.mkdirs();
resourceFile = new File( baseDir, RESOURCE_FILE );
resourceFile.createNewFile();
resourceFactory = new RootContextDavResourceFactory();
resourceLocator = (ContinuumBuildAgentDavResourceLocator) new ContinuumBuildAgentDavLocatorFactory()
.createResourceLocator( "/", RESOURCE_FILE );
resource = getDavResource( resourceLocator.getHref( false ), resourceFile );
}
@After
public void tearDown()
throws Exception
{
if ( baseDir.exists() )
{
fsManager.removeDir( baseDir );
}
}
@Test
public void testAddResource()
throws Exception
{
File newResource = new File( baseDir, "newResource.jar" );
assertFalse( newResource.exists() );
try
{
resource.getCollection().addMember( resource, null );
fail( "Should have thrown an UnsupportedOperationException" );
}
catch ( UnsupportedOperationException e )
{
assertFalse( newResource.exists() );
}
}
@Test
public void testDeleteCollection()
throws Exception
{
File dir = new File( baseDir, "testdir" );
try
{
assertTrue( dir.mkdir() );
DavResource directoryResource = getDavResource( "/testdir", dir );
directoryResource.getCollection().removeMember( directoryResource );
fail( "Should have thrown an UnsupportedOperationException" );
}
catch ( UnsupportedOperationException e )
{
assertTrue( dir.exists() );
}
finally
{
fsManager.removeDir( dir );
}
}
@Test
public void testDeleteResource()
throws Exception
{
assertTrue( resourceFile.exists() );
try
{
resource.getCollection().removeMember( resource );
fail( "Should have thrown an UnsupportedOperationException" );
}
catch ( UnsupportedOperationException e )
{
assertTrue( resourceFile.exists() );
}
}
private DavResource getDavResource( String logicalPath, File file )
{
return new ContinuumBuildAgentDavResource( file.getAbsolutePath(), logicalPath, session, resourceLocator,
resourceFactory, mimeTypes );
}
private class RootContextDavResourceFactory
implements DavResourceFactory
{
public DavResource createResource( DavResourceLocator locator, DavServletRequest request,
DavServletResponse response )
throws DavException
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public DavResource createResource( DavResourceLocator locator, DavSession session )
throws DavException
{
return new ContinuumBuildAgentDavResource( baseDir.getAbsolutePath(), "/", session, resourceLocator,
resourceFactory, mimeTypes );
}
}
}
| 5,000 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/ContinuumBuildAgentDavResourceFactoryTest.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService;
import org.apache.continuum.utils.file.FileSystemManager;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavResourceLocator;
import org.apache.jackrabbit.webdav.DavServletRequest;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ContinuumBuildAgentDavResourceFactoryTest
extends PlexusSpringTestCase
{
private DavServletRequest request;
private DavServletResponse response;
private BuildAgentConfigurationService buildAgentConfigurationService;
private ContinuumBuildAgentDavResourceFactory resourceFactory;
private FileSystemManager fsManager;
private File workingDirectory;
@Before
public void setUp()
throws Exception
{
request = mock( DavServletRequest.class );
response = mock( DavServletResponse.class );
buildAgentConfigurationService = mock( BuildAgentConfigurationService.class );
resourceFactory = new ContinuumBuildAgentDavResourceFactory();
resourceFactory.setBuildAgentConfigurationService( buildAgentConfigurationService );
fsManager = lookup( FileSystemManager.class );
String appserverBase = getTestFile( "target/appserver-base" ).getAbsolutePath();
System.setProperty( "appserver.base", appserverBase );
workingDirectory = new File( appserverBase, "data/working-directory" );
new File( workingDirectory, "1/target" ).mkdirs();
new File( workingDirectory, "1/target/continuum-artifact-1.0.jar" ).createNewFile();
}
@After
public void tearDown()
throws Exception
{
if ( workingDirectory.exists() )
{
fsManager.removeDir( workingDirectory );
}
}
@Test
public void testRequestArtifact()
throws Exception
{
DavResourceLocator locator = new ContinuumBuildAgentDavResourceLocator( "http://myhost/",
"/workingcopy/1/target/continuum-artifact-1.0.jar",
new ContinuumBuildAgentDavLocatorFactory(),
1 );
try
{
when( request.getMethod() ).thenReturn( "GET" );
when( buildAgentConfigurationService.getWorkingDirectory( 1 ) ).thenReturn( getWorkingDirectory( 1 ) );
when( request.getDavSession() ).thenReturn( new ContinuumBuildAgentDavSession() );
DavResource resource = resourceFactory.createResource( locator, request, response );
assertNotNull( resource );
assertEquals( locator.getRepositoryPath(), locator.getRepositoryPath() );
}
catch ( DavException e )
{
fail( "A DavException should not have been thrown!" );
}
}
@Test
public void testRequestArtifactDoesNotExist()
throws Exception
{
DavResourceLocator locator = new ContinuumBuildAgentDavResourceLocator( "http://myhost/",
"/workingcopy/1/pom.xml",
new ContinuumBuildAgentDavLocatorFactory(),
1 );
try
{
when( request.getMethod() ).thenReturn( "GET" );
when( buildAgentConfigurationService.getWorkingDirectory( 1 ) ).thenReturn( getWorkingDirectory( 1 ) );
resourceFactory.createResource( locator, request, response );
fail( "A DavException with 404 error code should have been thrown." );
}
catch ( DavException e )
{
assertEquals( 404, e.getErrorCode() );
}
}
private File getWorkingDirectory( int projectId )
{
return new File( workingDirectory, String.valueOf( projectId ) );
}
}
| 5,001 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/MockContinuumBuildAgentDavResource.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.io.IOUtils;
import org.apache.continuum.webdav.util.IndexWriter;
import org.apache.jackrabbit.webdav.DavResourceFactory;
import org.apache.jackrabbit.webdav.DavSession;
import org.apache.jackrabbit.webdav.io.OutputContext;
import java.io.FileInputStream;
import java.io.IOException;
import javax.activation.MimetypesFileTypeMap;
public class MockContinuumBuildAgentDavResource
extends ContinuumBuildAgentDavResource
{
public MockContinuumBuildAgentDavResource( String localResource, String logicalResource, DavSession session,
ContinuumBuildAgentDavResourceLocator locator,
DavResourceFactory factory, MimetypesFileTypeMap mimeTypes )
{
super( localResource, logicalResource, session, locator, factory, mimeTypes );
}
@Override
public void spool( OutputContext outputContext )
throws IOException
{
if ( !isCollection() )
{
outputContext.setContentLength( getLocalResource().length() );
outputContext.setContentType( getMimeTypes().getContentType( getLocalResource() ) );
}
if ( !isCollection() && outputContext.hasStream() )
{
FileInputStream is = null;
try
{
// Write content to stream
is = new FileInputStream( getLocalResource() );
IOUtils.copy( is, outputContext.getOutputStream() );
}
finally
{
IOUtils.closeQuietly( is );
}
}
else if ( outputContext.hasStream() )
{
IndexWriter writer = new IndexWriter( this, getLocalResource(), getLogicalResource() );
writer.write( outputContext );
}
}
}
| 5,002 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/MockContinuumBuildAgentDavResourceFactory.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavSession;
import java.io.File;
import java.io.IOException;
public class MockContinuumBuildAgentDavResourceFactory
extends ContinuumBuildAgentDavResourceFactory
{
@Override
protected File getResourceFile( int projectId, String logicalResource )
{
return new File( getWorkingDirectory( projectId ), logicalResource );
}
@Override
protected DavResource createResource( File resourceFile, String logicalResource, DavSession session,
ContinuumBuildAgentDavResourceLocator locator )
{
return new MockContinuumBuildAgentDavResource( resourceFile.getAbsolutePath(), logicalResource, session,
locator, this, getMimeTypes() );
}
private File getWorkingDirectory( int projectId )
{
String basedir = System.getProperty( "basedir" );
if ( basedir == null )
{
basedir = new File( "" ).getAbsolutePath();
}
File dir = new File( basedir, "target/appserver-base/data/working-directory/" + projectId );
try
{
dir = dir.getCanonicalFile();
}
catch ( IOException e )
{
}
return dir;
}
}
| 5,003 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/ContinuumBuildAgentDavSessionProviderTest.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.io.IOUtils;
import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService;
import org.apache.jackrabbit.webdav.DavSessionProvider;
import org.apache.jackrabbit.webdav.WebdavRequest;
import org.apache.jackrabbit.webdav.WebdavRequestImpl;
import org.codehaus.plexus.util.Base64;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.*;
public class ContinuumBuildAgentDavSessionProviderTest
{
private DavSessionProvider sessionProvider;
private WebdavRequest request;
private BuildAgentConfigurationService buildAgentConfigurationService;
@Before
public void setUp()
throws Exception
{
buildAgentConfigurationService = mock( BuildAgentConfigurationService.class );
sessionProvider = new ContinuumBuildAgentDavSessionProvider( buildAgentConfigurationService );
request = new WebdavRequestImpl( new HttpServletRequestMock(), null );
when( buildAgentConfigurationService.getSharedSecretPassword() ).thenReturn( "secret" );
}
@Test
public void testAttachSession()
throws Exception
{
assertNull( request.getDavSession() );
sessionProvider.attachSession( request );
assertNotNull( request.getDavSession() );
}
@Test
public void testReleaseSession()
throws Exception
{
assertNull( request.getDavSession() );
sessionProvider.attachSession( request );
assertNotNull( request.getDavSession() );
sessionProvider.releaseSession( request );
assertNull( request.getDavSession() );
}
@SuppressWarnings( "unchecked" )
private class HttpServletRequestMock
implements HttpServletRequest
{
public Object getAttribute( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Enumeration getAttributeNames()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getCharacterEncoding()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public int getContentLength()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getContentType()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public ServletInputStream getInputStream()
throws IOException
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getLocalAddr()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getLocalName()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public int getLocalPort()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Locale getLocale()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Enumeration getLocales()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getParameter( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Map getParameterMap()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Enumeration getParameterNames()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String[] getParameterValues( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getProtocol()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public BufferedReader getReader()
throws IOException
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getRealPath( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getRemoteAddr()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getRemoteHost()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public int getRemotePort()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public RequestDispatcher getRequestDispatcher( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getScheme()
{
return "";
}
public String getServerName()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public int getServerPort()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public boolean isSecure()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public void removeAttribute( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public void setAttribute( String arg0, Object arg1 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public void setCharacterEncoding( String arg0 )
throws UnsupportedEncodingException
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getAuthType()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getContextPath()
{
return "/";
}
public Cookie[] getCookies()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public long getDateHeader( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getHeader( String arg0 )
{
if ( arg0 != null && arg0.equalsIgnoreCase( "authorization" ) )
{
return getAuthorizationHeader();
}
return "";
}
public Enumeration getHeaderNames()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Enumeration getHeaders( String arg0 )
{
Hashtable<String, String> hashTable = new Hashtable<String, String>();
hashTable.put( "Authorization", getAuthorizationHeader() );
return hashTable.elements();
}
public int getIntHeader( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getMethod()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getPathInfo()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getPathTranslated()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getQueryString()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getRemoteUser()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getRequestURI()
{
return "/";
}
public StringBuffer getRequestURL()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getRequestedSessionId()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public String getServletPath()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public HttpSession getSession( boolean arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public HttpSession getSession()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public Principal getUserPrincipal()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public boolean isRequestedSessionIdFromCookie()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public boolean isRequestedSessionIdFromURL()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public boolean isRequestedSessionIdFromUrl()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public boolean isRequestedSessionIdValid()
{
throw new UnsupportedOperationException( "Not supported yet." );
}
public boolean isUserInRole( String arg0 )
{
throw new UnsupportedOperationException( "Not supported yet." );
}
private String getAuthorizationHeader()
{
try
{
String encodedPassword = IOUtils.toString( Base64.encodeBase64( ":secret".getBytes() ) );
return "Basic " + encodedPassword;
}
catch ( IOException e )
{
return "";
}
}
}
}
| 5,004 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/ContinuumBuildAgentDavSessionTest.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Test;
import static org.junit.Assert.*;
public class ContinuumBuildAgentDavSessionTest
{
@Test
public void testTokens()
{
ContinuumBuildAgentDavSession session = new ContinuumBuildAgentDavSession();
final String myToken = "thisisadavtoken";
session.addLockToken( myToken );
assertEquals( 1, session.getLockTokens().length );
assertEquals( myToken, session.getLockTokens()[0] );
session.removeLockToken( myToken );
assertEquals( 0, session.getLockTokens().length );
}
@Test
public void testAddReferencesThrowsUnsupportedOperationException()
{
ContinuumBuildAgentDavSession session = new ContinuumBuildAgentDavSession();
try
{
session.addReference( new Object() );
fail( "Did not throw UnsupportedOperationException" );
}
catch ( UnsupportedOperationException e )
{
assertTrue( true );
}
}
@Test
public void testRemoveReferencesThrowsUnsupportedOperationException()
{
ContinuumBuildAgentDavSession session = new ContinuumBuildAgentDavSession();
try
{
session.removeReference( new Object() );
fail( "Did not throw UnsupportedOperationException" );
}
catch ( UnsupportedOperationException e )
{
assertTrue( true );
}
}
}
| 5,005 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/ContinuumBuildAgentDavResourceLocatorTest.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ContinuumBuildAgentDavResourceLocatorTest
{
private ContinuumBuildAgentDavLocatorFactory factory;
private ContinuumBuildAgentDavResourceLocator locator;
@Before
public void setUp()
throws Exception
{
factory = new ContinuumBuildAgentDavLocatorFactory();
}
@Test
public void testAvoidDoubleSlashInHref()
throws Exception
{
String prefix = "http://myhost/";
String href = "/workingcopy/1/";
locator = getLocator( prefix, href );
assertEquals( 1, locator.getProjectId() );
assertEquals( "", locator.getWorkspaceName() );
assertEquals( "", locator.getWorkspacePath() );
assertEquals( "http://myhost/", locator.getPrefix() );
assertEquals( "http://myhost/workingcopy/1/", locator.getHref( false ) );
assertEquals( "http://myhost/workingcopy/1/", locator.getHref( true ) );
assertEquals( "/workingcopy/1", locator.getResourcePath() );
assertEquals( "/workingcopy/1", locator.getRepositoryPath() );
}
@Test
public void testLocatorWithPrefixHref()
throws Exception
{
String prefix = "http://myhost/";
String href = "/workingcopy/1";
locator = getLocator( prefix, href );
assertEquals( 1, locator.getProjectId() );
assertEquals( "", locator.getWorkspaceName() );
assertEquals( "", locator.getWorkspacePath() );
assertEquals( "http://myhost/", locator.getPrefix() );
assertEquals( "http://myhost/workingcopy/1", locator.getHref( false ) );
assertEquals( "http://myhost/workingcopy/1/", locator.getHref( true ) );
assertEquals( "/workingcopy/1", locator.getResourcePath() );
assertEquals( "/workingcopy/1", locator.getRepositoryPath() );
}
@Test
public void testLocatorWithHrefThatContainsPrefix()
throws Exception
{
String prefix = "http://myhost/";
String href = "http://myhost/workingcopy/1";
locator = getLocator( prefix, href );
assertEquals( 1, locator.getProjectId() );
assertEquals( "", locator.getWorkspaceName() );
assertEquals( "", locator.getWorkspacePath() );
assertEquals( "http://myhost/", locator.getPrefix() );
assertEquals( "http://myhost/workingcopy/1", locator.getHref( false ) );
assertEquals( "http://myhost/workingcopy/1/", locator.getHref( true ) );
assertEquals( "/workingcopy/1", locator.getResourcePath() );
assertEquals( "/workingcopy/1", locator.getRepositoryPath() );
}
@Test
public void testLocatorWithRootHref()
throws Exception
{
String prefix = "http://myhost/";
String href = "/";
locator = getLocator( prefix, href );
assertEquals( 0, locator.getProjectId() );
assertEquals( "", locator.getWorkspaceName() );
assertEquals( "", locator.getWorkspacePath() );
assertEquals( "http://myhost/", locator.getPrefix() );
assertEquals( "http://myhost/", locator.getHref( false ) );
assertEquals( "http://myhost/", locator.getHref( true ) );
assertEquals( "/", locator.getResourcePath() );
assertEquals( "/", locator.getRepositoryPath() );
}
private ContinuumBuildAgentDavResourceLocator getLocator( String prefix, String href )
{
return (ContinuumBuildAgentDavResourceLocator) factory.createResourceLocator( prefix, href );
}
}
| 5,006 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/util/WorkingCopyPathUtilTest.java | package org.apache.continuum.webdav.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.junit.Test;
import static org.junit.Assert.assertEquals;
public class WorkingCopyPathUtilTest
{
@Test
public void testGetProjectId()
{
String href = "/path/1/src/main/java";
assertEquals( 1, WorkingCopyPathUtil.getProjectId( href ) );
href = "path/2/src/test";
assertEquals( 2, WorkingCopyPathUtil.getProjectId( href ) );
}
@Test
public void testGetLogicalPath()
{
String href = "/workingcopy/1/src/main/java/org/apache/maven/someartifact.jar";
assertEquals( "/src/main/java/org/apache/maven/someartifact.jar", WorkingCopyPathUtil.getLogicalResource(
href ) );
href = "workingcopy/1/src/main/java/org/apache/maven/someartifact.jar";
assertEquals( "/src/main/java/org/apache/maven/someartifact.jar", WorkingCopyPathUtil.getLogicalResource(
href ) );
href = "workingcopy/1/src/main/java/";
assertEquals( "/src/main/java/", WorkingCopyPathUtil.getLogicalResource( href ) );
href = "workingcopy";
assertEquals( "/", WorkingCopyPathUtil.getLogicalResource( href ) );
}
}
| 5,007 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/ContinuumBuildAgentDavResourceFactory.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService;
import org.apache.continuum.webdav.util.WebdavMethodUtil;
import org.apache.continuum.webdav.util.WorkingCopyPathUtil;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavResourceFactory;
import org.apache.jackrabbit.webdav.DavResourceLocator;
import org.apache.jackrabbit.webdav.DavServletRequest;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.DavSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
@Component( role = org.apache.continuum.webdav.ContinuumBuildAgentDavResourceFactory.class )
public class ContinuumBuildAgentDavResourceFactory
implements DavResourceFactory
{
private static final Logger log = LoggerFactory.getLogger( ContinuumBuildAgentDavResourceFactory.class );
private static final MimetypesFileTypeMap mimeTypes;
@Requirement
private BuildAgentConfigurationService buildAgentConfigurationService;
static
{
mimeTypes = new MimetypesFileTypeMap();
mimeTypes.addMimeTypes( "application/java-archive jar war ear" );
mimeTypes.addMimeTypes( "application/java-class class" );
mimeTypes.addMimeTypes( "image/png png" );
}
public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
throws DavException
{
ContinuumBuildAgentDavResourceLocator continuumLocator = checkLocatorIsInstanceOfContinuumBuildAgentLocator(
locator );
String logicalResource = WorkingCopyPathUtil.getLogicalResource( locator.getResourcePath() );
if ( logicalResource.startsWith( "/" ) )
{
logicalResource = logicalResource.substring( 1 );
}
File resourceFile = getResourceFile( continuumLocator.getProjectId(), logicalResource );
if ( !resourceFile.exists() || ( continuumLocator.getHref( false ).endsWith( "/" ) &&
!resourceFile.isDirectory() ) )
{
// force a resource not found
log.error( "Resource file '" + resourceFile.getAbsolutePath() + "' does not exist" );
throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
}
else
{
return createResource( resourceFile, logicalResource, davSession, continuumLocator );
}
}
public DavResource createResource( DavResourceLocator locator, DavServletRequest request,
DavServletResponse response )
throws DavException
{
ContinuumBuildAgentDavResourceLocator continuumLocator = checkLocatorIsInstanceOfContinuumBuildAgentLocator(
locator );
if ( !WebdavMethodUtil.isReadMethod( request.getMethod() ) )
{
throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
"Write method not allowed in working copy" );
}
String logicalResource = WorkingCopyPathUtil.getLogicalResource( continuumLocator.getResourcePath() );
if ( logicalResource.startsWith( "/" ) )
{
logicalResource = logicalResource.substring( 1 );
}
File resourceFile = getResourceFile( continuumLocator.getProjectId(), logicalResource );
if ( !resourceFile.exists() || ( continuumLocator.getHref( false ).endsWith( "/" ) &&
!resourceFile.isDirectory() ) )
{
// force a resource not found
log.error( "Resource file '" + resourceFile.getAbsolutePath() + "' does not exist" );
throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
}
else
{
return createResource( resourceFile, logicalResource, request.getDavSession(), continuumLocator );
}
}
public BuildAgentConfigurationService getBuildAgentConfigurationService()
{
return buildAgentConfigurationService;
}
public MimetypesFileTypeMap getMimeTypes()
{
return mimeTypes;
}
public void setBuildAgentConfigurationService( BuildAgentConfigurationService buildAgentConfigurationService )
{
this.buildAgentConfigurationService = buildAgentConfigurationService;
}
private ContinuumBuildAgentDavResourceLocator checkLocatorIsInstanceOfContinuumBuildAgentLocator(
DavResourceLocator locator )
throws DavException
{
if ( !( locator instanceof ContinuumBuildAgentDavResourceLocator ) )
{
throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Locator does not implement ContinuumBuildAgentLocator" );
}
// Hidden paths
if ( locator.getResourcePath().startsWith( ContinuumBuildAgentDavResource.HIDDEN_PATH_PREFIX ) )
{
throw new DavException( HttpServletResponse.SC_NOT_FOUND );
}
ContinuumBuildAgentDavResourceLocator continuumLocator = (ContinuumBuildAgentDavResourceLocator) locator;
if ( continuumLocator.getProjectId() <= 0 )
{
log.error( "Invalid project id: " + continuumLocator.getProjectId() );
throw new DavException( HttpServletResponse.SC_NO_CONTENT );
}
return continuumLocator;
}
protected File getResourceFile( int projectId, String logicalResource )
{
File workingDir = buildAgentConfigurationService.getWorkingDirectory( projectId );
return new File( workingDir, logicalResource );
}
protected DavResource createResource( File resourceFile, String logicalResource, DavSession session,
ContinuumBuildAgentDavResourceLocator locator )
{
return new ContinuumBuildAgentDavResource( resourceFile.getAbsolutePath(), logicalResource, session, locator,
this, mimeTypes );
}
}
| 5,008 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/ContinuumBuildAgentDavSessionProvider.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavSessionProvider;
import org.apache.jackrabbit.webdav.WebdavRequest;
import org.codehaus.plexus.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
public class ContinuumBuildAgentDavSessionProvider
implements DavSessionProvider
{
private Logger log = LoggerFactory.getLogger( this.getClass() );
private BuildAgentConfigurationService buildAgentConfigurationService;
public ContinuumBuildAgentDavSessionProvider( BuildAgentConfigurationService buildAgentConfigurationService )
{
this.buildAgentConfigurationService = buildAgentConfigurationService;
}
public boolean attachSession( WebdavRequest request )
throws DavException
{
if ( !isAuthorized( request ) )
{
throw new DavException( HttpServletResponse.SC_UNAUTHORIZED );
}
request.setDavSession( new ContinuumBuildAgentDavSession() );
return true;
}
public void releaseSession( WebdavRequest request )
{
request.setDavSession( null );
}
private boolean isAuthorized( WebdavRequest request )
{
String header = request.getHeader( "Authorization" );
// in tomcat this is : authorization=Basic YWRtaW46TWFuYWdlMDc=
if ( header == null )
{
header = request.getHeader( "authorization" );
}
if ( ( header != null ) && header.startsWith( "Basic " ) )
{
String base64Token = header.substring( 6 );
String token = new String( Base64.decodeBase64( base64Token.getBytes() ) );
String password = "";
int delim = token.indexOf( ':' );
if ( delim != ( -1 ) )
{
password = token.substring( delim + 1 );
}
if ( buildAgentConfigurationService.getSharedSecretPassword() != null &&
buildAgentConfigurationService.getSharedSecretPassword().equals( password ) )
{
log.debug( "Password matches configured shared key in continuum build agent." );
return true;
}
}
log.warn( "Not authorized to access the working copy." );
return false;
}
}
| 5,009 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/WorkingCopyServlet.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavLocatorFactory;
import org.apache.jackrabbit.webdav.DavMethods;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavResourceFactory;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.DavSessionProvider;
import org.apache.jackrabbit.webdav.WebdavRequest;
import org.apache.jackrabbit.webdav.WebdavRequestImpl;
import org.apache.jackrabbit.webdav.WebdavResponse;
import org.apache.jackrabbit.webdav.WebdavResponseImpl;
import org.apache.jackrabbit.webdav.server.AbstractWebdavServlet;
import org.codehaus.plexus.spring.PlexusToSpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WorkingCopyServlet
extends AbstractWebdavServlet
{
private Logger log = LoggerFactory.getLogger( this.getClass() );
private DavLocatorFactory locatorFactory;
private DavResourceFactory resourceFactory;
protected DavSessionProvider sessionProvider;
@Override
public void init( ServletConfig servletConfig )
throws ServletException
{
super.init( servletConfig );
initServers( servletConfig );
}
/**
* Service the given request. This method has been overridden and copy/pasted to allow better exception handling and
* to support different realms
*
* @param request
* @param response
* @throws ServletException
* @throws java.io.IOException
*/
@Override
protected void service( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
WebdavRequest webdavRequest = new WebdavRequestImpl( request, getLocatorFactory() );
// DeltaV requires 'Cache-Control' header for all methods except 'VERSION-CONTROL' and 'REPORT'.
int methodCode = DavMethods.getMethodCode( request.getMethod() );
boolean noCache = DavMethods.isDeltaVMethod( webdavRequest ) &&
!( DavMethods.DAV_VERSION_CONTROL == methodCode || DavMethods.DAV_REPORT == methodCode );
WebdavResponse webdavResponse = new WebdavResponseImpl( response, noCache );
DavResource resource = null;
try
{
// make sure there is a authenticated user
if ( !( getDavSessionProvider() ).attachSession( webdavRequest ) )
{
return;
}
// check matching if=header for lock-token relevant operations
resource = getResourceFactory().createResource( webdavRequest.getRequestLocator(), webdavRequest,
webdavResponse );
if ( !isPreconditionValid( webdavRequest, resource ) )
{
webdavResponse.sendError( DavServletResponse.SC_PRECONDITION_FAILED );
return;
}
if ( !execute( webdavRequest, webdavResponse, methodCode, resource ) )
{
super.service( request, response );
}
}
catch ( DavException e )
{
if ( e.getErrorCode() == HttpServletResponse.SC_UNAUTHORIZED )
{
final String msg = "Unauthorized error";
log.error( msg );
webdavResponse.sendError( e.getErrorCode(), msg );
}
else if ( e.getCause() != null )
{
webdavResponse.sendError( e.getErrorCode(), e.getCause().getMessage() );
}
else
{
webdavResponse.sendError( e.getErrorCode(), e.getMessage() );
}
}
finally
{
getDavSessionProvider().releaseSession( webdavRequest );
}
}
public synchronized void initServers( ServletConfig servletConfig )
{
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
servletConfig.getServletContext() );
resourceFactory = (DavResourceFactory) wac.getBean( PlexusToSpringUtils.
buildSpringId( ContinuumBuildAgentDavResourceFactory.class ) );
BuildAgentConfigurationService buildAgentConfigurationService = (BuildAgentConfigurationService) wac.getBean(
PlexusToSpringUtils.buildSpringId( BuildAgentConfigurationService.class ) );
locatorFactory = new ContinuumBuildAgentDavLocatorFactory();
sessionProvider = new ContinuumBuildAgentDavSessionProvider( buildAgentConfigurationService );
}
@Override
public String getAuthenticateHeaderValue()
{
throw new UnsupportedOperationException();
}
@Override
public DavSessionProvider getDavSessionProvider()
{
return sessionProvider;
}
@Override
public DavLocatorFactory getLocatorFactory()
{
return locatorFactory;
}
@Override
public DavResourceFactory getResourceFactory()
{
return resourceFactory;
}
@Override
protected boolean isPreconditionValid( WebdavRequest request, DavResource resource )
{
// TODO Auto-generated method stub
return true;
}
@Override
public void setDavSessionProvider( final DavSessionProvider sessionProvider )
{
this.sessionProvider = sessionProvider;
}
@Override
public void setLocatorFactory( final DavLocatorFactory locatorFactory )
{
this.locatorFactory = locatorFactory;
}
@Override
public void setResourceFactory( DavResourceFactory resourceFactory )
{
this.resourceFactory = resourceFactory;
}
@Override
public void destroy()
{
resourceFactory = null;
locatorFactory = null;
sessionProvider = null;
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext( getServletContext() );
if ( wac instanceof ConfigurableApplicationContext )
{
( (ConfigurableApplicationContext) wac ).close();
}
super.destroy();
}
}
| 5,010 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/ContinuumBuildAgentDavResource.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.io.IOUtils;
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavResourceFactory;
import org.apache.jackrabbit.webdav.DavResourceIterator;
import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
import org.apache.jackrabbit.webdav.DavResourceLocator;
import org.apache.jackrabbit.webdav.DavSession;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.io.InputContext;
import org.apache.jackrabbit.webdav.io.OutputContext;
import org.apache.jackrabbit.webdav.lock.ActiveLock;
import org.apache.jackrabbit.webdav.lock.LockInfo;
import org.apache.jackrabbit.webdav.lock.LockManager;
import org.apache.jackrabbit.webdav.lock.Scope;
import org.apache.jackrabbit.webdav.lock.Type;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
import org.apache.jackrabbit.webdav.property.ResourceType;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;
public class ContinuumBuildAgentDavResource
implements DavResource
{
private static final Logger log = LoggerFactory.getLogger( ContinuumBuildAgentDavResource.class );
private final ContinuumBuildAgentDavResourceLocator locator;
private final DavResourceFactory factory;
private final File localResource;
private final String logicalResource;
private final DavSession session;
private final MimetypesFileTypeMap mimeTypes;
private DavPropertySet properties = null;
public static final String COMPLIANCE_CLASS = "1, 2";
public static final String HIDDEN_PATH_PREFIX = ".";
public static final String SUPPORTED_METHODS = "OPTIONS, GET, HEAD, TRACE, PROPFIND";
public ContinuumBuildAgentDavResource( String localResource, String logicalResource, DavSession session,
ContinuumBuildAgentDavResourceLocator locator, DavResourceFactory factory,
MimetypesFileTypeMap mimeTypes )
{
this.localResource = new File( localResource );
this.logicalResource = logicalResource;
this.locator = locator;
this.factory = factory;
this.session = session;
this.mimeTypes = mimeTypes;
}
public void addLockManager( LockManager lockManager )
{
}
public void addMember( DavResource davResource, InputContext inputContext )
throws DavException
{
throw new UnsupportedOperationException( "Not supported" );
}
public MultiStatusResponse alterProperties( List changeList )
throws DavException
{
return null;
}
public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
throws DavException
{
return null;
}
public void copy( DavResource destination, boolean shallow )
throws DavException
{
throw new UnsupportedOperationException( "Not supported" );
}
public boolean exists()
{
return localResource.exists();
}
public DavResource getCollection()
{
DavResource parent = null;
if ( getResourcePath() != null && !"/".equals( getResourcePath() ) )
{
String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
if ( "".equals( parentPath ) )
{
parentPath = "/";
}
DavResourceLocator parentloc = locator.getFactory().createResourceLocator( locator.getPrefix(),
parentPath );
try
{
parent = factory.createResource( parentloc, session );
}
catch ( DavException e )
{
// should not occur
}
}
return parent;
}
public String getComplianceClass()
{
return COMPLIANCE_CLASS;
}
public String getDisplayName()
{
String resPath = getResourcePath();
return ( resPath != null ) ? Text.getName( resPath ) : resPath;
}
public DavResourceFactory getFactory()
{
return factory;
}
public String getHref()
{
return locator.getHref( isCollection() );
}
public File getLocalResource()
{
return localResource;
}
public DavResourceLocator getLocator()
{
return locator;
}
public ActiveLock getLock( Type type, Scope scope )
{
return null;
}
public ActiveLock[] getLocks()
{
return null;
}
public String getLogicalResource()
{
return logicalResource;
}
public DavResourceIterator getMembers()
{
List<DavResource> list = new ArrayList<DavResource>();
if ( exists() && isCollection() )
{
for ( String item : localResource.list() )
{
try
{
if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
{
String path = locator.getResourcePath() + '/' + item;
DavResourceLocator resourceLocator = locator.getFactory().createResourceLocator(
locator.getPrefix(), path );
DavResource resource = factory.createResource( resourceLocator, session );
if ( resource != null )
{
log.debug( "Retrieved resource: " + resource.getResourcePath() );
list.add( resource );
}
}
}
catch ( DavException e )
{
// should not occur
}
}
}
return new DavResourceIteratorImpl( list );
}
public MimetypesFileTypeMap getMimeTypes()
{
return mimeTypes;
}
public long getModificationTime()
{
return localResource.lastModified();
}
public DavPropertySet getProperties()
{
return initProperties();
}
public DavProperty getProperty( DavPropertyName propertyName )
{
return getProperties().get( propertyName );
}
public DavPropertyName[] getPropertyNames()
{
return getProperties().getPropertyNames();
}
public String getResourcePath()
{
return locator.getResourcePath();
}
public DavSession getSession()
{
return session;
}
public String getSupportedMethods()
{
return SUPPORTED_METHODS;
}
public boolean hasLock( Type type, Scope scope )
{
return false;
}
public boolean isCollection()
{
return localResource.isDirectory();
}
public boolean isLockable( Type type, Scope scope )
{
return false;
}
public ActiveLock lock( LockInfo lockInfo )
throws DavException
{
return null;
}
public void move( DavResource destination )
throws DavException
{
throw new UnsupportedOperationException( "Not supported" );
}
public ActiveLock refreshLock( LockInfo lockInfo, String lockTocken )
throws DavException
{
return null;
}
public void removeMember( DavResource member )
throws DavException
{
throw new UnsupportedOperationException( "Not supported" );
}
public void removeProperty( DavPropertyName propertyName )
throws DavException
{
throw new UnsupportedOperationException( "Not supported" );
}
public void setProperty( DavProperty property )
throws DavException
{
throw new UnsupportedOperationException( "Not supported" );
}
public void spool( OutputContext outputContext )
throws IOException
{
if ( !isCollection() )
{
outputContext.setContentLength( localResource.length() );
outputContext.setContentType( mimeTypes.getContentType( localResource ) );
}
if ( !isCollection() && outputContext.hasStream() )
{
FileInputStream is = null;
try
{
// Write content to stream
is = new FileInputStream( localResource );
IOUtils.copy( is, outputContext.getOutputStream() );
}
finally
{
IOUtils.closeQuietly( is );
}
}
}
public void unlock( String lockTocken )
throws DavException
{
}
/**
* Fill the set of properties
*/
protected DavPropertySet initProperties()
{
if ( !exists() )
{
properties = new DavPropertySet();
}
if ( properties != null )
{
return properties;
}
DavPropertySet properties = new DavPropertySet();
// set (or reset) fundamental properties
if ( getDisplayName() != null )
{
properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
}
if ( isCollection() )
{
properties.add( new ResourceType( ResourceType.COLLECTION ) );
// Windows XP support
properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
}
else
{
properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
// Windows XP support
properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
}
// Need to get the ISO8601 date for properties
DateTime dt = new DateTime( localResource.lastModified() );
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String modifiedDate = fmt.print( dt );
properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
this.properties = properties;
return properties;
}
}
| 5,011 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/ContinuumBuildAgentDavSession.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.jackrabbit.webdav.DavSession;
import java.util.HashSet;
public class ContinuumBuildAgentDavSession
implements DavSession
{
private final HashSet<String> lockTokens = new HashSet<String>();
public void addLockToken( String token )
{
lockTokens.add( token );
}
public void addReference( Object reference )
{
throw new UnsupportedOperationException( "Not supported yet" );
}
public String[] getLockTokens()
{
return (String[]) lockTokens.toArray( new String[lockTokens.size()] );
}
public void removeLockToken( String token )
{
lockTokens.remove( token );
}
public void removeReference( Object reference )
{
throw new UnsupportedOperationException( "Not supported yet" );
}
}
| 5,012 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/ContinuumBuildAgentDavResourceLocator.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.webdav.DavLocatorFactory;
import org.apache.jackrabbit.webdav.DavResourceLocator;
public class ContinuumBuildAgentDavResourceLocator
implements DavResourceLocator
{
private final String prefix;
private final String resourcePath;
private final String href;
private final DavLocatorFactory davLocatorFactory;
private final int projectId;
public ContinuumBuildAgentDavResourceLocator( String prefix, String resourcePath,
DavLocatorFactory davLocatorFactory, int projectId )
{
this.prefix = prefix;
this.davLocatorFactory = davLocatorFactory;
this.projectId = projectId;
String escapedPath = Text.escapePath( resourcePath );
String hrefPrefix = prefix;
// Ensure no extra slashes when href is joined
if ( hrefPrefix.endsWith( "/" ) && escapedPath.startsWith( "/" ) )
{
hrefPrefix = hrefPrefix.substring( 0, hrefPrefix.length() - 1 );
}
href = hrefPrefix + escapedPath;
String path = resourcePath;
if ( !resourcePath.startsWith( "/" ) )
{
path = "/" + resourcePath;
}
//Remove trailing slashes otherwise Text.getRelativeParent fails
if ( resourcePath.endsWith( "/" ) && resourcePath.length() > 1 )
{
path = resourcePath.substring( 0, resourcePath.length() - 1 );
}
this.resourcePath = path;
}
public DavLocatorFactory getFactory()
{
return davLocatorFactory;
}
public String getHref( boolean isCollection )
{
// avoid doubled trailing '/' for the root item
String suffix = ( isCollection && !isRootLocation() && !href.endsWith( "/" ) ) ? "/" : "";
return href + suffix;
}
public String getPrefix()
{
return prefix;
}
public int getProjectId()
{
return projectId;
}
public String getRepositoryPath()
{
return getResourcePath();
}
public String getResourcePath()
{
return resourcePath;
}
public String getWorkspaceName()
{
return "";
}
public String getWorkspacePath()
{
return "";
}
/**
* Computes the hash code from the href, which is built using the final fields prefix and resourcePath.
*
* @return the hash code
*/
public int hashCode()
{
return href.hashCode();
}
public boolean isRootLocation()
{
return "/".equals( resourcePath );
}
public boolean isSameWorkspace( DavResourceLocator locator )
{
return isSameWorkspace( locator.getWorkspaceName() );
}
public boolean isSameWorkspace( String workspaceName )
{
return getWorkspaceName().equals( workspaceName );
}
/**
* Equality of path is achieved if the specified object is a <code>DavResourceLocator</code> object with the same
* hash code.
*
* @param obj the object to compare to
* @return <code>true</code> if the 2 objects are equal; <code>false</code> otherwise
*/
public boolean equals( Object obj )
{
if ( obj instanceof DavResourceLocator )
{
DavResourceLocator other = (DavResourceLocator) obj;
return hashCode() == other.hashCode();
}
return false;
}
}
| 5,013 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/ContinuumBuildAgentDavLocatorFactory.java | package org.apache.continuum.webdav;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.webdav.util.WorkingCopyPathUtil;
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.webdav.DavLocatorFactory;
import org.apache.jackrabbit.webdav.DavResourceLocator;
public class ContinuumBuildAgentDavLocatorFactory
implements DavLocatorFactory
{
public DavResourceLocator createResourceLocator( String prefix, String href )
{
// build prefix string and remove all prefixes from the given href.
StringBuilder b = new StringBuilder();
if ( prefix != null && prefix.length() > 0 )
{
b.append( prefix );
if ( !prefix.endsWith( "/" ) )
{
b.append( '/' );
}
if ( href.startsWith( prefix ) )
{
href = href.substring( prefix.length() );
}
}
// special treatment for root item, that has no name but '/' path.
if ( href == null || "".equals( href ) )
{
href = "/";
}
final int projectId = WorkingCopyPathUtil.getProjectId( href );
return new ContinuumBuildAgentDavResourceLocator( b.toString(), Text.unescape( href ), this, projectId );
}
public DavResourceLocator createResourceLocator( String prefix, String workspacePath, String resourcePath )
{
return createResourceLocator( prefix, workspacePath, resourcePath, true );
}
public DavResourceLocator createResourceLocator( String prefix, String workspacePath, String path,
boolean isResourcePath )
{
final int projectId = WorkingCopyPathUtil.getProjectId( path );
return new ContinuumBuildAgentDavResourceLocator( prefix, path, this, projectId );
}
}
| 5,014 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/util/IndexWriter.java | package org.apache.continuum.webdav.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.commons.lang.StringUtils;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.io.OutputContext;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class IndexWriter
{
private final String logicalResource;
private final List<File> localResources;
public IndexWriter( DavResource resource, File localResource, String logicalResource )
{
this.localResources = new ArrayList<File>();
this.localResources.add( localResource );
this.logicalResource = logicalResource;
}
public IndexWriter( DavResource resource, List<File> localResources, String logicalResource )
{
this.localResources = localResources;
this.logicalResource = logicalResource;
}
public void write( OutputContext outputContext )
{
outputContext.setModificationTime( new Date().getTime() );
outputContext.setContentType( "text/html" );
outputContext.setETag( "" );
if ( outputContext.hasStream() )
{
PrintWriter writer = new PrintWriter( outputContext.getOutputStream() );
writeDocumentStart( writer );
writeHyperlinks( writer );
writeDocumentEnd( writer );
writer.flush();
writer.close();
}
}
private void writeDocumentStart( PrintWriter writer )
{
writer.println( "<html>" );
writer.println( "<head>" );
writer.println( "<title>Working Copy: /" + logicalResource + "</title>" );
writer.println( "</head>" );
writer.println( "<body>" );
writer.println( "<h3>Working Copy: /" + logicalResource + "</h3>" );
// Check if not root
if ( logicalResource.length() > 0 )
{
File file = new File( logicalResource );
String parentName = file.getParent() == null ? "/" : file.getParent();
//convert to unix path in case archiva is hosted on windows
parentName = StringUtils.replace( parentName, "\\", "/" );
writer.println( "<ul>" );
writer.println( "<li><a href=\"../\">" + parentName + "</a> <i><small>(Parent)</small></i></li>" );
writer.println( "</ul>" );
}
writer.println( "</ul>" );
}
private void writeDocumentEnd( PrintWriter writer )
{
writer.println( "</ul>" );
writer.println( "</body>" );
writer.println( "</html>" );
}
private void writeHyperlinks( PrintWriter writer )
{
for ( File localResource : localResources )
{
List<File> files = new ArrayList<File>( Arrays.asList( localResource.listFiles() ) );
Collections.sort( files );
for ( File file : files )
{
writeHyperlink( writer, file.getName(), file.isDirectory() );
}
}
}
private void writeHyperlink( PrintWriter writer, String resourceName, boolean directory )
{
if ( directory && !"CVS".equals( resourceName ) && !".svn".equals( resourceName ) && !"SCCS".equals(
resourceName ) )
{
writer.println( "<li><a href=\"" + resourceName + "/\">" + resourceName + "</a></li>" );
}
else if ( !directory && !".cvsignore".equals( resourceName ) && !"vssver.scc".equals( resourceName ) &&
!".DS_Store".equals( resourceName ) && !"release.properties".equals( resourceName ) )
{
writer.println( "<li><a href=\"" + resourceName + "\">" + resourceName + "</a></li>" );
}
}
}
| 5,015 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/util/WorkingCopyPathUtil.java | package org.apache.continuum.webdav.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.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
public class WorkingCopyPathUtil
{
public static String getLogicalResource( final String href )
{
String logicalResource = null;
String requestPathInfo = StringUtils.defaultString( href );
//remove prefix ie /workingcopy/blah becomes /blah
requestPathInfo = removePrefix( requestPathInfo );
// Remove prefixing slash as the project id doesn't contain it;
if ( requestPathInfo.startsWith( "/" ) )
{
requestPathInfo = requestPathInfo.substring( 1 );
}
int slash = requestPathInfo.indexOf( '/' );
if ( slash > 0 )
{
logicalResource = requestPathInfo.substring( slash );
if ( logicalResource.endsWith( "/.." ) )
{
logicalResource += "/";
}
if ( logicalResource != null && logicalResource.startsWith( "//" ) )
{
logicalResource = logicalResource.substring( 1 );
}
if ( logicalResource == null )
{
logicalResource = "/";
}
}
else
{
logicalResource = "/";
}
return logicalResource;
}
public static int getProjectId( final String href )
{
String requestPathInfo = StringUtils.defaultString( href );
// Remove prefix ie /workingcopy/blah becomes /blah
requestPathInfo = removePrefix( requestPathInfo );
// Remove prefixing slash as the project id doesn't contain it;
if ( requestPathInfo.startsWith( "/" ) )
{
requestPathInfo = requestPathInfo.substring( 1 );
}
int projectId = 0;
try
{
// Find first element, if slash exists.
int slash = requestPathInfo.indexOf( '/' );
if ( slash > 0 )
{
// Filtered: "1/src/main/java/" -> "1"
projectId = Integer.parseInt( requestPathInfo.substring( 0, slash ) );
}
else
{
projectId = Integer.parseInt( requestPathInfo );
}
}
catch ( NumberFormatException e )
{
}
return projectId;
}
private static String removePrefix( final String href )
{
String[] parts = StringUtils.split( href, '/' );
parts = (String[]) ArrayUtils.subarray( parts, 1, parts.length );
if ( parts == null || parts.length == 0 )
{
return "/";
}
String joinedString = StringUtils.join( parts, '/' );
if ( href.endsWith( "/" ) )
{
joinedString = joinedString + "/";
}
return joinedString;
}
}
| 5,016 |
0 | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav | Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/main/java/org/apache/continuum/webdav/util/WebdavMethodUtil.java | package org.apache.continuum.webdav.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.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class WebdavMethodUtil
{
private static final List<String> READ_METHODS;
static
{
READ_METHODS = new ArrayList<String>();
READ_METHODS.add( "HEAD" );
READ_METHODS.add( "GET" );
READ_METHODS.add( "PROPFIND" );
READ_METHODS.add( "OPTIONS" );
READ_METHODS.add( "REPORT" );
}
public static boolean isReadMethod( String method )
{
if ( StringUtils.isBlank( method ) )
{
throw new IllegalArgumentException( "WebDAV method is empty" );
}
return READ_METHODS.contains( method.toUpperCase( Locale.US ) );
}
}
| 5,017 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/DefaultContinuumTest.java | package org.apache.maven.continuum;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import edu.emory.mathcs.backport.java.util.Arrays;
import org.apache.continuum.buildmanager.BuildsManager;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.model.release.ContinuumReleaseResult;
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.release.config.ContinuumReleaseDescriptor;
import org.apache.continuum.repository.RepositoryService;
import org.apache.continuum.taskqueue.manager.TaskQueueManager;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.builddefinition.BuildDefinitionService;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.initialization.ContinuumInitializer;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.apache.maven.continuum.model.scm.ChangeSet;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.shared.release.ReleaseResult;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class DefaultContinuumTest
extends AbstractContinuumTest
{
private static final Logger log = LoggerFactory.getLogger( DefaultContinuumTest.class );
private TaskQueueManager taskQueueManager;
private ProjectDao projectDao;
private BuildResultDao buildResultDao;
@Before
public void setUp()
throws Exception
{
taskQueueManager = mock( TaskQueueManager.class );
projectDao = mock( ProjectDao.class );
buildResultDao = mock( BuildResultDao.class );
}
@Test
public void testContinuumConfiguration()
throws Exception
{
lookup( Continuum.ROLE );
}
@Test
public void testAddMavenTwoProjectSet()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
int projectCount = getProjectDao().getAllProjectsByName().size();
int projectGroupCount = getProjectGroupDao().getAllProjectGroupsWithProjects().size();
File rootPom = getTestFile( "src/test/resources/projects/continuum/continuum-notifiers/pom.xml" );
assertTrue( rootPom.exists() );
ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( rootPom.toURI().toURL().toExternalForm(),
-1, true, false, true, -1, false );
assertNotNull( result );
assertEquals( "result.warnings.size" + result.getErrors(), 0, result.getErrors().size() );
assertEquals( "result.projects.size", 3, result.getProjects().size() );
assertEquals( "result.projectGroups.size", 1, result.getProjectGroups().size() );
log.info( "number of projects: " + getProjectDao().getAllProjectsByName().size() );
log.info( "number of project groups: " + getProjectGroupDao().getAllProjectGroupsWithProjects().size() );
assertEquals( "Total project count", projectCount + 3, getProjectDao().getAllProjectsByName().size() );
assertEquals( "Total project group count.", projectGroupCount + 1,
getProjectGroupDao().getAllProjectGroupsWithProjects().size() );
Map<String, Project> projects = new HashMap<String, Project>();
for ( Project project : getProjectDao().getAllProjectsByName() )
{
projects.put( project.getName(), project );
// validate project in project group
assertTrue( "project not in project group", getProjectGroupDao().getProjectGroupByProjectId(
project.getId() ) != null );
}
assertTrue( "no irc notifier", projects.containsKey( "Continuum IRC Notifier" ) );
assertTrue( "no jabber notifier", projects.containsKey( "Continuum Jabber Notifier" ) );
}
@Test
public void testUpdateMavenTwoProject()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
// ----------------------------------------------------------------------
// Test projects with duplicate names
// ----------------------------------------------------------------------
String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url );
assertNotNull( result );
List<Project> projects = result.getProjects();
assertEquals( 1, projects.size() );
assertEquals( Project.class, projects.get( 0 ).getClass() );
Project project = projects.get( 0 );
// reattach
project = continuum.getProject( project.getId() );
project.setName( project.getName() + " 2" );
continuum.updateProject( project );
project = continuum.getProject( project.getId() );
}
@Test
public void testRemoveMavenTwoProject()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
Project project = makeStubProject( "test-project" );
ProjectGroup defaultGroup = getDefaultProjectGroup();
defaultGroup.addProject( project );
getProjectGroupDao().updateProjectGroup( defaultGroup );
project = getProjectDao().getProjectByName( "test-project" );
assertNotNull( project );
BuildResult buildResult = new BuildResult();
getBuildResultDao().addBuildResult( project, buildResult );
Collection<BuildResult> brs = continuum.getBuildResultsForProject( project.getId(), 0, 5 );
assertEquals( "Build result of project was not added", 1, brs.size() );
// delete project
continuum.removeProject( project.getId() );
try
{
continuum.getProject( project.getId() );
fail( "Project was not removed" );
}
catch ( ContinuumException expected )
{
brs = continuum.getBuildResultsForProject( project.getId(), 0, 5 );
assertEquals( "Build result of project was not removed", 0, brs.size() );
}
}
@Test
public void testBuildDefinitions()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url );
assertNotNull( result );
List<Project> projects = result.getProjects();
assertEquals( 1, projects.size() );
assertEquals( Project.class, projects.get( 0 ).getClass() );
Project project = projects.get( 0 );
// reattach
project = continuum.getProject( project.getId() );
ProjectGroup projectGroup = getProjectGroupDao().getProjectGroupByProjectId( project.getId() );
projectGroup = getProjectGroupDao().getProjectGroupWithBuildDetailsByProjectGroupId( projectGroup.getId() );
List<BuildDefinition> buildDefs = projectGroup.getBuildDefinitions();
assertTrue( "missing project group build definition", !buildDefs.isEmpty() );
assertTrue( "more then one project group build definition on add project", buildDefs.size() == 1 );
BuildDefinition pgbd = buildDefs.get( 0 );
pgbd.setGoals( "foo" );
continuum.updateBuildDefinitionForProjectGroup( projectGroup.getId(), pgbd );
pgbd = continuum.getBuildDefinition( pgbd.getId() );
assertTrue( "update failed for project group build definition", "foo".equals( pgbd.getGoals() ) );
assertTrue( "project group build definition is not default", pgbd.isDefaultForProject() );
BuildDefinition nbd = new BuildDefinition();
nbd.setGoals( "clean" );
nbd.setArguments( "" );
nbd.setDefaultForProject( true );
nbd.setSchedule( getScheduleDao().getScheduleByName( ConfigurationService.DEFAULT_SCHEDULE_NAME ) );
continuum.addBuildDefinitionToProject( project.getId(), nbd );
assertTrue( "project lvl build definition not default for project", continuum.getDefaultBuildDefinition(
project.getId() ).getId() == nbd.getId() );
continuum.removeBuildDefinitionFromProject( project.getId(), nbd.getId() );
assertTrue( "default build definition didn't toggle back to project group level",
continuum.getDefaultBuildDefinition( project.getId() ).getId() == pgbd.getId() );
try
{
continuum.removeBuildDefinitionFromProjectGroup( projectGroup.getId(), pgbd.getId() );
fail( "we were able to remove the default build definition, and that is bad" );
}
catch ( ContinuumException expected )
{
}
}
/**
* todo add another project group to test
*/
@Test
public void testProjectGroups()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
Collection projectGroupList = continuum.getAllProjectGroups();
int projectGroupsBefore = projectGroupList.size();
assertEquals( 1, projectGroupsBefore );
String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url );
assertNotNull( result );
assertEquals( 1, result.getProjectGroups().size() );
ProjectGroup projectGroup = result.getProjectGroups().get( 0 );
assertEquals( "plexus", projectGroup.getGroupId() );
projectGroupList = continuum.getAllProjectGroups();
assertEquals( "Project group missing, should have " + ( projectGroupsBefore + 1 ) + " project groups",
projectGroupsBefore + 1, projectGroupList.size() );
projectGroup = (ProjectGroup) projectGroupList.iterator().next();
assertNotNull( projectGroup );
BuildsManager buildsManager = continuum.getBuildsManager();
List<Project> projects = continuum.getProjectGroupWithProjects( projectGroup.getId() ).getProjects();
int[] projectIds = new int[projects.size()];
int idx = 0;
for ( Project project : projects )
{
projectIds[idx] = project.getId();
idx++;
}
while ( buildsManager.isAnyProjectCurrentlyBeingCheckedOut( projectIds ) )
{
}
continuum.removeProjectGroup( projectGroup.getId() );
projectGroupList = continuum.getAllProjectGroups();
assertEquals( "Remove project group failed", projectGroupsBefore, projectGroupList.size() );
}
/**
* test the logic for notifiers
*/
@Test
public void testProjectAndGroupNotifiers()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
Collection projectGroupList = continuum.getAllProjectGroups();
int projectGroupsBefore = projectGroupList.size();
assertEquals( 1, projectGroupsBefore );
String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url );
assertNotNull( result );
assertEquals( 1, result.getProjectGroups().size() );
ProjectGroup projectGroup = result.getProjectGroups().get( 0 );
continuum.addGroupNotifier( projectGroup.getId(), new ProjectNotifier() );
for ( Project p : (List<Project>) projectGroup.getProjects() )
{
continuum.addNotifier( p.getId(), new ProjectNotifier() );
}
projectGroup = continuum.getProjectGroupWithBuildDetails( projectGroup.getId() );
assertEquals( 1, projectGroup.getNotifiers().size() );
for ( Project p : (List<Project>) projectGroup.getProjects() )
{
assertEquals( 2, p.getNotifiers().size() );
}
}
@Test
public void testExecuteAction()
throws Exception
{
DefaultContinuum continuum = (DefaultContinuum) lookup( Continuum.class );
String exceptionName = ContinuumException.class.getName();
try
{
continuum.executeAction( "testAction", new HashMap() );
}
catch ( ContinuumException e )
{
//expected, check for twice wrapped exception
if ( e.getCause() != null )
{
assertFalse( exceptionName + " is wrapped in " + exceptionName, e.getCause().getClass().equals(
ContinuumException.class ) );
}
}
}
@Test
public void testRemoveProjectFromCheckoutQueue()
throws Exception
{
Continuum continuum = (Continuum) lookup( Continuum.ROLE );
BuildsManager parallelBuildsManager = continuum.getBuildsManager();
String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url );
assertNotNull( result );
List<Project> projects = result.getProjects();
assertEquals( 1, projects.size() );
assertEquals( Project.class, projects.get( 0 ).getClass() );
Project project = projects.get( 0 );
parallelBuildsManager.removeProjectFromCheckoutQueue( project.getId() );
assertFalse( "project still exist on the checkout queue", parallelBuildsManager.isInAnyCheckoutQueue(
project.getId() ) );
}
@Test
public void testAddAntProjectWithDefaultBuildDef()
throws Exception
{
Continuum continuum = getContinuum();
Project project = new Project();
project.setScmUrl( "scmUrl" );
ProjectGroup defaultProjectGroup = continuum.getProjectGroupByGroupId(
ContinuumInitializer.DEFAULT_PROJECT_GROUP_GROUP_ID );
int projectId = continuum.addProject( project, ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR,
defaultProjectGroup.getId() );
assertEquals( 1, continuum.getProjectGroupWithProjects( defaultProjectGroup.getId() ).getProjects().size() );
project = continuum.getProjectWithAllDetails( projectId );
assertNotNull( project );
BuildDefinitionService service = lookup( BuildDefinitionService.class );
assertEquals( 4, service.getAllBuildDefinitionTemplate().size() );
assertEquals( 5, service.getAllBuildDefinitions().size() );
BuildDefinition buildDef =
service.getDefaultAntBuildDefinitionTemplate().getBuildDefinitions().get( 0 );
buildDef = service.cloneBuildDefinition( buildDef );
buildDef.setTemplate( false );
continuum.addBuildDefinitionToProject( project.getId(), buildDef );
project = continuum.getProjectWithAllDetails( project.getId() );
assertEquals( 2, project.getBuildDefinitions().size() );
assertEquals( 4, service.getAllBuildDefinitionTemplate().size() );
assertEquals( 6, service.getAllBuildDefinitions().size() );
}
@Test
public void testRemoveProjectGroupWithRepository()
throws Exception
{
Continuum continuum = getContinuum();
RepositoryService service = lookup( RepositoryService.class );
LocalRepository repository = new LocalRepository();
repository.setName( "defaultRepo" );
repository.setLocation( getTestFile( "target/default-repository" ).getAbsolutePath() );
repository = service.addLocalRepository( repository );
ProjectGroup group = new ProjectGroup();
group.setGroupId( "testGroup" );
group.setName( "testGroup" );
group.setLocalRepository( repository );
continuum.addProjectGroup( group );
ProjectGroup retrievedDefaultProjectGroup = continuum.getProjectGroupByGroupId( "testGroup" );
assertNotNull( retrievedDefaultProjectGroup.getLocalRepository() );
continuum.removeProjectGroup( retrievedDefaultProjectGroup.getId() );
try
{
continuum.getProjectGroupByGroupId( "testGroup" );
fail( "project group was not deleted" );
}
catch ( Exception e )
{
// should fail. do nothing.
}
LocalRepository retrievedRepository = service.getLocalRepository( repository.getId() );
assertNotNull( retrievedRepository );
assertEquals( repository, retrievedRepository );
}
@Test
public void testContinuumReleaseResult()
throws Exception
{
Continuum continuum = getContinuum();
Project project = makeStubProject( "test-project" );
ProjectGroup defaultGroup = getDefaultProjectGroup();
defaultGroup.addProject( project );
getProjectGroupDao().updateProjectGroup( defaultGroup );
project = getProjectDao().getProjectByName( "test-project" );
assertNotNull( project );
assertEquals( 0, continuum.getAllContinuumReleaseResults().size() );
ReleaseResult result = new ReleaseResult();
result.setStartTime( System.currentTimeMillis() );
result.setEndTime( System.currentTimeMillis() );
result.setResultCode( 200 );
result.appendOutput( "Error in release" );
ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor();
descriptor.setPreparationGoals( "clean" );
descriptor.setReleaseBy( "admin" );
continuum.getReleaseManager().getReleaseResults().put( "test-release-id", result );
continuum.getReleaseManager().getPreparedReleases().put( "test-release-id", descriptor );
ContinuumReleaseResult releaseResult = continuum.addContinuumReleaseResult( project.getId(), "test-release-id",
"prepare" );
releaseResult = continuum.addContinuumReleaseResult( releaseResult );
List<ContinuumReleaseResult> releaseResults = continuum.getContinuumReleaseResultsByProjectGroup(
defaultGroup.getId() );
assertEquals( 1, releaseResults.size() );
assertEquals( releaseResult, releaseResults.get( 0 ) );
continuum.removeContinuumReleaseResult( releaseResult.getId() );
assertEquals( 0, continuum.getAllContinuumReleaseResults().size() );
assertEquals( defaultGroup, continuum.getProjectGroupByGroupId(
ContinuumInitializer.DEFAULT_PROJECT_GROUP_GROUP_ID ) );
}
@Test
public void testBuildProjectWhileProjectIsInReleaseStage()
throws Exception
{
DefaultContinuum continuum = (DefaultContinuum) getContinuum();
continuum.setTaskQueueManager( taskQueueManager );
continuum.setProjectDao( projectDao );
Project project = new Project();
project.setId( 1 );
project.setName( "Continuum Core" );
project.setGroupId( "org.apache.continuum" );
project.setArtifactId( "continuum-core" );
when( projectDao.getProject( 1 ) ).thenReturn( project );
when( taskQueueManager.isProjectInReleaseStage( "org.apache.continuum:continuum-core" ) ).thenReturn( true );
try
{
continuum.buildProject( 1, "test-user" );
fail( "An exception should have been thrown." );
}
catch ( ContinuumException e )
{
assertEquals( "Project (id=1) is currently in release stage.", e.getMessage() );
}
}
@Test
public void testBuildProjectGroupWhileAtLeastOneProjectIsInReleaseStage()
throws Exception
{
DefaultContinuum continuum = (DefaultContinuum) getContinuum();
continuum.setTaskQueueManager( taskQueueManager );
continuum.setProjectDao( projectDao );
List<Project> projects = new ArrayList<Project>();
Project project = new Project();
project.setId( 1 );
project.setName( "Continuum Core" );
project.setGroupId( "org.apache.continuum" );
project.setArtifactId( "continuum-core" );
projects.add( project );
project = new Project();
project.setId( 2 );
project.setName( "Continuum API" );
project.setGroupId( "org.apache.continuum" );
project.setArtifactId( "continuum-api" );
projects.add( project );
when( projectDao.getProjectsInGroup( 1 ) ).thenReturn( projects );
when( taskQueueManager.isProjectInReleaseStage( "org.apache.continuum:continuum-core" ) ).thenReturn( true );
try
{
continuum.buildProjectGroup( 1, new BuildTrigger( 1, "test-user" ) );
fail( "An exception should have been thrown." );
}
catch ( ContinuumException e )
{
assertEquals( "Cannot build project group. Project (id=1) in group is currently in release stage.",
e.getMessage() );
}
}
@Test
public void testGetChangesSinceLastSuccessNoSuccess()
throws Exception
{
DefaultContinuum continuum = getContinuum();
continuum.setBuildResultDao( buildResultDao );
when( buildResultDao.getPreviousBuildResultInSuccess( anyInt(), anyInt() ) ).thenReturn( null );
List<ChangeSet> changes = continuum.getChangesSinceLastSuccess( 5, 5 );
assertEquals( "no prior success should return no changes", 0, changes.size() );
}
@Test
public void testGetChangesSinceLastSuccessNoInterveningFailures()
throws Exception
{
DefaultContinuum continuum = getContinuum();
continuum.setBuildResultDao( buildResultDao );
int projectId = 123, fromId = 789, toId = 1011;
BuildResult priorResult = new BuildResult();
priorResult.setId( fromId );
when( buildResultDao.getPreviousBuildResultInSuccess( projectId, toId ) ).thenReturn( priorResult );
when( buildResultDao.getBuildResultsForProjectWithDetails( projectId, fromId, toId ) ).thenReturn(
Collections.EMPTY_LIST );
List<ChangeSet> changes = continuum.getChangesSinceLastSuccess( projectId, toId );
assertEquals( "no intervening failures, should return no changes", 0, changes.size() );
}
@Test
public void testGetChangesSinceLastSuccessInterveningFailures()
throws Exception
{
DefaultContinuum continuum = getContinuum();
continuum.setBuildResultDao( buildResultDao );
int projectId = 123, fromId = 789, toId = 1011;
BuildResult priorResult = new BuildResult();
priorResult.setId( fromId );
BuildResult[] failures = { resultWithChanges( 1 ), resultWithChanges( 0 ), resultWithChanges( 0, 1 ),
resultWithChanges( 1, 0 ), resultWithChanges( 0, 1, 0 ), resultWithChanges( 1, 0, 1 ) };
when( buildResultDao.getPreviousBuildResultInSuccess( projectId, toId ) ).thenReturn( priorResult );
when( buildResultDao.getBuildResultsForProjectWithDetails( projectId, fromId, toId ) ).thenReturn(
Arrays.asList( failures ) );
List<ChangeSet> changes = continuum.getChangesSinceLastSuccess( projectId, toId );
assertEquals( "should return same number of changes as in failed results", 6, changes.size() );
assertOldestToNewest( changes );
}
private static int changeCounter = 1;
private BuildResult resultWithChanges( int... changeSetCounts )
{
BuildResult result = new BuildResult();
ScmResult scmResult = new ScmResult();
result.setScmResult( scmResult );
for ( Integer changeCount : changeSetCounts )
{
for ( int i = 0; i < changeCount; i++ )
{
ChangeSet change = new ChangeSet();
change.setId( String.format( "%011d", changeCounter++ ) ); // zero-padded for string comparison
scmResult.addChange( change );
}
}
return result;
}
private void assertOldestToNewest( List<ChangeSet> changes )
{
if ( changes == null || changes.isEmpty() || changes.size() == 1 )
return;
for ( int prior = 0, next = 1; next < changes.size(); prior++, next = prior + 1 )
{
String priorId = changes.get( prior ).getId(), nextId = changes.get( next ).getId();
assertTrue( "changes were not in ascending order", priorId.compareTo( nextId ) < 0 );
}
}
private DefaultContinuum getContinuum()
throws Exception
{
return (DefaultContinuum) lookup( Continuum.class );
}
private BuildResultDao getBuildResultDao()
{
return lookup( BuildResultDao.class );
}
}
| 5,018 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/AddMaven2ProjectTest.java | package org.apache.maven.continuum;
import org.apache.continuum.AbstractAddProjectTest;
import org.apache.maven.continuum.builddefinition.BuildDefinitionService;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Collections;
import static org.junit.Assert.*;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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 olamy
*/
public class AddMaven2ProjectTest
extends AbstractAddProjectTest
{
protected final Logger log = LoggerFactory.getLogger( getClass() );
protected BuildDefinitionTemplate bdt;
protected BuildDefinition bd;
protected BuildDefinitionService bds;
@Before
public void setUp()
throws Exception
{
bd = new BuildDefinition();
bd.setGoals( "clean deploy" );
bd.setBuildFile( "pom.xml" );
bd.setDescription( "my foo" );
bd.setTemplate( true );
bds = lookup( BuildDefinitionService.class, "default" );
bd = bds.addBuildDefinition( bd );
assertEquals( 5, bds.getAllBuildDefinitions().size() );
bdt = new BuildDefinitionTemplate();
bdt.setName( "bdt foo" );
bdt = bds.addBuildDefinitionTemplate( bdt );
bdt = bds.addBuildDefinitionInTemplate( bdt, bd, false );
createLocalRepository();
}
@Test
public void testAddProjectToExistingGroupWithBuildDefTemplate()
throws Exception
{
ProjectGroup pg = new ProjectGroup();
pg.setName( "foo" );
pg.setDescription( "foo pg" );
getContinuum().addProjectGroup( pg );
pg = getContinuum().getAllProjectGroups().get( 1 );
assertEquals( 2, getContinuum().getAllProjectGroups().size() );
pg = getContinuum().getProjectGroupWithBuildDetails( pg.getId() );
// group created with the m2 default build def
assertEquals( 1, pg.getBuildDefinitions().size() );
assertEquals( "clean install", pg.getBuildDefinitions().get( 0 ).getGoals() );
File rootPom = getTestFile( "src/test/resources/projects/continuum/continuum-core/pom.xml" );
assertTrue( rootPom.exists() );
//String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = getContinuum().addMavenTwoProject(
rootPom.toURI().toURL().toExternalForm(), pg.getId(), true, false, false, bdt.getId(), false );
assertNotNull( result );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
project = getContinuum().getProjectWithBuildDetails( project.getId() );
assertNotNull( project );
log.info( "project buildDef list size : " + project.getBuildDefinitions().size() );
assertEquals( 1, project.getBuildDefinitions().size() );
// project with the build def coming from template
assertEquals( "clean deploy", project.getBuildDefinitions().get( 0 ).getGoals() );
}
@Test
public void testAddProjectWithGroupCreationWithBuildDefTemplate()
throws Exception
{
//bdt = bds.addBuildDefinitionInTemplate( bdt, bd, true );
File rootPom = getTestFile( "src/test/resources/projects/continuum/continuum-core/pom.xml" );
assertTrue( rootPom.exists() );
ContinuumProjectBuildingResult result = getContinuum().addMavenTwoProject(
rootPom.toURI().toURL().toExternalForm(), -1, true, false, true, bdt.getId(), false );
assertNotNull( result );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
assertNotNull( project );
project = getContinuum().getProjectWithBuildDetails( project.getId() );
log.info( "project buildDef list size : " + project.getBuildDefinitions().size() );
// build def only at the group level du to group creation
assertEquals( 0, project.getBuildDefinitions().size() );
log.info( "all pg size " + getContinuum().getAllProjectGroups().size() );
ProjectGroup pg = result.getProjectGroups().get( 0 );
pg = getContinuum().getProjectGroupWithBuildDetails( pg.getId() );
log.info( " pg groupId " + pg.getGroupId() );
//@ group level the db from template must be used
log.info( " pg builddefs size " + pg.getBuildDefinitions().size() );
log.info( "pg bd goals " + ( pg.getBuildDefinitions().get( 0 ) ).getGoals() );
assertEquals( "clean deploy", ( pg.getBuildDefinitions().get( 0 ) ).getGoals() );
}
@Test
public void testAddProjectWithGroupCreationDefaultBuildDef()
throws Exception
{
//bdt = bds.addBuildDefinitionInTemplate( bdt, bd, true );
File rootPom = getTestFile( "src/test/resources/projects/continuum/continuum-core/pom.xml" );
assertTrue( rootPom.exists() );
ContinuumProjectBuildingResult result = getContinuum().addMavenTwoProject(
rootPom.toURI().toURL().toExternalForm(), -1, true, false, true, -1, false );
assertNotNull( result );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
assertNotNull( project );
assertNotNull( project );
project = getContinuum().getProjectWithBuildDetails( project.getId() );
log.info( "project buildDef list size : " + project.getBuildDefinitions().size() );
// only build def at group level
assertEquals( 0, project.getBuildDefinitions().size() );
log.info( "all pg size " + getContinuum().getAllProjectGroups().size() );
ProjectGroup pg = result.getProjectGroups().get( 0 );
log.info( getContinuum().getAllProjectGroups().toString() );
log.info( " pg id " + Integer.toString( pg.getId() ) );
pg = getContinuum().getProjectGroupWithBuildDetails( pg.getId() );
//@ group level the db from template must be used
assertEquals( "clean install", pg.getBuildDefinitions().get( 0 ).getGoals() );
}
@Test
public void testAddProjectToExistingGroupDefaultBuildDef()
throws Exception
{
ProjectGroup pg = new ProjectGroup();
String groupId = "foo";
pg.setName( groupId );
pg.setGroupId( groupId );
pg.setDescription( "foo pg" );
getContinuum().addProjectGroup( pg );
pg = getContinuum().getProjectGroupByGroupIdWithBuildDetails( groupId );
assertEquals( 1, pg.getBuildDefinitions().size() );
BuildDefinition buildDefinition = pg.getBuildDefinitions().get( 0 );
assertEquals( "clean install", buildDefinition.getGoals() );
assertEquals( "--batch-mode --non-recursive", buildDefinition.getArguments() );
File rootPom = getTestFile( "src/test/resources/projects/continuum/continuum-core/pom.xml" );
assertTrue( rootPom.exists() );
//String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = getContinuum().addMavenTwoProject(
rootPom.toURI().toURL().toExternalForm(), pg.getId(), true, false, false, -1, false );
assertNotNull( result );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
project = getContinuum().getProjectWithBuildDetails( project.getId() );
assertNotNull( project );
assertEquals( 1, project.getBuildDefinitions().size() );
buildDefinition = project.getBuildDefinitions().get( 0 );
assertEquals( "clean install", buildDefinition.getGoals() );
assertEquals( "--batch-mode", buildDefinition.getArguments() );
}
@Test
public void testAddProjectToExistingGroupMatchingBuildDef()
throws Exception
{
ProjectGroup pg = new ProjectGroup();
String groupId = "testAddProjectToExistingGroupMatchingBuildDef";
pg.setName( groupId );
pg.setGroupId( groupId );
pg.setDescription( "foo pg" );
getContinuum().addProjectGroup( pg );
pg = getContinuum().getProjectGroupByGroupIdWithBuildDetails( groupId );
assertEquals( 1, pg.getBuildDefinitions().size() );
BuildDefinition buildDefinition = pg.getBuildDefinitions().get( 0 );
buildDefinition.setArguments( "--batch-mode" );
bds.updateBuildDefinition( buildDefinition );
pg = getContinuum().getProjectGroupByGroupIdWithBuildDetails( groupId );
buildDefinition = pg.getBuildDefinitions().get( 0 );
assertEquals( "clean install", buildDefinition.getGoals() );
assertEquals( "--batch-mode", buildDefinition.getArguments() );
File rootPom = getTestFile( "src/test/resources/projects/continuum/continuum-core/pom.xml" );
assertTrue( rootPom.exists() );
//String url = getTestFile( "src/test-projects/project1/pom.xml" ).toURL().toExternalForm();
ContinuumProjectBuildingResult result = getContinuum().addMavenTwoProject(
rootPom.toURI().toURL().toExternalForm(), pg.getId(), true, false, false, -1, false );
assertNotNull( result );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
project = getContinuum().getProjectWithBuildDetails( project.getId() );
assertNotNull( project );
assertEquals( 0, project.getBuildDefinitions().size() );
}
private Continuum getContinuum()
throws Exception
{
return (Continuum) lookup( Continuum.ROLE );
}
@Override
protected String getPlexusConfigLocation()
{
return "org/apache/maven/continuum/DefaultContinuumTest.xml";
}
@Override
protected String getSpringConfigLocation()
{
return "applicationContextSlf4jPlexusLogger.xml";
}
}
| 5,019 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/AddProjectToCheckoutQueueStub.java | package org.apache.maven.continuum;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.core.action.AbstractContinuumAction;
import org.apache.maven.continuum.core.action.CheckoutProjectContinuumAction;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
*/
public class AddProjectToCheckoutQueueStub
extends AbstractContinuumAction
{
@SuppressWarnings( "unchecked" )
public void execute( Map context )
throws Exception
{
getLogger().info( "Executing add-project-to-checkout-queue (stub for testing) action." );
// check if scm credentials were set in context (CONTINUUM-2466)
assertEquals( AddProjectTest.SCM_USERNAME, CheckoutProjectContinuumAction.getScmUsername( context, null ) );
assertEquals( AddProjectTest.SCM_PASSWORD, CheckoutProjectContinuumAction.getScmPassword( context, null ) );
}
}
| 5,020 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/AddProjectTest.java | package org.apache.maven.continuum;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.AbstractAddProjectTest;
import org.apache.maven.continuum.builddefinition.BuildDefinitionService;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.continuum.project.builder.maven.MavenTwoContinuumProjectBuilder;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:olamy@apache.org">olamy</a>
* @since 12 juin 2008
*/
public class AddProjectTest
extends AbstractAddProjectTest
{
static final String SCM_USERNAME = "test";
static final String SCM_PASSWORD = ";password";
private Server server;
private String scmUrl;
@Before
public void setUp()
throws Exception
{
createLocalRepository();
server = startJettyServer();
int port = server.getConnectors()[0].getLocalPort();
scmUrl = "http://test:;password@localhost:" + port + "/projects/continuum/continuum-core/pom.xml";
}
@After
public void tearDown()
throws Exception
{
server.stop();
}
private Server startJettyServer()
throws Exception
{
Server server = new Server( 0 );
ResourceHandler handler = new ResourceHandler();
handler.setResourceBase( getTestFile( "src/test/resources" ).getAbsolutePath() );
HandlerList handlers = new HandlerList();
handlers.setHandlers( new Handler[] { handler, new DefaultHandler() } );
server.setHandler( handlers );
server.start();
return server;
}
@Test
public void testScmUserNamePasswordNotStoring()
throws Exception
{
DefaultContinuum continuum = (DefaultContinuum) lookup( Continuum.class );
ContinuumProjectBuildingResult result = continuum.executeAddProjectsFromMetadataActivity( scmUrl,
MavenTwoContinuumProjectBuilder.ID,
getDefaultProjectGroup().getId(),
false, true, false,
-1, false, false );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
// read the project from store
Project project = continuum.getProject( result.getProjects().get( 0 ).getId() );
assertNull( project.getScmUsername() );
assertNull( project.getScmPassword() );
assertTrue( project.isScmUseCache() );
}
@Test
public void testScmUserNamePasswordStoring()
throws Exception
{
DefaultContinuum continuum = (DefaultContinuum) lookup( Continuum.class );
ContinuumProjectBuildingResult result = continuum.executeAddProjectsFromMetadataActivity( scmUrl,
MavenTwoContinuumProjectBuilder.ID,
getDefaultProjectGroup().getId(),
false, false, false,
-1, false, false );
assertEquals( Collections.emptyList(), result.getErrors() );
assertEquals( 1, result.getProjects().size() );
// read the project from store
Project project = continuum.getProject( result.getProjects().get( 0 ).getId() );
assertEquals( SCM_USERNAME, project.getScmUsername() );
assertEquals( SCM_PASSWORD, project.getScmPassword() );
assertFalse( project.isScmUseCache() );
}
@Test
public void testAntProjectScmUserNamePasswordNotStoring()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
Project project = new Project();
project.setName( "Sample Ant Project" );
project.setVersion( "1.0" );
project.setScmUsername( SCM_USERNAME );
project.setScmPassword( SCM_PASSWORD );
project.setScmUrl( this.scmUrl );
project.setScmUseCache( true );
BuildDefinitionService bdService = lookup( BuildDefinitionService.class );
int projectId = continuum.addProject( project, ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR,
getDefaultProjectGroup().getId(),
bdService.getDefaultAntBuildDefinitionTemplate().getId() );
// read the project from store
Project retrievedProject = continuum.getProject( projectId );
assertNull( retrievedProject.getScmUsername() );
assertNull( retrievedProject.getScmPassword() );
assertTrue( retrievedProject.isScmUseCache() );
}
@Test
public void testAntProjectScmUserNamePasswordStoring()
throws Exception
{
Continuum continuum = lookup( Continuum.class );
Project project = new Project();
project.setName( "Sample Ant Project" );
project.setVersion( "1.0" );
project.setScmUsername( SCM_USERNAME );
project.setScmPassword( SCM_PASSWORD );
project.setScmUrl( scmUrl );
project.setScmUseCache( false );
BuildDefinitionService bdService = lookup( BuildDefinitionService.class );
int projectId = continuum.addProject( project, ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR,
getDefaultProjectGroup().getId(),
bdService.getDefaultAntBuildDefinitionTemplate().getId() );
// read the project from store
Project retrievedProject = continuum.getProject( projectId );
assertEquals( SCM_USERNAME, retrievedProject.getScmUsername() );
assertEquals( SCM_PASSWORD, retrievedProject.getScmPassword() );
assertFalse( retrievedProject.isScmUseCache() );
}
}
| 5,021 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/TestAction.java | package org.apache.maven.continuum;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.codehaus.plexus.action.AbstractAction;
import java.util.Map;
/**
* @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a>
*/
public class TestAction
extends AbstractAction
{
public void execute( Map context )
throws Exception
{
throw new ContinuumException( "TestAction exception." );
}
}
| 5,022 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/core/action/CleanWorkingDirectoryActionTest.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.io.IOUtils;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.utils.file.DefaultFileSystemManager;
import org.apache.continuum.utils.file.FileSystemManager;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests that the cleanup action works properly. This is a non-portable test, and needs a special setup to run.
* Specifically:
* * OOME test requires a small heap (-Xmx2m -Xms2m)
* * Link traversal tests require a system with "/bin/ln"
*
* @see org.apache.maven.continuum.core.action.CleanWorkingDirectoryAction
*/
public class CleanWorkingDirectoryActionTest
{
public static final String FILE_PREFIX = "cwdat";
private CleanWorkingDirectoryAction action;
private WorkingDirectoryService mockWorkingDirectoryService;
private FileSystemManager fsManager;
private ProjectDao mockProjectDao;
/**
* Builds and returns a directory levels deep with the specified number of directories and files at each level.
*
* @param root optional root of the tree, a temporary directory will be created otherwise.
* @param levels the depth of directories to build
* @param files the number of files to create in each directory
* @param dirs the number of directories to include in each directory
* @return the location of the root of the tree, should be root if it was specified
* @throws IOException
*/
private File createFileTree( File root, int levels, int files, int dirs )
throws IOException
{
// Create a root path if one isn't specified
root = root == null ? fsManager.createTempFile( FILE_PREFIX, "", null ) : root;
// Create the directory at that path
if ( !root.mkdir() )
{
throw new IOException( "Failed to create directory " + root );
}
// Create the files for this directory
for ( int i = 0; i < files; i++ )
{
File newFile = fsManager.createTempFile( FILE_PREFIX, "", root );
fsManager.writeFile( newFile, "" );
}
// Create the directories
if ( levels > 1 )
{
for ( int i = 0; i < dirs; i++ )
{
File newDir = fsManager.createTempFile( FILE_PREFIX, "", root );
createFileTree( newDir, levels - 1, files, dirs );
}
}
return root;
}
@Before
public void setUp()
throws NoSuchFieldException, IllegalAccessException
{
// Create mocks
mockWorkingDirectoryService = mock( WorkingDirectoryService.class );
mockProjectDao = mock( ProjectDao.class );
fsManager = new DefaultFileSystemManager();
action = new CleanWorkingDirectoryAction();
// Get the private fields and make them accessible
Field wdsField = action.getClass().getDeclaredField( "workingDirectoryService" );
Field pdField = action.getClass().getDeclaredField( "projectDao" );
Field fsMgrField = action.getClass().getDeclaredField( "fsManager" );
for ( Field f : new Field[] { wdsField, pdField } )
{
f.setAccessible( true );
}
// Inject the mocks as dependencies
wdsField.set( action, mockWorkingDirectoryService );
pdField.set( action, mockProjectDao );
fsMgrField.set( action, fsManager );
}
/**
* Tests that deleting large directories doesn't result in an OutOfMemoryError.
* Reported as CONTINUUM-2199.
*
* @throws Exception
*/
@Test
public void testOutOfMemory()
throws Exception
{
File deepTree = createFileTree( null, 10, 10, 2 );
Project p = new Project();
when( mockProjectDao.getProject( 0 ) ).thenReturn( p );
when( mockWorkingDirectoryService.getWorkingDirectory( p, null, new ArrayList<Project>() ) ).thenReturn(
deepTree );
action.execute( new HashMap() );
assertFalse( String.format( "%s should not exist after deletion", deepTree.getPath() ), deepTree.exists() );
}
private int numFiles( File f )
{
return f.listFiles().length;
}
/**
* Tests that cleanup doesn't traverse across symlinks.
*/
@Test
public void testSymlinkTraversal()
throws Exception
{
int size = 10;
File tree1 = createFileTree( null, 1, 10, 0 );
assertEquals( String.format( "%s should contain %s files", tree1, size ), size, numFiles( tree1 ) );
File tree2 = createFileTree( null, 1, 10, 0 );
assertEquals( String.format( "%s should contain %s files", tree2, size ), size, numFiles( tree2 ) );
File symlink = new File( tree1, "tree2soft" );
// Create a symbolic link to second tree in first tree
String[] symlinkCommand = { "/bin/ln", "-s", tree2.getPath(), symlink.getPath() };
Process p1 = Runtime.getRuntime().exec( symlinkCommand );
if ( p1.waitFor() != 0 )
{
System.err.println( "Failed to run command " + Arrays.toString( symlinkCommand ) );
IOUtils.copy( p1.getInputStream(), System.err );
}
assertTrue( String.format( "Symbolic link %s should have been created", symlink ), symlink.exists() );
assertEquals( size + 1, numFiles( tree1 ) );
Project p = new Project();
when( mockProjectDao.getProject( 0 ) ).thenReturn( p );
when( mockWorkingDirectoryService.getWorkingDirectory( p, null, new ArrayList<Project>() ) ).thenReturn(
tree1 );
action.execute( new HashMap() );
assertFalse( String.format( "%s should not exist after deletion", tree1.getPath() ), tree1.exists() );
assertTrue( String.format( "%s should exist after deletion", tree2 ), tree2.exists() );
assertEquals( String.format( "%s should have %s files", tree2, size ), size, numFiles( tree2 ) );
}
/**
* Tests that cleanup doesn't traverse across hard links.
*/
@Test
public void testHardlinkTraversal()
throws Exception
{
int size = 10;
final File tree1 = createFileTree( null, 1, 10, 0 );
assertEquals( String.format( "%s should contain %s files", tree1, size ), size, numFiles( tree1 ) );
final File tree2 = createFileTree( null, 1, 10, 0 );
assertEquals( String.format( "%s should contain %s files", tree2, size ), size, numFiles( tree2 ) );
final File hardlink = new File( tree1, "tree2hard" );
File hardLinkedFile = new File( tree2, tree2.list()[0] ); // Hardlinks can't be to directories
String[] hardlinkCommand = { "/bin/ln", hardLinkedFile.getPath(), hardlink.getPath() };
Process p2 = Runtime.getRuntime().exec( hardlinkCommand );
if ( p2.waitFor() != 0 )
{
System.err.println( "Failed to run command " + Arrays.toString( hardlinkCommand ) );
IOUtils.copy( p2.getInputStream(), System.err );
}
assertTrue( String.format( "Hard link %s should have been created", hardlink ), hardlink.exists() );
assertEquals( size + 1, numFiles( tree1 ) );
Project p = new Project();
when( mockProjectDao.getProject( 0 ) ).thenReturn( p );
when( mockWorkingDirectoryService.getWorkingDirectory( p, null, new ArrayList<Project>() ) ).thenReturn(
tree1 );
action.execute( new HashMap() );
assertFalse( String.format( "%s should not exist after deletion", tree1.getPath() ), tree1.exists() );
assertTrue( String.format( "%s should exist after deletion", tree2 ), tree2.exists() );
assertEquals( String.format( "%s should have %s files", tree2, size ), size, numFiles( tree2 ) );
}
}
| 5,023 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/core/action/CreateProjectsFromMetadataTest.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.continuum.project.builder.manager.ContinuumProjectBuilderManager;
import org.apache.maven.continuum.utils.ContinuumUrlValidator;
import org.apache.maven.settings.MavenSettingsBuilder;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.spring.PlexusInSpringTestCase;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.junit.Before;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.*;
public class CreateProjectsFromMetadataTest
{
private CreateProjectsFromMetadataAction action;
private ContinuumProjectBuildingResult result;
@Before
public void setUp()
throws Exception
{
result = new ContinuumProjectBuildingResult();
action = new CreateProjectsFromMetadataAction();
action.enableLogging( new ConsoleLogger( Logger.LEVEL_DEBUG, "" ) );
result = new ContinuumProjectBuildingResult();
ContinuumProjectBuilderManager projectBuilderManagerMock = mock( ContinuumProjectBuilderManager.class );
action.setProjectBuilderManager( projectBuilderManagerMock );
action.setUrlValidator( new ContinuumUrlValidator() );
ContinuumProjectBuilder projectBuilder = mock( ContinuumProjectBuilder.class );
when( projectBuilderManagerMock.getProjectBuilder( anyString() ) ).thenReturn( projectBuilder );
when( projectBuilder.buildProjectsFromMetadata( any( URL.class ), anyString(), anyString(), anyBoolean(),
any( BuildDefinitionTemplate.class ), anyBoolean(),
anyInt() ) ).thenReturn( result );
when( projectBuilder.getDefaultBuildDefinitionTemplate() ).thenReturn( getDefaultBuildDefinitionTemplate() );
}
private void invokeBuildSettings()
throws IOException, XmlPullParserException
{
MavenSettingsBuilder mavenSettingsBuilderMock = mock( MavenSettingsBuilder.class );
action.setMavenSettingsBuilder( mavenSettingsBuilderMock );
when( mavenSettingsBuilderMock.buildSettings() ).thenReturn( new Settings() );
}
private BuildDefinitionTemplate getDefaultBuildDefinitionTemplate()
throws Exception
{
BuildDefinition bd = new BuildDefinition();
bd.setDefaultForProject( true );
bd.setGoals( "clean install" );
bd.setArguments( "-B" );
bd.setBuildFile( "pom.xml" );
bd.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR );
BuildDefinitionTemplate bdt = new BuildDefinitionTemplate();
bdt.addBuildDefinition( bd );
return bdt;
}
@SuppressWarnings( "unchecked" )
public void testExecuteWithNonRecursiveMode()
throws Exception
{
invokeBuildSettings();
Map<String, Object> context = new HashMap<String, Object>();
CreateProjectsFromMetadataAction.setUrl( context,
"http://svn.apache.org/repos/asf/maven/continuum/trunk/pom.xml" );
CreateProjectsFromMetadataAction.setProjectBuilderId( context, "id" );
CreateProjectsFromMetadataAction.setLoadRecursiveProject( context, true );
context.put( CreateProjectsFromMetadataAction.KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY, false );
action.execute( context );
ContinuumProjectBuildingResult result = CreateProjectsFromMetadataAction.getProjectBuildingResult( context );
assertFalse(
"Should not have errors but had " + result.getErrorsAsString() + " (this test requires internet access)",
result.hasErrors() );
}
public void testExecuteWithRecursiveMode()
throws Exception
{
invokeBuildSettings();
Map<String, Object> context = new HashMap<String, Object>();
CreateProjectsFromMetadataAction.setUrl( context,
"http://svn.apache.org/repos/asf/maven/archiva/trunk/pom.xml" );
CreateProjectsFromMetadataAction.setProjectBuilderId( context, "id" );
CreateProjectsFromMetadataAction.setLoadRecursiveProject( context, false );
context.put( CreateProjectsFromMetadataAction.KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY, false );
action.execute( context );
ContinuumProjectBuildingResult result = CreateProjectsFromMetadataAction.getProjectBuildingResult( context );
assertFalse(
"Should not have errors but had " + result.getErrorsAsString() + " (this test requires internet access)",
result.hasErrors() );
}
public void testExecuteWithCheckoutProjectsInSingleDirectory()
throws Exception
{
Project project = new Project();
project.setGroupId( "org.apache.continuum" );
project.setArtifactId( "parent-project" );
project.setVersion( "1.0-SNAPSHOT" );
project.setId( 6 );
project.setName( "parent-project" );
project.setScmUrl( "scm:local:src/test-projects:flat-multi-module/parent-project" );
this.result.addProject( project );
project = new Project();
project.setGroupId( "org.apache.continuum" );
project.setArtifactId( "module-a" );
project.setVersion( "1.0-SNAPSHOT" );
project.setId( 7 );
project.setName( "module-a" );
project.setScmUrl( "scm:local:src/test-projects:flat-multi-module/module-a" );
this.result.addProject( project );
project = new Project();
project.setGroupId( "org.apache.continuum" );
project.setArtifactId( "module-b" );
project.setVersion( "1.0-SNAPSHOT" );
project.setId( 8 );
project.setName( "module-b" );
project.setScmUrl( "scm:local:src/test-projects:flat-multi-module/module-b" );
this.result.addProject( project );
// assert using scm url set in root!
Map<String, Object> context = new HashMap<String, Object>();
CreateProjectsFromMetadataAction.setUrl( context, "file://" + PlexusInSpringTestCase.getBasedir() +
"/src/test-projects/flat-multi-module/parent-project/pom.xml" );
CreateProjectsFromMetadataAction.setProjectBuilderId( context, "id" );
CreateProjectsFromMetadataAction.setLoadRecursiveProject( context, true );
context.put( CreateProjectsFromMetadataAction.KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY, true );
action.execute( context );
ContinuumProjectBuildingResult result = CreateProjectsFromMetadataAction.getProjectBuildingResult( context );
assertFalse(
"Should not have errors but had " + result.getErrorsAsString() + " (this test requires internet access)",
result.hasErrors() );
assertEquals( "Incorrect SCM Root Url for flat multi-module project.",
"scm:local:src/test-projects:flat-multi-module/", AbstractContinuumAction.getProjectScmRootUrl(
context, "" ) );
}
public void testExecuteFlatMultiModuleProjectThatStartsWithTheSameLetter()
throws Exception
{
invokeBuildSettings();
Project project = new Project();
project.setGroupId( "com.example.flat" );
project.setArtifactId( "flat-parent" );
project.setVersion( "1.0-SNAPSHOT" );
project.setId( 6 );
project.setName( "Flat Example" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf/continuum/sandbox/flat-example/flat-parent" );
this.result.addProject( project );
project = new Project();
project.setGroupId( "com.example.flat" );
project.setArtifactId( "flat-core" );
project.setVersion( "1.0-SNAPSHOT" );
project.setId( 7 );
project.setName( "flat-core" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf/continuum/sandbox/flat-example/flat-core" );
this.result.addProject( project );
project = new Project();
project.setGroupId( "com.example.flat" );
project.setArtifactId( "flat-webapp" );
project.setVersion( "1.0-SNAPSHOT" );
project.setId( 8 );
project.setName( "flat-webapp Maven Webapp" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf/continuum/sandbox/flat-example/flat-webapp" );
this.result.addProject( project );
Map<String, Object> context = new HashMap<String, Object>();
CreateProjectsFromMetadataAction.setUrl( context,
"http://svn.apache.org/repos/asf/continuum/sandbox/flat-example/flat-parent/pom.xml" );
CreateProjectsFromMetadataAction.setProjectBuilderId( context, "id" );
CreateProjectsFromMetadataAction.setLoadRecursiveProject( context, true );
context.put( CreateProjectsFromMetadataAction.KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY, false );
action.execute( context );
ContinuumProjectBuildingResult result = CreateProjectsFromMetadataAction.getProjectBuildingResult( context );
assertFalse(
"Should not have errors but had " + result.getErrorsAsString() + " (this test requires internet access)",
result.hasErrors() );
assertEquals( "Wrong scm root url created",
"scm:svn:http://svn.apache.org/repos/asf/continuum/sandbox/flat-example/",
AbstractContinuumAction.getProjectScmRootUrl( context, null ) );
}
}
| 5,024 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/notification/ContinuumNotificationDispatcherTest.java | package org.apache.maven.continuum.notification;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildResultDao;
import org.apache.maven.continuum.AbstractContinuumTest;
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.junit.Before;
import org.junit.Test;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class ContinuumNotificationDispatcherTest
extends AbstractContinuumTest
{
private BuildResultDao buildResultDao;
@Before
public void setUp()
throws Exception
{
buildResultDao = lookup( BuildResultDao.class );
}
@Test
public void testNotificationDispatcher()
throws Exception
{
ContinuumNotificationDispatcher notificationDispatcher = lookup( ContinuumNotificationDispatcher.class );
Project project = addProject( "Notification Dispatcher Test Project" );
project = getProjectDao().getProjectWithBuildDetails( project.getId() );
BuildResult build = new BuildResult();
build.setStartTime( System.currentTimeMillis() );
build.setState( ContinuumProjectState.BUILDING );
build.setTrigger( ContinuumProjectState.TRIGGER_SCHEDULED );
buildResultDao.addBuildResult( project, build );
build = buildResultDao.getBuildResult( build.getId() );
notificationDispatcher.buildComplete( project, null, build );
}
}
| 5,025 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/notification | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/notification/mail/MailContinuumNotifierTest.java | package org.apache.maven.continuum.notification.mail;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.notification.mail.MockJavaMailSender;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher;
import org.apache.maven.continuum.notification.MessageContext;
import org.apache.maven.continuum.notification.Notifier;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class MailContinuumNotifierTest
extends AbstractContinuumTest
{
protected static final Logger logger = LoggerFactory.getLogger( MailContinuumNotifierTest.class );
@Test
public void testSuccessfulBuild()
throws Exception
{
MailContinuumNotifier notifier = (MailContinuumNotifier) lookup( Notifier.class, "mail" );
String toOverride = "recipient@host.com";
notifier.setToOverride( toOverride );
ProjectGroup group = createStubProjectGroup( "foo.bar", "" );
BuildResultDao brDao = lookup( BuildResultDao.class );
Project project = addProject( "Test Project", group );
BuildResult br = makeBuild( ContinuumProjectState.FAILED );
brDao.addBuildResult( project, br );
br = makeBuild( ContinuumProjectState.OK );
brDao.addBuildResult( project, br );
br = makeBuild( ContinuumProjectState.FAILED );
brDao.addBuildResult( project, br );
BuildResult build = makeBuild( ContinuumProjectState.OK );
assertEquals( ContinuumProjectState.OK, build.getState() );
project.setState( build.getState() );
getProjectDao().updateProject( project );
BuildDefinition buildDef = new BuildDefinition();
buildDef.setType( "maven2" );
buildDef.setBuildFile( "pom.xml" );
buildDef.setGoals( "clean install" );
buildDef.setArguments( "" );
BuildDefinitionDao buildDefDao = (BuildDefinitionDao) lookup( BuildDefinitionDao.class );
buildDef = buildDefDao.addBuildDefinition( buildDef );
build.setBuildDefinition( buildDef );
assertEquals( ContinuumProjectState.OK, build.getState() );
brDao.addBuildResult( project, build );
build = brDao.getLatestBuildResultForProjectWithDetails( project.getId() );
assertEquals( ContinuumProjectState.OK, build.getState() );
MimeMessage mailMessage = sendNotificationAndGetMessage( project, build, buildDef, "lots out build output",
toOverride );
assertEquals( "[continuum] BUILD SUCCESSFUL: foo.bar Test Project", mailMessage.getSubject() );
String mailContent = dumpContent( mailMessage, "recipient@host.com" );
//CONTINUUM-1946
assertTrue( mailContent.indexOf( "Goals: clean install" ) > 0 );
}
@Test
public void testFailedBuild()
throws Exception
{
ProjectGroup group = createStubProjectGroup( "foo.bar", "" );
Project project = addProject( "Test Project", group );
BuildResult build = makeBuild( ContinuumProjectState.FAILED );
MimeMessage mailMessage = sendNotificationAndGetMessage( project, build, null, "output", null );
assertEquals( "[continuum] BUILD FAILURE: foo.bar Test Project", mailMessage.getSubject() );
dumpContent( mailMessage );
}
@Test
public void testErroneousBuild()
throws Exception
{
ProjectGroup group = createStubProjectGroup( "foo.bar", "" );
Project project = addProject( "Test Project", group );
BuildResult build = makeBuild( ContinuumProjectState.ERROR );
build.setError( "Big long error message" );
MimeMessage mailMessage = sendNotificationAndGetMessage( project, build, null, "lots of stack traces", null );
assertEquals( "[continuum] BUILD ERROR: foo.bar Test Project", mailMessage.getSubject() );
dumpContent( mailMessage );
}
private String dumpContent( MimeMessage mailMessage )
throws Exception
{
return dumpContent( mailMessage, null );
}
private String dumpContent( MimeMessage mailMessage, String toOverride )
throws Exception
{
Address[] tos = mailMessage.getRecipients( RecipientType.TO );
if ( toOverride != null )
{
assertEquals( toOverride, ( (InternetAddress) tos[0] ).getAddress() );
}
else
{
assertEquals( "foo@bar", ( (InternetAddress) tos[0] ).getAddress() );
}
assertTrue( "The template isn't loaded correctly.", ( (String) mailMessage.getContent() ).indexOf(
"#shellBuildResult()" ) < 0 );
assertTrue( "The template isn't loaded correctly.", ( (String) mailMessage.getContent() ).indexOf(
"Build statistics" ) > 0 );
String mailContent = (String) mailMessage.getContent();
logger.info( mailContent );
return mailContent;
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
private MimeMessage sendNotificationAndGetMessage( Project project, BuildResult build, BuildDefinition buildDef,
String buildOutput, String toOverride )
throws Exception
{
MessageContext context = new MessageContext();
context.setProject( project );
context.setBuildResult( build );
context.setBuildDefinition( buildDef );
ProjectNotifier projectNotifier = new ProjectNotifier();
projectNotifier.setType( "mail" );
Map<String, String> config = new HashMap<String, String>();
config.put( MailContinuumNotifier.ADDRESS_FIELD, "foo@bar" );
projectNotifier.setConfiguration( config );
List<ProjectNotifier> projectNotifiers = new ArrayList<ProjectNotifier>();
projectNotifiers.add( projectNotifier );
context.setNotifier( projectNotifiers );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
Notifier notifier = lookup( Notifier.class, "mail" );
( (MailContinuumNotifier) notifier ).setBuildHost( "foo.bar.com" );
notifier.sendMessage( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE, context );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
MockJavaMailSender mailSender = (MockJavaMailSender) lookup( JavaMailSender.class, "continuum" );
assertEquals( 1, mailSender.getReceivedEmails().size() );
List<MimeMessage> mails = mailSender.getReceivedEmails();
MimeMessage mailMessage = mails.get( 0 );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertEquals( "continuum@localhost", ( (InternetAddress) mailMessage.getFrom()[0] ).getAddress() );
assertEquals( "Continuum", ( (InternetAddress) mailMessage.getFrom()[0] ).getPersonal() );
Address[] tos = mailMessage.getRecipients( RecipientType.TO );
assertEquals( 1, tos.length );
assertEquals( toOverride == null ? "foo@bar" : toOverride, ( (InternetAddress) tos[0] ).getAddress() );
return mailMessage;
}
private BuildResult makeBuild( int state )
{
BuildResult build = new BuildResult();
build.setStartTime( System.currentTimeMillis() );
build.setEndTime( System.currentTimeMillis() + 1234567 );
build.setState( state );
build.setTrigger( ContinuumProjectState.TRIGGER_FORCED );
build.setExitCode( 10 );
return build;
}
}
| 5,026 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/notification | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/notification/mail/FormatterToolTest.java | package org.apache.maven.continuum.notification.mail;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class FormatterToolTest
{
@Test
public void testIntervalFormatting()
throws Exception
{
FormatterTool tool = new FormatterTool( null );
assertEquals( "10s", tool.formatInterval( 0, makeTime( 0, 0, 10 ) ) );
assertEquals( "1m 0s", tool.formatInterval( 0, makeTime( 0, 1, 0 ) ) );
assertEquals( "1m 10s", tool.formatInterval( 0, makeTime( 0, 1, 10 ) ) );
assertEquals( "1h 0m 0s", tool.formatInterval( 0, makeTime( 1, 0, 0 ) ) );
assertEquals( "1h 10m 0s", tool.formatInterval( 0, makeTime( 1, 10, 0 ) ) );
assertEquals( "1h 1m 10s", tool.formatInterval( 0, makeTime( 1, 1, 10 ) ) );
assertEquals( "8s", tool.formatInterval( 1112561981137L, 1112561990023L ) );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
private long makeTime( int hours, int minutes, int seconds )
{
return ( hours * 3600 + minutes * 60 + seconds ) * 1000;
}
}
| 5,027 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/initialization/DefaultContinuumInitializerTest.java | package org.apache.maven.continuum.initialization;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.DaoUtils;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.model.project.Schedule;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:olamy@codehaus.org">olamy</a>
* @since 4 juin 07
*/
public class DefaultContinuumInitializerTest
extends AbstractContinuumTest
{
@Before
public void setUp()
throws Exception
{
DaoUtils daoUtils = lookup( DaoUtils.class );
daoUtils.eraseDatabase();
ContinuumInitializer continuumInitializer = lookup( ContinuumInitializer.class, "default" );
continuumInitializer.initialize();
}
@Test
public void testDefaultSchedule()
throws Exception
{
Schedule schedule = getScheduleDao().getScheduleByName( ConfigurationService.DEFAULT_SCHEDULE_NAME );
assertNotNull( schedule );
}
}
| 5,028 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/project | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/project/builder/AbstractContinuumProjectBuilderTest.java | package org.apache.maven.continuum.project.builder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.io.FileUtils;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* Test for {@link AbstractContinuumProjectBuilder}
*
* @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a>
*/
public abstract class AbstractContinuumProjectBuilderTest
{
private ContinuumProjectBuilder builder;
private File importRoot;
@Before
public void setUp()
throws Exception
{
File tmpDir = new File( System.getProperty( "java.io.tmpdir" ) );
importRoot = File.createTempFile( getClass().getSimpleName(), "", tmpDir );
builder = new ContinuumProjectBuilder();
}
@After
public void tearDown()
throws IOException
{
if ( importRoot.exists() )
{
FileUtils.deleteDirectory( importRoot );
}
}
@Test
@Ignore( "requires a password protected resource under https" )
public void testCreateMetadataFileURLStringString()
throws Exception
{
URL url = new URL( "https://someurl/pom.xml" );
String username = "myusername";
String password = "mypassword";
builder.createMetadataFile( importRoot, url, username, password, new ContinuumProjectBuildingResult() );
}
private class ContinuumProjectBuilder
extends AbstractContinuumProjectBuilder
{
public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password )
throws ContinuumProjectBuilderException
{
return null;
}
public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password,
boolean recursiveProjects,
boolean checkoutInSingleDirectory )
throws ContinuumProjectBuilderException
{
return null;
}
public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password,
boolean recursiveProjects,
BuildDefinitionTemplate buildDefinitionTemplate,
boolean checkoutInSingleDirectory )
throws ContinuumProjectBuilderException
{
return null;
}
public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password,
boolean recursiveProjects,
BuildDefinitionTemplate buildDefinitionTemplate,
boolean checkoutInSingleDirectory,
int projectGroupId )
throws ContinuumProjectBuilderException
{
return null;
}
public BuildDefinitionTemplate getDefaultBuildDefinitionTemplate()
throws ContinuumProjectBuilderException
{
return null;
}
}
}
| 5,029 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/project/builder | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/project/builder/maven/MavenOneContinuumProjectBuilderTest.java | package org.apache.maven.continuum.project.builder.maven;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.builddefinition.BuildDefinitionService;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class MavenOneContinuumProjectBuilderTest
extends AbstractContinuumTest
{
@Test
public void testBuildingAProjectFromMetadataWithACompleteMaven1Pom()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenOneContinuumProjectBuilder.ID );
BuildDefinition bd = new BuildDefinition();
bd.setDefaultForProject( true );
bd.setGoals( "clean:clean jar:install" );
bd.setBuildFile( "project.xml" );
bd.setType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR );
bd.setTemplate( true );
BuildDefinitionService service = lookup( BuildDefinitionService.class );
BuildDefinitionTemplate bdt = new BuildDefinitionTemplate();
bdt.setName( "maven1" );
bd = service.addBuildDefinition( bd );
bdt = service.addBuildDefinitionTemplate( bdt );
bdt = service.addBuildDefinitionInTemplate( bdt, bd, false );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( getTestFile(
"src/test/resources/projects/maven-1.pom.xml" ).toURL(), null, null, false, bdt, false );
assertOnResult( result );
}
@Test
public void testBuildingAProjectFromMetadataWithACompleteMaven1PomWithDefaultBuildDef()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenOneContinuumProjectBuilder.ID );
BuildDefinitionService service = lookup( BuildDefinitionService.class );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( getTestFile(
"src/test/resources/projects/maven-1.pom.xml" ).toURL(),
null, null, false,
service.getDefaultMavenOneBuildDefinitionTemplate(),
false );
assertOnResult( result );
}
protected void assertOnResult( ContinuumProjectBuildingResult result )
{
assertNotNull( result.getErrors() );
assertNotNull( result.getProjects() );
for ( String error : result.getErrors() )
{
System.err.println( error );
}
assertEquals( "result.warning.length", 0, result.getErrors().size() );
assertEquals( "result.projects.length", 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
assertNotNull( project );
assertEquals( "Maven", project.getName() );
assertEquals( "Java Project Management Tools", project.getDescription() );
assertEquals( "scm:svn:http://svn.apache.org/repos/asf:maven/maven-1/core/trunk/", project.getScmUrl() );
ProjectNotifier notifier = project.getNotifiers().get( 0 );
assertEquals( "mail", notifier.getType() );
assertEquals( "dev@maven.apache.org", notifier.getConfiguration().get( "address" ) );
assertEquals( "1.1-SNAPSHOT", project.getVersion() );
}
}
| 5,030 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/project/builder | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/project/builder/maven/MavenTwoContinuumProjectBuilderTest.java | package org.apache.maven.continuum.project.builder.maven;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.builddefinition.BuildDefinitionService;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectDependency;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.codehaus.plexus.util.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class MavenTwoContinuumProjectBuilderTest
extends AbstractContinuumTest
{
private static final Logger logger = LoggerFactory.getLogger( MavenTwoContinuumProjectBuilderTest.class );
@Test
public void testGetEmailAddressWhenTypeIsSetToEmail()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
File pom = getTestFile( "src/test/repository/maven-builder-helper-1.xml" );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( pom.toURL(), null, null );
assertNotNull( result.getErrors() );
assertEquals( 0, result.getErrors().size() );
assertNotNull( result.getProjects() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
assertNotNull( project );
assertNotNull( project.getNotifiers() );
assertEquals( 1, project.getNotifiers().size() );
ProjectNotifier notifier = project.getNotifiers().get( 0 );
assertEquals( "mail", notifier.getType() );
assertEquals( "foo@bar", notifier.getConfiguration().get( "address" ) );
ProjectGroup pg = result.getProjectGroups().get( 0 );
assertNotNull( pg );
assertNotNull( pg.getNotifiers() );
assertEquals( 0, pg.getNotifiers().size() );
}
@Test
public void testGetEmailAddressWhenTypeIsntSet()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
File pom = getTestFile( "src/test/repository/maven-builder-helper-2.xml" );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( pom.toURL(), null, null );
assertNotNull( result.getErrors() );
assertEquals( 0, result.getErrors().size() );
assertNotNull( result.getProjects() );
assertEquals( 1, result.getProjects().size() );
Project project = result.getProjects().get( 0 );
assertNotNull( project );
assertNotNull( project.getNotifiers() );
assertEquals( 1, project.getNotifiers().size() );
ProjectNotifier notifier = project.getNotifiers().get( 0 );
assertEquals( "mail", notifier.getType() );
assertEquals( "foo@bar", notifier.getConfiguration().get( "address" ) );
ProjectGroup pg = result.getProjectGroups().get( 0 );
assertNotNull( pg );
assertNotNull( pg.getNotifiers() );
assertEquals( 0, pg.getNotifiers().size() );
}
@Test
public void testGetScmUrlWithParams()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
File pom = getTestFile( "src/test/repository/maven-builder-helper-3.xml" );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( pom.toURL(), null, null );
assertNotNull( result.getErrors() );
assertEquals( 0, result.getErrors().size() );
assertNotNull( result.getProjects() );
assertEquals( 1, result.getProjects().size() );
ProjectGroup pg = result.getProjectGroups().get( 0 );
assertNotNull( pg );
String username = System.getProperty( "user.name" );
String scmUrl = "scm:cvs:ext:${user.name}@company.org:/home/company/cvs:project/foo";
Project project = result.getProjects().get( 0 );
scmUrl = StringUtils.replace( scmUrl, "${user.name}", username );
assertEquals( scmUrl, project.getScmUrl() );
}
@Test
public void testCreateProjectsWithModules()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
URL url = getClass().getClassLoader().getResource( "projects/continuum/pom.xml" );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( url, null, null );
assertNotNull( result );
// ----------------------------------------------------------------------
// Assert the warnings
// ----------------------------------------------------------------------
assertNotNull( result.getErrors() );
assertEquals( 1, result.getErrors().size() );
assertEquals( ContinuumProjectBuildingResult.ERROR_POM_NOT_FOUND, result.getErrors().get( 0 ) );
// ----------------------------------------------------------------------
// Assert the project group built
// ----------------------------------------------------------------------
assertNotNull( result.getProjectGroups() );
assertEquals( 1, result.getProjectGroups().size() );
ProjectGroup projectGroup = result.getProjectGroups().iterator().next();
assertEquals( "projectGroup.groupId", "org.apache.maven.continuum", projectGroup.getGroupId() );
assertEquals( "projectGroup.name", "Continuum Parent Project", projectGroup.getName() );
assertEquals( "projectGroup.description", "Continuum Project Description", projectGroup.getDescription() );
// ----------------------------------------------------------------------
// Assert the projects built
// ----------------------------------------------------------------------
assertNotNull( result.getProjects() );
assertEquals( 9, result.getProjects().size() );
Map<String, Project> projects = new HashMap<String, Project>();
for ( Project project : result.getProjects() )
{
assertNotNull( project.getName() );
assertNotNull( project.getDescription() );
projects.put( project.getName(), project );
}
assertMavenTwoProject( "Continuum Core", projects );
assertMavenTwoProject( "Continuum Model", projects );
assertMavenTwoProject( "Continuum Plexus Application", projects );
assertScmUrl( "Continuum Web", projects,
"scm:svn:http://svn.apache.org/repos/asf/maven/continuum/tags/continuum-1.0.3/continuum-web" );
//directoryName != artifactId for this project
assertScmUrl( "Continuum XMLRPC Interface", projects,
"scm:svn:http://svn.apache.org/repos/asf/maven/continuum/tags/continuum-1.0.3/continuum-xmlrpc" );
assertMavenTwoProject( "Continuum Notifiers", projects );
assertMavenTwoProject( "Continuum IRC Notifier", projects );
assertMavenTwoProject( "Continuum Jabber Notifier", projects );
assertEquals( "continuum-parent-notifiers", ( projects.get(
"Continuum IRC Notifier" ) ).getParent().getArtifactId() );
assertEquals( "continuum-parent-notifiers", ( projects.get(
"Continuum Jabber Notifier" ) ).getParent().getArtifactId() );
assertDependency( "Continuum Model", "Continuum Web", projects );
}
@Test
public void testCreateProjectsWithModuleswithParentPomIsntPomXml()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
URL url = getClass().getClassLoader().getResource( "projects/continuum/pom_ci.xml" );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( url, null, null );
assertNotNull( result );
// ----------------------------------------------------------------------
// Assert the warnings
// ----------------------------------------------------------------------
assertNotNull( result.getErrors() );
assertEquals( 1, result.getErrors().size() );
assertEquals( ContinuumProjectBuildingResult.ERROR_POM_NOT_FOUND, result.getErrors().get( 0 ) );
// ----------------------------------------------------------------------
// Assert the project group built
// ----------------------------------------------------------------------
assertNotNull( result.getProjectGroups() );
assertEquals( 1, result.getProjectGroups().size() );
ProjectGroup projectGroup = result.getProjectGroups().iterator().next();
assertEquals( "projectGroup.groupId", "org.apache.maven.continuum", projectGroup.getGroupId() );
assertEquals( "projectGroup.name", "Continuum Parent Project", projectGroup.getName() );
assertEquals( "projectGroup.description", "Continuum Project Description", projectGroup.getDescription() );
// assertEquals( "projectGroup.url", "http://cvs.continuum.codehaus.org/", projectGroup.getUrl() );
// ----------------------------------------------------------------------
// Assert the projects built
// ----------------------------------------------------------------------
assertNotNull( result.getProjects() );
assertEquals( 9, result.getProjects().size() );
Map<String, Project> projects = new HashMap<String, Project>();
for ( Project project : result.getProjects() )
{
assertNotNull( project.getName() );
projects.put( project.getName(), project );
}
assertMavenTwoProject( "Continuum Core", projects );
assertMavenTwoProject( "Continuum Model", projects );
assertMavenTwoProject( "Continuum Plexus Application", projects );
assertScmUrl( "Continuum Web", projects,
"scm:svn:http://svn.apache.org/repos/asf/maven/continuum/tags/continuum-1.0.3/continuum-web" );
//directoryName != artifactId for this project
assertScmUrl( "Continuum XMLRPC Interface", projects,
"scm:svn:http://svn.apache.org/repos/asf/maven/continuum/tags/continuum-1.0.3/continuum-xmlrpc" );
assertMavenTwoProject( "Continuum Notifiers", projects );
assertMavenTwoProject( "Continuum IRC Notifier", projects );
assertMavenTwoProject( "Continuum Jabber Notifier", projects );
assertEquals( "continuum-parent-notifiers", ( projects.get(
"Continuum IRC Notifier" ) ).getParent().getArtifactId() );
assertEquals( "continuum-parent-notifiers", ( projects.get(
"Continuum Jabber Notifier" ) ).getParent().getArtifactId() );
assertDependency( "Continuum Model", "Continuum Web", projects );
}
@Test
public void testCreateProjectWithoutModules()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
URL url = getClass().getClassLoader().getResource( "projects/continuum/continuum-core/pom.xml" );
BuildDefinition bd = new BuildDefinition();
bd.setDefaultForProject( true );
bd.setGoals( "clean test-compile" );
bd.setArguments( "-N" );
bd.setBuildFile( "pom.xml" );
bd.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR );
BuildDefinitionService service = lookup( BuildDefinitionService.class );
bd = service.addBuildDefinition( bd );
BuildDefinitionTemplate bdt = new BuildDefinitionTemplate();
bdt.setName( "maven2" );
bdt = service.addBuildDefinitionTemplate( bdt );
bdt = service.addBuildDefinitionInTemplate( bdt, bd, false );
assertEquals( 5, service.getAllBuildDefinitionTemplate().size() );
logger.debug( "templates number " + service.getAllBuildDefinitionTemplate().size() );
logger.debug( "projectGroups number " + getProjectGroupDao().getAllProjectGroups().size() );
int all = service.getAllBuildDefinitions().size();
ContinuumProjectBuildingResult result;
result = projectBuilder.buildProjectsFromMetadata( url, null, null, false, bdt, false );
assertFalse( result.hasErrors() );
assertEquals( 5, service.getAllBuildDefinitionTemplate().size() );
assertEquals( all + 1, service.getAllBuildDefinitions().size() );
assertNotNull( result );
assertNotNull( result.getErrors() );
assertEquals( 0, result.getErrors().size() );
assertNotNull( result.getProjectGroups() );
assertEquals( 1, result.getProjectGroups().size() );
ProjectGroup projectGroup = result.getProjectGroups().get( 0 );
assertEquals( "projectGroup.groupId", "org.apache.maven.continuum", projectGroup.getGroupId() );
assertEquals( "projectGroup.name", "Continuum Core", projectGroup.getName() );
assertNotNull( result.getProjects() );
assertEquals( 1, result.getProjects().size() );
assertNotNull( projectGroup.getProjects() );
assertEquals( 0, projectGroup.getProjects().size() );
}
@Test
public void testCreateProjectWithFlatStructure()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
URL url = getTestFile( "/src/test-projects/flat-multi-module/parent-project/pom.xml" ).toURL();
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( url, null, null, true, true );
Project rootProject = result.getRootProject();
assertEquals( "Incorrect root project", "parent-project", rootProject.getArtifactId() );
List<Project> projects = result.getProjects();
for ( Project project : projects )
{
if ( project.getName().equals( "parent-project" ) )
{
assertEquals( "Incorrect scm url for parent-project",
"scm:local:src/test-projects:flat-multi-module/parent-project", project.getScmUrl() );
}
else if ( project.getName().equals( "module-a" ) )
{
assertEquals( "Incorrect scm url for parent-project",
"scm:local:src/test-projects:flat-multi-module/module-a", project.getScmUrl() );
}
else if ( project.getName().equals( "module-b" ) )
{
assertEquals( "Incorrect scm url for parent-project",
"scm:local:src/test-projects:flat-multi-module/module-b", project.getScmUrl() );
}
else if ( project.getName().equals( "module-d" ) )
{
assertEquals( "Incorrect scm url for module-d",
"scm:local:src/test-projects:flat-multi-module/module-c/module-d", project.getScmUrl() );
}
else
{
fail( "Unknown project: " + project.getName() );
}
}
}
// CONTINUUM-2563
@Test
public void testCreateMultiModuleProjectLoadRecursiveProjectsIsFalse()
throws Exception
{
ContinuumProjectBuilder projectBuilder = lookup( ContinuumProjectBuilder.class,
MavenTwoContinuumProjectBuilder.ID );
URL url = getClass().getClassLoader().getResource( "projects/continuum/pom.xml" );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( url, null, null, false,
false );
assertNotNull( result );
// ----------------------------------------------------------------------
// Assert the project group built
// ----------------------------------------------------------------------
assertNotNull( result.getProjectGroups() );
assertEquals( 1, result.getProjectGroups().size() );
ProjectGroup projectGroup = result.getProjectGroups().iterator().next();
assertEquals( "projectGroup.groupId", "org.apache.maven.continuum", projectGroup.getGroupId() );
assertEquals( "projectGroup.name", "Continuum Parent Project", projectGroup.getName() );
assertEquals( "projectGroup.description", "Continuum Project Description", projectGroup.getDescription() );
// ----------------------------------------------------------------------
// Assert the projects built
// ----------------------------------------------------------------------
assertNotNull( result.getProjects() );
assertEquals( 1, result.getProjects().size() );
Map<String, Project> projects = new HashMap<String, Project>();
Project project = result.getProjects().iterator().next();
assertNotNull( project.getName() );
assertNotNull( project.getDescription() );
projects.put( project.getName(), project );
assertMavenTwoProject( "Continuum Parent Project", projects );
// assert the default project build definition
List<BuildDefinition> buildDefs = project.getBuildDefinitions();
assertEquals( 0, buildDefs.size() );
// assert the default project build definition
buildDefs = projectGroup.getBuildDefinitions();
assertEquals( 1, buildDefs.size() );
for ( BuildDefinition buildDef : buildDefs )
{
if ( buildDef.isDefaultForProject() )
{
assertEquals( "--batch-mode", buildDef.getArguments() );
assertEquals( "clean install", buildDef.getGoals() );
assertEquals( "pom.xml", buildDef.getBuildFile() );
}
}
}
private void assertDependency( String dep, String proj, Map<String, Project> projects )
{
Project p = projects.get( proj );
Project dependency = projects.get( dep );
assertNotNull( p );
assertNotNull( dependency );
assertNotNull( p.getDependencies() );
for ( ProjectDependency pd : (List<ProjectDependency>) p.getDependencies() )
{
if ( pd.getArtifactId().equals( dependency.getArtifactId() ) &&
pd.getGroupId().equals( dependency.getGroupId() ) && pd.getVersion().equals( dependency.getVersion() ) )
{
return;
}
}
assertFalse( true );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
private Project getProject( String name, Map<String, Project> projects )
{
return projects.get( name );
}
private void assertMavenTwoProject( String name, Map<String, Project> projects )
{
Project project = getProject( name, projects );
assertNotNull( project );
assertEquals( name, project.getName() );
String scmUrl = "scm:svn:http://svn.apache.org/repos/asf/maven/continuum/";
assertTrue( project.getScmUrl().startsWith( scmUrl ) );
}
private void assertScmUrl( String name, Map<String, Project> projects, String scmUrl )
{
assertMavenTwoProject( name, projects );
Project project = getProject( name, projects );
assertEquals( scmUrl, project.getScmUrl() );
}
}
| 5,031 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/ContinuumBuildExecutorTest.java | package org.apache.maven.continuum.execution;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.utils.shell.ExecutionResult;
import org.apache.continuum.utils.shell.ShellCommandHelper;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.configuration.DefaultConfigurationService;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.utils.ChrootJailWorkingDirectoryService;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class ContinuumBuildExecutorTest
{
protected AbstractBuildExecutor executor = new BuildExecutorStub();
private String toSystemPath( String path )
{
if ( File.separator.equals( "\\" ) )
{
String newPath = path.replaceAll( "/", "\\" + File.separator );
return newPath.replaceAll( "\\\\bin\\\\sh", "/bin/sh" );
}
return path;
}
@Test
public void testExecuteShellCommand()
throws Exception
{
File chrootJailFile = new File( toSystemPath( "/home" ) );
File workingDirectory = new File( toSystemPath( "/dir1/dir2/workingdir" ) );
ShellCommandHelper helper = mock( ShellCommandHelper.class );
ConfigurationService configurationService = mock( DefaultConfigurationService.class );
when( configurationService.getWorkingDirectory() ).thenReturn( workingDirectory );
ChrootJailWorkingDirectoryService directoryService = new ChrootJailWorkingDirectoryService();
directoryService.setConfigurationService( configurationService );
directoryService.setChrootJailDirectory( chrootJailFile );
executor.setChrootJailDirectory( chrootJailFile );
executor.setShellCommandHelper( helper );
executor.setWorkingDirectoryService( directoryService );
//executor.enableLogging( new ConsoleLogger( Logger.LEVEL_DEBUG, "" ) );
Project project = new Project();
project.setId( 7 );
project.setGroupId( "xx" );
ProjectGroup projectGroup = new ProjectGroup();
projectGroup.setGroupId( project.getGroupId() );
project.setProjectGroup( projectGroup );
assertEquals( toSystemPath(
chrootJailFile.getPath() + "/" + project.getGroupId() + workingDirectory.getPath() + "/" +
project.getId() ), directoryService.getWorkingDirectory( project ).getPath() );
String executable = "mvn";
String arguments = "-o clean install";
File output = new File( "target/tmp" );
Map<String, String> environments = new HashMap<String, String>();
String cmd =
"chroot /home/xx " + " /bin/sh -c 'cd /dir1/dir2/workingdir/" + project.getId() + " && " + executable +
" " + arguments + "'";
ExecutionResult expectedResult = new ExecutionResult( 0 );
when( helper.executeShellCommand( chrootJailFile, "sudo", toSystemPath( cmd ), output, project.getId(),
environments ) ).thenReturn( expectedResult );
ContinuumBuildExecutionResult result =
executor.executeShellCommand( project, executable, arguments, output, environments,
null, null );
assertEquals( 0, result.getExitCode() );
verify( helper ).executeShellCommand( chrootJailFile, "sudo", toSystemPath( cmd ), output, project.getId(),
environments );
}
class BuildExecutorStub
extends AbstractBuildExecutor
{
protected BuildExecutorStub()
{
super( "stub", true );
}
protected String findExecutable( String executable, String defaultExecutable, boolean resolveExecutable,
File workingDirectory )
{
return executable;
}
@Override
protected Map<String, String> getEnvironments( BuildDefinition buildDefinition )
{
// TODO Auto-generated method stub
return null;
}
public ContinuumBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput,
List<Project> projectsWithCommonScmRoot, String projectScmRootUrl )
throws ContinuumBuildExecutorException
{
// TODO Auto-generated method stub
return null;
}
public void updateProjectFromCheckOut( File workingDirectory, Project project, BuildDefinition buildDefinition,
ScmResult scmResult )
throws ContinuumBuildExecutorException
{
// TODO Auto-generated method stub
}
}
}
| 5,032 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/maven/m1/MavenOneBuildExecutorTest.java | package org.apache.maven.continuum.execution.maven.m1;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class MavenOneBuildExecutorTest
extends AbstractContinuumTest
{
private File checkOut;
private MavenOneBuildExecutor executor;
@Before
public void setUp()
throws Exception
{
BuildExecutorManager builderManager = lookup( BuildExecutorManager.class );
executor = (MavenOneBuildExecutor) builderManager.getBuildExecutor( MavenOneBuildExecutor.ID );
// ----------------------------------------------------------------------
// Make a checkout
// ----------------------------------------------------------------------
checkOut = getTestFile( "target/test-checkout" );
if ( !checkOut.exists() )
{
assertTrue( checkOut.mkdirs() );
}
getFileSystemManager().wipeDir( checkOut );
}
@Test
public void testUpdatingAProjectFromScmWithAExistingProjectAndAEmptyMaven1Pom()
throws Exception
{
getFileSystemManager().writeFile( new File( checkOut, "project.xml" ), "<project/>" );
// ----------------------------------------------------------------------
// Make the "existing" project
// ----------------------------------------------------------------------
Project project = new Project();
project.setName( "Maven" );
project.setGroupId( "org.apache.maven" );
project.setArtifactId( "maven" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf:maven/maven-1/core/trunk/" );
ProjectNotifier notifier = new ProjectNotifier();
Properties props = new Properties();
props.put( "address", "dev@maven.apache.org" );
notifier.setConfiguration( props );
notifier.setFrom( ProjectNotifier.FROM_USER );
List<ProjectNotifier> notifiers = new ArrayList<ProjectNotifier>();
notifiers.add( notifier );
project.setNotifiers( notifiers );
project.setVersion( "1.1-SNAPSHOT" );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertNotNull( project );
assertEquals( "Maven", project.getName() );
assertEquals( "scm:svn:http://svn.apache.org/repos/asf:maven/maven-1/core/trunk/", project.getScmUrl() );
ProjectNotifier actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "dev@maven.apache.org", actualNotifier.getConfiguration().get( "address" ) );
assertEquals( "1.1-SNAPSHOT", project.getVersion() );
}
@Test
public void testUpdatingAProjectWithNagEMailAddress()
throws Exception
{
getFileSystemManager().writeFile( new File( checkOut, "project.xml" ),
"<project><build><nagEmailAddress>myuser@myhost.org</nagEmailAddress></build></project>" );
// ----------------------------------------------------------------------
// Make the "existing" project
// ----------------------------------------------------------------------
Project project = new Project();
project.setName( "Maven" );
project.setGroupId( "org.apache.maven" );
project.setArtifactId( "maven" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf:maven/maven-1/core/trunk/" );
project.setVersion( "1.1-SNAPSHOT" );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertNotNull( project );
assertEquals( "Maven", project.getName() );
assertEquals( 1, project.getNotifiers().size() );
ProjectNotifier actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "myuser@myhost.org", actualNotifier.getConfiguration().get( "address" ) );
// ----------------------------------------------------------------------
// Updating a new time to prevent duplicated notifiers
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertEquals( 1, project.getNotifiers().size() );
actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "myuser@myhost.org", actualNotifier.getConfiguration().get( "address" ) );
}
@Test
public void testUpdatingAProjectWithNagEMailAddressAndOneNotifier()
throws Exception
{
getFileSystemManager().writeFile( new File( checkOut, "project.xml" ),
"<project><build><nagEmailAddress>myuser@myhost.org</nagEmailAddress></build></project>" );
// ----------------------------------------------------------------------
// Make the "existing" project
// ----------------------------------------------------------------------
Project project = new Project();
project.setName( "Maven" );
project.setGroupId( "org.apache.maven" );
project.setArtifactId( "maven" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf:maven/maven-1/core/trunk/" );
ProjectNotifier notifier = new ProjectNotifier();
Properties props = new Properties();
props.put( "address", "dev@maven.apache.org" );
notifier.setConfiguration( props );
notifier.setFrom( ProjectNotifier.FROM_USER );
List<ProjectNotifier> notifiers = new ArrayList<ProjectNotifier>();
notifiers.add( notifier );
project.setNotifiers( notifiers );
project.setVersion( "1.1-SNAPSHOT" );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertNotNull( project );
assertEquals( "Maven", project.getName() );
assertEquals( 2, project.getNotifiers().size() );
ProjectNotifier actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "myuser@myhost.org", actualNotifier.getConfiguration().get( "address" ) );
actualNotifier = (ProjectNotifier) project.getNotifiers().get( 1 );
assertEquals( "dev@maven.apache.org", actualNotifier.getConfiguration().get( "address" ) );
// ----------------------------------------------------------------------
// Updating a new time to prevent duplicated notifiers
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertEquals( 2, project.getNotifiers().size() );
actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "myuser@myhost.org", actualNotifier.getConfiguration().get( "address" ) );
actualNotifier = (ProjectNotifier) project.getNotifiers().get( 1 );
assertEquals( "dev@maven.apache.org", actualNotifier.getConfiguration().get( "address" ) );
}
@Test
public void testUpdatingAProjectWithOneNotifier()
throws Exception
{
getFileSystemManager().writeFile( new File( checkOut, "project.xml" ), "<project/>" );
// ----------------------------------------------------------------------
// Make the "existing" project
// ----------------------------------------------------------------------
Project project = new Project();
project.setName( "Maven" );
project.setGroupId( "org.apache.maven" );
project.setArtifactId( "maven" );
project.setScmUrl( "scm:svn:http://svn.apache.org/repos/asf:maven/maven-1/core/trunk/" );
ProjectNotifier notifier = new ProjectNotifier();
Properties props = new Properties();
props.put( "address", "dev@maven.apache.org" );
notifier.setConfiguration( props );
notifier.setFrom( ProjectNotifier.FROM_USER );
List<ProjectNotifier> notifiers = new ArrayList<ProjectNotifier>();
notifiers.add( notifier );
project.setNotifiers( notifiers );
project.setVersion( "1.1-SNAPSHOT" );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertNotNull( project );
assertEquals( "Maven", project.getName() );
assertEquals( 1, project.getNotifiers().size() );
ProjectNotifier actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "dev@maven.apache.org", actualNotifier.getConfiguration().get( "address" ) );
// ----------------------------------------------------------------------
// Updating a new time to prevent duplicated notifiers
// ----------------------------------------------------------------------
executor.updateProjectFromCheckOut( checkOut, project, null, null );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
assertEquals( 1, project.getNotifiers().size() );
actualNotifier = (ProjectNotifier) project.getNotifiers().get( 0 );
assertEquals( "dev@maven.apache.org", actualNotifier.getConfiguration().get( "address" ) );
}
}
| 5,033 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/maven/m2/TestMavenBuilderHelper.java | package org.apache.maven.continuum.execution.maven.m2;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:olamy@apache.org">olamy</a>
* @since 6 juin 2008
*/
public class TestMavenBuilderHelper
extends AbstractContinuumTest
{
private static final Logger log = LoggerFactory.getLogger( TestMavenBuilderHelper.class );
@Test
public void testGetMavenProject()
throws Exception
{
MavenBuilderHelper mavenBuilderHelper = lookup( MavenBuilderHelper.class, "default" );
ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult();
File file = new File( getBasedir(), "src/test-poms/pom.xml" );
MavenProject project = mavenBuilderHelper.getMavenProject( result, file );
assertNotNull( project );
assertEquals( "plexus", project.getGroupId() );
assertEquals( "continuum-project2", project.getArtifactId() );
assertEquals( "This is a sample pom for test purposes", project.getDescription() );
assertNotNull( project.getScm() );
assertTrue( project.getDependencies().isEmpty() );
assertTrue( result.getErrors().isEmpty() );
}
@Test
public void testGetMavenProjectMissingDeps()
throws Exception
{
MavenBuilderHelper mavenBuilderHelper = lookup( MavenBuilderHelper.class, "default" );
ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult();
File file = new File( getBasedir(), "src/test-poms/pom-unknown-dependency.xml" );
mavenBuilderHelper.getMavenProject( result, file );
assertFalse( result.getErrors().isEmpty() );
String errorsAsString = result.getErrorsAsString();
assertFalse( StringUtils.isEmpty( errorsAsString ) );
log.info( "errorAsString " + errorsAsString );
assertTrue( errorsAsString.contains( "ghd:non-exists:pom:2.6.267676-beta-754-alpha-95" ) );
log.info( "errors " + result.getErrors() );
}
}
| 5,034 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/maven | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/maven/m2/MavenTwoBuildExecutorTest.java | package org.apache.maven.continuum.execution.maven.m2;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.execution.ContinuumBuildExecutor;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ChangeFile;
import org.apache.maven.continuum.model.scm.ChangeSet;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author olamy
* @since 1.2.3
*/
public class MavenTwoBuildExecutorTest
extends AbstractContinuumTest
{
@Override
protected String getSpringConfigLocation()
{
return "applicationContextSlf4jPlexusLogger.xml";
}
@Test
public void testShouldNotBuildNonRecursive()
throws Exception
{
ContinuumBuildExecutor executor = lookup( ContinuumBuildExecutor.class, "maven2" );
BuildDefinition buildDefinition = new BuildDefinition();
buildDefinition.setArguments( "-N" );
Project continuumProject = new Project()
{
{
setVersion( "1.0.3" );
}
};
assertFalse( executor.shouldBuild( new ArrayList<ChangeSet>(), continuumProject, new File(
"target/test-classes/projects/continuum" ), buildDefinition ) );
}
@Test
public void testShouldNotBuildNonRecursiveChangeInAModule()
throws Exception
{
ContinuumBuildExecutor executor = lookup( ContinuumBuildExecutor.class, "maven2" );
BuildDefinition buildDefinition = new BuildDefinition();
buildDefinition.setArguments( "-N -Dfoo=bar" );
Project continuumProject = new Project()
{
{
setVersion( "1.0.3" );
}
};
final ChangeFile changeFile = new ChangeFile();
changeFile.setName( "continuum-notifiers/pom.xml" );
ChangeSet changeSet = new ChangeSet()
{
{
addFile( changeFile );
}
};
List<ChangeSet> changeSets = new ArrayList<ChangeSet>();
changeSets.add( changeSet );
assertFalse( executor.shouldBuild( changeSets, continuumProject, new File(
"target/test-classes/projects/continuum" ), buildDefinition ) );
}
@Test
public void testShouldBuildRecursiveChangeInAModule()
throws Exception
{
ContinuumBuildExecutor executor = lookup( ContinuumBuildExecutor.class, "maven2" );
BuildDefinition buildDefinition = new BuildDefinition();
buildDefinition.setArguments( "-Dfoo=bar" );
Project continuumProject = new Project()
{
{
setVersion( "1.0.3" );
}
};
final ChangeFile changeFile = new ChangeFile();
changeFile.setName( "continuum-notifiers/pom.xml" );
ChangeSet changeSet = new ChangeSet()
{
{
addFile( changeFile );
}
};
List<ChangeSet> changeSets = new ArrayList<ChangeSet>();
changeSets.add( changeSet );
assertTrue( executor.shouldBuild( changeSets, continuumProject, new File(
"target/test-classes/projects/continuum" ), buildDefinition ) );
}
}
| 5,035 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/execution/manager/DefaultBuildExecutorManagerTest.java | package org.apache.maven.continuum.execution.manager;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.execution.AbstractBuildExecutor;
import org.apache.maven.continuum.execution.ant.AntBuildExecutor;
import org.apache.maven.continuum.execution.maven.m1.MavenOneBuildExecutor;
import org.apache.maven.continuum.execution.maven.m2.MavenTwoBuildExecutor;
import org.apache.maven.continuum.execution.shell.ShellBuildExecutor;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class DefaultBuildExecutorManagerTest
extends AbstractContinuumTest
{
private BuildExecutorManager builderManager;
@Before
public void setUp()
throws Exception
{
builderManager = lookup( BuildExecutorManager.class );
}
@Test
public void testMavenTwoBuildExecutorDependencyInjection()
throws Exception
{
MavenTwoBuildExecutor executor = (MavenTwoBuildExecutor) builderManager.getBuildExecutor(
MavenTwoBuildExecutor.ID );
assertCommonFields( executor );
assertNotNull( executor.getBuilderHelper() );
assertNotNull( executor.getProjectHelper() );
assertNotNull( executor.getConfigurationService() );
}
@Test
public void testMavenOneBuildExecutorDependencyInjection()
throws Exception
{
MavenOneBuildExecutor executor = (MavenOneBuildExecutor) builderManager.getBuildExecutor(
MavenOneBuildExecutor.ID );
assertCommonFields( executor );
assertNotNull( executor.getMetadataHelper() );
}
@Test
public void testAntBuildExecutorDependencyInjection()
throws Exception
{
AntBuildExecutor executor = (AntBuildExecutor) builderManager.getBuildExecutor( AntBuildExecutor.ID );
assertCommonFields( executor );
}
@Test
public void testShellBuildExecutorDependencyInjection()
throws Exception
{
ShellBuildExecutor executor = (ShellBuildExecutor) builderManager.getBuildExecutor( ShellBuildExecutor.ID );
assertCommonFields( executor );
}
private void assertCommonFields( AbstractBuildExecutor executor )
{
assertNotNull( executor.getShellCommandHelper() );
assertNotNull( executor.getExecutableResolver() );
assertNotNull( executor.getWorkingDirectoryService() );
assertNotNull( executor.getInstallationService() );
}
}
| 5,036 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/buildqueue/BuildQueueTest.java | package org.apache.maven.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.taskqueue.BuildProjectTask;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class BuildQueueTest
extends AbstractContinuumTest
{
private TaskQueue buildQueue;
@Before
public void setUp()
throws Exception
{
buildQueue = lookup( TaskQueue.class, "build-project" );
}
@Test
public void testTestTheQueueWithASingleProject()
throws Exception
{
Project project = addProject( "Build Queue Project 1" );
int projectId = project.getId();
buildProject( projectId, ContinuumProjectState.TRIGGER_SCHEDULED );
assertNextBuildIs( projectId );
assertNextBuildIsNull();
buildProject( projectId, ContinuumProjectState.TRIGGER_SCHEDULED );
buildProject( projectId, ContinuumProjectState.TRIGGER_SCHEDULED );
buildProject( projectId, ContinuumProjectState.TRIGGER_SCHEDULED );
buildProject( projectId, ContinuumProjectState.TRIGGER_SCHEDULED );
buildProject( projectId, ContinuumProjectState.TRIGGER_SCHEDULED );
assertNextBuildIs( projectId );
assertNextBuildIsNull();
}
@Test
public void testTheQueueWithMultipleProjects()
throws Exception
{
int projectId1 = addProject( "Build Queue Project 2" ).getId();
int projectId2 = addProject( "Build Queue Project 3" ).getId();
buildProject( projectId1, ContinuumProjectState.TRIGGER_SCHEDULED );
buildProject( projectId2, ContinuumProjectState.TRIGGER_SCHEDULED );
assertNextBuildIs( projectId1 );
assertNextBuildIs( projectId2 );
assertNextBuildIsNull();
for ( int i = 0; i < 5; i++ )
{
buildProject( projectId1, ContinuumProjectState.TRIGGER_SCHEDULED );
buildProject( projectId2, ContinuumProjectState.TRIGGER_SCHEDULED );
}
assertNextBuildIs( projectId1 );
assertNextBuildIs( projectId2 );
assertNextBuildIsNull();
}
@Test
public void testTestTheQueueWithASingleProjectAndForcedBuilds()
throws Exception
{
String name = "Build Queue Project 4";
int projectId = addProject( name ).getId();
buildProject( projectId, ContinuumProjectState.TRIGGER_FORCED );
assertNextBuildIs( projectId );
assertNextBuildIsNull();
for ( int i = 0; i < 5; i++ )
{
buildProject( projectId, ContinuumProjectState.TRIGGER_FORCED );
}
assertNextBuildIs( projectId );
assertNextBuildIs( projectId );
assertNextBuildIs( projectId );
assertNextBuildIs( projectId );
assertNextBuildIs( projectId );
assertNextBuildIsNull();
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
private void buildProject( int projectId, int trigger )
throws Exception
{
ProjectGroup group = getDefaultProjectGroup();
buildQueue.put( new BuildProjectTask( projectId, 0, new BuildTrigger( trigger, "" ), null, null, null,
group.getId() ) );
}
private void assertNextBuildIs( int expectedProjectId )
throws Exception
{
Task task = buildQueue.take();
assertEquals( BuildProjectTask.class.getName(), task.getClass().getName() );
BuildProjectTask buildProjectTask = (BuildProjectTask) task;
assertEquals( "Didn't get the expected project id.", expectedProjectId, buildProjectTask.getProjectId() );
}
private void assertNextBuildIsNull()
throws Exception
{
Task task = buildQueue.take();
if ( task != null )
{
fail( "Got a non-null build task returned. Project id: " + ( (BuildProjectTask) task ).getProjectId() );
}
}
}
| 5,037 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/builddefinition/DefaultBuildDefinitionServiceTest.java | package org.apache.maven.continuum.builddefinition;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.DaoUtils;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:olamy@apache.org">olamy</a>
* @since 15 sept. 07
*/
public class DefaultBuildDefinitionServiceTest
extends AbstractContinuumTest
{
private static final Logger logger = LoggerFactory.getLogger( DefaultBuildDefinitionServiceTest.class );
private Project project;
private BuildDefinitionTemplate buildDefinitionTemplate;
@Before
public void setUp()
throws Exception
{
DaoUtils daoUtils = lookup( DaoUtils.class );
daoUtils.eraseDatabase();
ProjectGroup projectGroup = new ProjectGroup();
projectGroup.setName( "test" );
projectGroup = getProjectGroupDao().addProjectGroup( projectGroup );
project = new Project();
project.setGroupId( "foo" );
project.setArtifactId( "bar" );
project.setVersion( "0.1-alpha-1-SNAPSHOT" );
projectGroup.addProject( project );
getProjectGroupDao().updateProjectGroup( projectGroup );
BuildDefinition buildDefinition = new BuildDefinition();
buildDefinition.setTemplate( true );
buildDefinition.setArguments( "-N" );
buildDefinition.setGoals( "clean test-compile" );
buildDefinition.setBuildFile( "pom.xml" );
buildDefinition.setDescription( "desc template" );
buildDefinition = getBuildDefinitionService().addBuildDefinition( buildDefinition );
buildDefinitionTemplate = new BuildDefinitionTemplate();
buildDefinitionTemplate.setName( "test" );
buildDefinitionTemplate = getBuildDefinitionService().addBuildDefinitionTemplate( buildDefinitionTemplate );
buildDefinitionTemplate = getBuildDefinitionService().addBuildDefinitionInTemplate( buildDefinitionTemplate,
buildDefinition, false );
}
protected BuildDefinitionService getBuildDefinitionService()
throws Exception
{
return lookup( BuildDefinitionService.class );
}
@Test
public void testAddTemplateInProject()
throws Exception
{
try
{
List<BuildDefinitionTemplate> templates = getBuildDefinitionService().getAllBuildDefinitionTemplate();
assertEquals( 5, templates.size() );
assertEquals( 5, getBuildDefinitionService().getAllBuildDefinitions().size() );
getBuildDefinitionService().addTemplateInProject( buildDefinitionTemplate.getId(), project );
project = getProjectDao().getProjectWithAllDetails( project.getId() );
templates = getBuildDefinitionService().getAllBuildDefinitionTemplate();
assertEquals( 1, project.getBuildDefinitions().size() );
assertEquals( 5, templates.size() );
List<BuildDefinition> all = getBuildDefinitionService().getAllBuildDefinitions();
assertEquals( 6, all.size() );
getBuildDefinitionService().addTemplateInProject( buildDefinitionTemplate.getId(), project );
project = getProjectDao().getProjectWithAllDetails( project.getId() );
templates = getBuildDefinitionService().getAllBuildDefinitionTemplate();
assertEquals( 2, project.getBuildDefinitions().size() );
assertEquals( 5, templates.size() );
all = getBuildDefinitionService().getAllBuildDefinitions();
assertEquals( 7, all.size() );
}
catch ( Exception e )
{
logger.error( e.getMessage(), e );
throw e;
}
}
@Test
public void testGetDefaultBuildDef()
throws Exception
{
BuildDefinition bd =
getBuildDefinitionService().getDefaultAntBuildDefinitionTemplate().getBuildDefinitions().get(
0 );
assertNotNull( bd );
assertEquals( "build.xml", bd.getBuildFile() );
bd =
getBuildDefinitionService().getDefaultMavenTwoBuildDefinitionTemplate().getBuildDefinitions().get(
0 );
BuildDefinitionService buildDefinitionService = lookup( BuildDefinitionService.class );
assertEquals( 5, buildDefinitionService.getAllBuildDefinitionTemplate().size() );
assertNotNull( bd );
assertEquals( "pom.xml", bd.getBuildFile() );
assertEquals( "clean install", bd.getGoals() );
}
@Test
public void testAddBuildDefinitionTemplate()
throws Exception
{
BuildDefinitionTemplate template = new BuildDefinitionTemplate();
template.setName( "testTemplate" );
template = getBuildDefinitionService().addBuildDefinitionTemplate( template );
template = getBuildDefinitionService().getBuildDefinitionTemplate( template.getId() );
assertNotNull( template );
assertEquals( "testTemplate", template.getName() );
List<BuildDefinition> all = getBuildDefinitionService().getAllBuildDefinitions();
assertEquals( 5, all.size() );
BuildDefinition bd =
getBuildDefinitionService().getDefaultMavenTwoBuildDefinitionTemplate().getBuildDefinitions().get(
0 );
template = getBuildDefinitionService().addBuildDefinitionInTemplate( template, bd, false );
assertEquals( true, getBuildDefinitionService().isBuildDefinitionInUse( bd ) );
assertEquals( 1, template.getBuildDefinitions().size() );
all = getBuildDefinitionService().getAllBuildDefinitions();
assertEquals( 5, all.size() );
template = getBuildDefinitionService().getBuildDefinitionTemplate( template.getId() );
template = getBuildDefinitionService().updateBuildDefinitionTemplate( template );
template = getBuildDefinitionService().removeBuildDefinitionFromTemplate( template, bd );
assertEquals( 0, template.getBuildDefinitions().size() );
all = getBuildDefinitionService().getAllBuildDefinitions();
assertEquals( 5, all.size() );
}
@Test
public void testAddDuplicateBuildDefinitionTemplate()
throws Exception
{
BuildDefinitionTemplate template = new BuildDefinitionTemplate();
template.setName( "test" );
template = getBuildDefinitionService().addBuildDefinitionTemplate( template );
assertNull( template );
}
@Test
public void testUnusedBuildDefinition()
throws Exception
{
BuildDefinition unused = new BuildDefinition();
unused.setTemplate( true );
unused.setArguments( "-N" );
unused.setGoals( "clean test-compile" );
unused.setBuildFile( "pom.xml" );
unused.setDescription( "desc template" );
assertFalse( getBuildDefinitionService().isBuildDefinitionInUse( unused ) );
}
}
| 5,038 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/scm | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/scm/queue/PrepareBuildProjectsTaskExecutorTest.java | package org.apache.maven.continuum.scm.queue;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildmanager.BuildsManager;
import org.apache.continuum.dao.ProjectScmRootDao;
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.continuum.taskqueue.BuildProjectTask;
import org.apache.continuum.taskqueue.PrepareBuildProjectsTask;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.core.action.AbstractContinuumAction;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilderException;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.continuum.project.builder.maven.MavenTwoContinuumProjectBuilder;
import org.codehaus.plexus.action.ActionManager;
import org.codehaus.plexus.util.StringUtils;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class PrepareBuildProjectsTaskExecutorTest
extends AbstractContinuumTest
{
private ContinuumProjectBuilder projectBuilder;
private ActionManager actionManager;
private ProjectScmRootDao projectScmRootDao;
private ConfigurationService configurationService;
private BuildsManager buildsManager;
@Before
public void setUp()
throws Exception
{
projectBuilder = lookup( ContinuumProjectBuilder.class, MavenTwoContinuumProjectBuilder.ID );
projectScmRootDao = lookup( ProjectScmRootDao.class );
actionManager = lookup( ActionManager.class );
configurationService = (ConfigurationService) lookup( "configurationService" );
buildsManager = lookup( BuildsManager.class, "parallel" );
}
@Test
public void testCheckoutPrepareBuildMultiModuleProject()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/multi-module/pom.xml", false, false );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "multi-module-parent" );
Project moduleA = getProjectDao().getProjectByName( "module-A" );
Project moduleB = getProjectDao().getProjectByName( "module-B" );
Project moduleD = getProjectDao().getProjectByName( "module-D" );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File workingDir = configurationService.getWorkingDirectory();
assertTrue( "checkout directory of project 'multi-module-parent' does not exist.", new File( workingDir,
Integer.toString(
rootProject.getId() ) ).exists() );
assertTrue( "checkout directory of project 'module-A' does not exist.", new File( workingDir, Integer.toString(
moduleA.getId() ) ).exists() );
assertTrue( "checkout directory of project 'module-B' does not exist.", new File( workingDir, Integer.toString(
moduleB.getId() ) ).exists() );
assertTrue( "checkout directory of project 'module-D' does not exist.", new File( workingDir, Integer.toString(
moduleD.getId() ) ).exists() );
assertTrue( "failed to checkout project 'multi-module-parent'", new File( workingDir, Integer.toString(
rootProject.getId() ) ).list().length > 0 );
assertTrue( "failed to checkout project 'module-A'", new File( workingDir, Integer.toString(
moduleA.getId() ) ).list().length > 0 );
assertTrue( "failed to checkout project 'module-B'", new File( workingDir, Integer.toString(
moduleB.getId() ) ).list().length > 0 );
assertTrue( "failed to checkout project 'module-D'", new File( workingDir, Integer.toString(
moduleD.getId() ) ).list().length > 0 );
// wait while task finished build
waitForBuildToFinish();
}
@Test
public void testCheckoutPrepareBuildMultiModuleProjectFreshBuild()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/multi-module/pom.xml", false, true );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "multi-module-parent" );
Project moduleA = getProjectDao().getProjectByName( "module-A" );
Project moduleB = getProjectDao().getProjectByName( "module-B" );
Project moduleD = getProjectDao().getProjectByName( "module-D" );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File workingDir = configurationService.getWorkingDirectory();
assertTrue( "checkout directory of project 'multi-module-parent' does not exist.", new File( workingDir,
Integer.toString(
rootProject.getId() ) ).exists() );
assertTrue( "checkout directory of project 'module-A' does not exist.", new File( workingDir, Integer.toString(
moduleA.getId() ) ).exists() );
assertTrue( "checkout directory of project 'module-B' does not exist.", new File( workingDir, Integer.toString(
moduleB.getId() ) ).exists() );
assertTrue( "checkout directory of project 'module-D' does not exist.", new File( workingDir, Integer.toString(
moduleD.getId() ) ).exists() );
assertTrue( "failed to checkout project 'multi-module-parent'", new File( workingDir, Integer.toString(
rootProject.getId() ) ).list().length > 0 );
assertTrue( "failed to checkout project 'module-A'", new File( workingDir, Integer.toString(
moduleA.getId() ) ).list().length > 0 );
assertTrue( "failed to checkout project 'module-B'", new File( workingDir, Integer.toString(
moduleB.getId() ) ).list().length > 0 );
assertTrue( "failed to checkout project 'module-D'", new File( workingDir, Integer.toString(
moduleD.getId() ) ).list().length > 0 );
// wait while task finished build
waitForBuildToFinish();
}
@Test
public void testCheckoutPrepareBuildSingleCheckedoutMultiModuleProject()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/multi-module/pom.xml", true, false );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "multi-module-parent" );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File checkedOutDir = new File( configurationService.getWorkingDirectory(), Integer.toString(
rootProject.getId() ) );
assertTrue( "checkout directory of project 'multi-module-parent' does not exist.", checkedOutDir.exists() );
assertTrue( "module-A was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-A" ).exists() );
assertTrue( "module-B was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-B" ).exists() );
assertTrue( "module-D was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-C/module-D" ).exists() );
assertTrue( "failed to checkout project 'multi-module-parent'", checkedOutDir.list().length > 0 );
assertTrue( "failed to checkout project 'module-A'", new File( checkedOutDir, "module-A" ).list().length > 0 );
assertTrue( "failed to checkout project 'module-B'", new File( checkedOutDir, "module-B" ).list().length > 0 );
assertTrue( "failed to checkout project 'module-D'", new File( checkedOutDir,
"module-C/module-D" ).list().length > 0 );
// wait while task finishes build
waitForBuildToFinish();
}
@Test
public void testCheckoutPrepareBuildSingleCheckedoutMultiModuleProjectFreshBuild()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/multi-module/pom.xml", true, true );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "multi-module-parent" );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File checkedOutDir = new File( configurationService.getWorkingDirectory(), Integer.toString(
rootProject.getId() ) );
assertTrue( "checkout directory of project 'multi-module-parent' does not exist.", checkedOutDir.exists() );
assertTrue( "module-A was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-A" ).exists() );
assertTrue( "module-B was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-B" ).exists() );
assertTrue( "module-D was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-C/module-D" ).exists() );
assertTrue( "failed to checkout project 'multi-module-parent'", checkedOutDir.list().length > 0 );
assertTrue( "failed to checkout project 'module-A'", new File( checkedOutDir, "module-A" ).list().length > 0 );
assertTrue( "failed to checkout project 'module-B'", new File( checkedOutDir, "module-B" ).list().length > 0 );
assertTrue( "failed to checkout project 'module-D'", new File( checkedOutDir,
"module-C/module-D" ).list().length > 0 );
// wait while task finishes build
waitForBuildToFinish();
}
@Test
public void testCheckoutPrepareBuildSingleCheckoutFlatMultiModuleProject()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/flat-multi-module/parent-project/pom.xml", true,
false );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "parent-project" );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File checkedOutDir = new File( configurationService.getWorkingDirectory(), Integer.toString(
rootProject.getId() ) );
assertTrue( "checkout directory of project 'parent-project' does not exist.", new File( checkedOutDir,
"parent-project" ).exists() );
assertTrue( "module-a was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-a" ).exists() );
assertTrue( "module-b was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-b" ).exists() );
assertTrue( "module-d was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-c/module-d" ).exists() );
assertTrue( "failed to checkout parent-project", new File( checkedOutDir, "parent-project" ).list().length >
0 );
assertTrue( "failed to checkout module-a", new File( checkedOutDir, "module-a" ).list().length > 0 );
assertTrue( "failed to checkout module-b", new File( checkedOutDir, "module-b" ).list().length > 0 );
assertTrue( "failed to checkout module-d", new File( checkedOutDir, "module-c/module-d" ).list().length > 0 );
// wait while task finishes build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
}
@Test
public void testCheckoutPrepareBuildSingleCheckoutFlatMultiModuleProjectBuildFresh()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/flat-multi-module/parent-project/pom.xml", true,
true );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "parent-project" );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File checkedOutDir = new File( configurationService.getWorkingDirectory(), Integer.toString(
rootProject.getId() ) );
assertTrue( "checkout directory of project 'parent-project' does not exist.", new File( checkedOutDir,
"parent-project" ).exists() );
assertTrue( "module-a was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-a" ).exists() );
assertTrue( "module-b was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-b" ).exists() );
assertTrue( "module-d was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-c/module-d" ).exists() );
assertTrue( "failed to checkout parent-project", new File( checkedOutDir, "parent-project" ).list().length >
0 );
assertTrue( "failed to checkout module-a", new File( checkedOutDir, "module-a" ).list().length > 0 );
assertTrue( "failed to checkout module-b", new File( checkedOutDir, "module-b" ).list().length > 0 );
assertTrue( "failed to checkout module-d", new File( checkedOutDir, "module-c/module-d" ).list().length > 0 );
// wait while task finishes build
waitForBuildToFinish();
}
@Test
public void testCheckoutPrepareBuildSingleCheckoutFlatMultiModuleProjectBuildFreshAfterRemovingWorkingCopy()
throws Exception
{
PrepareBuildProjectsTask task = createTask( "src/test-projects/flat-multi-module/parent-project/pom.xml", true,
true );
List<Project> projects = getProjectDao().getProjectsInGroup( task.getProjectGroupId() );
assertEquals( "failed to add all projects", 4, projects.size() );
Project rootProject = getProjectDao().getProjectByName( "parent-project" );
File rootProjectDir = new File( configurationService.getWorkingDirectory(), Integer.toString(
rootProject.getId() ) );
rootProjectDir = new File( rootProjectDir, "parent-project" );
rootProject.setWorkingDirectory( rootProjectDir.getAbsolutePath() );
getProjectDao().updateProject( rootProject );
buildsManager.prepareBuildProjects( task.getProjectsBuildDefinitionsMap(), task.getBuildTrigger(),
task.getProjectGroupId(), task.getProjectGroupName(),
task.getScmRootAddress(), task.getProjectScmRootId() );
// wait while task finishes prepare build
waitForPrepareBuildToFinish( task.getProjectGroupId(), task.getProjectScmRootId() );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( task.getProjectScmRootId() );
assertEquals( "Failed to update multi-module project", ContinuumProjectState.UPDATED, scmRoot.getState() );
File checkedOutDir = new File( configurationService.getWorkingDirectory(), Integer.toString(
rootProject.getId() ) );
assertTrue( "checkout directory of project 'parent-project' does not exist.", new File( checkedOutDir,
"parent-project" ).exists() );
assertTrue( "module-a was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-a" ).exists() );
assertTrue( "module-b was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-b" ).exists() );
assertTrue( "module-d was not checked out in the same directory as it's parent.", new File( checkedOutDir,
"module-c/module-d" ).exists() );
assertTrue( "failed to checkout parent-project", new File( checkedOutDir, "parent-project" ).list().length >
0 );
assertTrue( "failed to checkout module-a", new File( checkedOutDir, "module-a" ).list().length > 0 );
assertTrue( "failed to checkout module-b", new File( checkedOutDir, "module-b" ).list().length > 0 );
assertTrue( "failed to checkout module-d", new File( checkedOutDir, "module-c/module-d" ).list().length > 0 );
// wait while task finishes build
waitForBuildToFinish();
}
private PrepareBuildProjectsTask createTask( String pomResource, boolean singleCheckout, boolean buildFresh )
throws Exception
{
ProjectGroup projectGroup = getProjectGroup( pomResource, singleCheckout );
BuildDefinition buildDefinition = new BuildDefinition();
buildDefinition.setId( 0 );
buildDefinition.setGoals( "clean" );
buildDefinition.setBuildFresh( buildFresh );
projectGroup.addBuildDefinition( buildDefinition );
Map<String, Object> pgContext = new HashMap<String, Object>();
AbstractContinuumAction.setWorkingDirectory( pgContext,
configurationService.getWorkingDirectory().getAbsolutePath() );
AbstractContinuumAction.setUnvalidatedProjectGroup( pgContext, projectGroup );
actionManager.lookup( "validate-project-group" ).execute( pgContext );
actionManager.lookup( "store-project-group" ).execute( pgContext );
int projectGroupId = AbstractContinuumAction.getProjectGroupId( pgContext );
projectGroup = getProjectGroupDao().getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId );
String scmRootUrl = getScmRootUrl( projectGroup );
assertNotNull( scmRootUrl );
ProjectScmRoot scmRoot = getProjectScmRoot( projectGroup, scmRootUrl );
assertNotNull( scmRoot );
buildDefinition = (BuildDefinition) projectGroup.getBuildDefinitions().get( 0 );
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Project rootProject = null;
List<Project> projects = (List<Project>) projectGroup.getProjects();
for ( Project project : projects )
{
assertFalse( project.getId() == 0 );
map.put( project.getId(), buildDefinition.getId() );
if ( rootProject == null || rootProject.getId() > project.getId() )
{
rootProject = project;
}
}
assertEquals( 4, map.size() );
PrepareBuildProjectsTask task = new PrepareBuildProjectsTask( map,
new org.apache.continuum.utils.build.BuildTrigger(
1, "user" ), projectGroupId,
projectGroup.getName(),
scmRoot.getScmRootAddress(), scmRoot.getId() );
return task;
}
private ProjectGroup getProjectGroup( String pomResource, boolean singleCheckout )
throws ContinuumProjectBuilderException, IOException
{
File pom = getTestFile( pomResource );
assertNotNull( "Can't find project " + pomResource, pom );
//ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( pom.toURL(), null, null, true );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( pom.toURL(), null, null, true,
singleCheckout );
// some assertions to make sure our expectations match. This is NOT
// meant as a unit test for the projectbuilder!
assertNotNull( "Project list not null", result.getProjects() );
assertEquals( "#Projectgroups", 1, result.getProjectGroups().size() );
ProjectGroup pg = result.getProjectGroups().get( 0 );
if ( !result.getProjects().isEmpty() )
{
for ( Project p : result.getProjects() )
{
pg.addProject( p );
}
}
return pg;
}
private ProjectScmRoot getProjectScmRoot( ProjectGroup pg, String url )
throws Exception
{
if ( StringUtils.isEmpty( url ) )
{
return null;
}
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( pg.getId(), url );
if ( scmRoot != null )
{
return scmRoot;
}
ProjectScmRoot projectScmRoot = new ProjectScmRoot();
projectScmRoot.setProjectGroup( pg );
projectScmRoot.setScmRootAddress( url );
return projectScmRootDao.addProjectScmRoot( projectScmRoot );
}
private String getScmRootUrl( ProjectGroup pg )
{
String scmRootUrl = null;
for ( Project project : pg.getProjects() )
{
String scmUrl = project.getScmUrl();
scmRootUrl = getCommonPath( scmUrl, scmRootUrl );
}
return scmRootUrl;
}
private String getCommonPath( String path1, String path2 )
{
if ( path2 == null || path2.equals( "" ) )
{
return path1;
}
else
{
int indexDiff = StringUtils.differenceAt( path1, path2 );
return path1.substring( 0, indexDiff );
}
}
private void waitForPrepareBuildToFinish( int projectGroupId, int scmRootId )
throws Exception
{
while ( buildsManager.isInPrepareBuildQueue( projectGroupId, scmRootId ) ||
buildsManager.isProjectGroupCurrentlyPreparingBuild( projectGroupId, scmRootId ) )
{
Thread.sleep( 10 );
}
}
private void waitForBuildToFinish()
throws Exception
{
while ( buildsManager.isBuildInProgress() || isAnyProjectInBuildQueue() )
{
Thread.sleep( 10 );
}
}
private boolean isAnyProjectInBuildQueue()
throws Exception
{
Map<String, List<BuildProjectTask>> buildTasks = buildsManager.getProjectsInBuildQueues();
for ( String queue : buildTasks.keySet() )
{
if ( !buildTasks.get( queue ).isEmpty() )
{
return true;
}
}
return false;
}
}
| 5,039 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/buildcontroller/DefaultBuildControllerTest.java | package org.apache.maven.continuum.buildcontroller;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.core.action.AbstractContinuumAction;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectDependency;
import org.apache.maven.continuum.model.project.Schedule;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class DefaultBuildControllerTest
extends AbstractContinuumTest
{
private DefaultBuildController controller;
private static String FORCED_BUILD_USER = "TestUsername";
private static String SCHEDULE_NAME = "TEST_SCHEDULE";
int projectId1;
int projectId2;
int buildDefinitionId1;
int buildDefinitionId2;
@Before
public void setUp()
throws Exception
{
BuildDefinitionDao buildDefinitionDao = lookup( BuildDefinitionDao.class );
BuildResultDao buildResultDao = lookup( BuildResultDao.class );
Project project1 = createProject( "project1" );
BuildDefinition bd1 = createBuildDefinition();
project1.addBuildDefinition( bd1 );
project1.setState( ContinuumProjectState.OK );
projectId1 = addProject( project1 ).getId();
buildDefinitionId1 = buildDefinitionDao.getDefaultBuildDefinition( projectId1 ).getId();
project1 = getProjectDao().getProject( projectId1 );
BuildResult buildResult1 = new BuildResult();
buildResult1.setStartTime( Calendar.getInstance().getTimeInMillis() );
buildResult1.setEndTime( Calendar.getInstance().getTimeInMillis() );
buildResult1.setState( ContinuumProjectState.OK );
buildResult1.setSuccess( true );
buildResult1.setBuildDefinition( bd1 );
buildResultDao.addBuildResult( project1, buildResult1 );
BuildResult buildResult2 = new BuildResult();
buildResult2.setStartTime( Calendar.getInstance().getTimeInMillis() - 7200000 );
buildResult2.setEndTime( Calendar.getInstance().getTimeInMillis() - 7200000 );
buildResult2.setSuccess( true );
buildResult2.setState( ContinuumProjectState.OK );
buildResult2.setBuildDefinition( bd1 );
buildResultDao.addBuildResult( project1, buildResult2 );
createPomFile( getProjectDao().getProjectWithAllDetails( projectId1 ) );
Project project2 = createProject( "project2" );
ProjectDependency dep1 = new ProjectDependency();
dep1.setGroupId( "org.apache.maven.testproject" );
dep1.setArtifactId( "project1" );
dep1.setVersion( "1.0-SNAPSHOT" );
project2.addDependency( dep1 );
ProjectDependency dep2 = new ProjectDependency();
dep2.setGroupId( "junit" );
dep2.setArtifactId( "junit" );
dep2.setVersion( "3.8.1" );
project2.addDependency( dep2 );
BuildDefinition bd2 = createBuildDefinition();
project2.addBuildDefinition( bd2 );
project2.setState( ContinuumProjectState.OK );
projectId2 = addProject( project2 ).getId();
buildDefinitionId2 = buildDefinitionDao.getDefaultBuildDefinition( projectId2 ).getId();
createPomFile( getProjectDao().getProjectWithAllDetails( projectId2 ) );
controller = (DefaultBuildController) lookup( BuildController.class );
}
private Project createProject( String artifactId )
{
Project project = new Project();
project.setExecutorId( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR );
project.setName( artifactId );
project.setGroupId( "org.apache.maven.testproject" );
project.setArtifactId( artifactId );
project.setVersion( "1.0-SNAPSHOT" );
return project;
}
private BuildDefinition createBuildDefinition()
{
BuildDefinition builddef = new BuildDefinition();
Schedule schedule = new Schedule();
schedule.setName( SCHEDULE_NAME );
builddef.setSchedule( schedule );
builddef.setBuildFile( "pom.xml" );
builddef.setGoals( "clean" );
builddef.setDefaultForProject( true );
return builddef;
}
private BuildContext getScheduledBuildContext()
throws Exception
{
return controller.initializeBuildContext( projectId2, buildDefinitionId2, new BuildTrigger(
ContinuumProjectState.TRIGGER_SCHEDULED ), new ScmResult() );
}
private BuildContext getForcedBuildContext()
throws Exception
{
return controller.initializeBuildContext( projectId2, buildDefinitionId2, new BuildTrigger(
ContinuumProjectState.TRIGGER_FORCED, FORCED_BUILD_USER ), new ScmResult() );
}
private BuildContext getContext( int hourOfLastExecution )
throws Exception
{
BuildContext context = getScheduledBuildContext();
BuildResult oldBuildResult = new BuildResult();
oldBuildResult.setEndTime( Calendar.getInstance().getTimeInMillis() + ( hourOfLastExecution * 3600000 ) );
context.setOldBuildResult( oldBuildResult );
context.setScmResult( new ScmResult() );
Map<String, Object> actionContext = context.getActionContext();
ProjectScmRoot projectScmRoot = new ProjectScmRoot();
projectScmRoot.setId( 1 );
projectScmRoot.setScmRootAddress( "scm:local:src/test-projects:flat-multi-module" );
AbstractContinuumAction.setProjectScmRoot( actionContext, projectScmRoot );
return context;
}
@Test
public void testWithoutDependencyChanges()
throws Exception
{
BuildContext context = getContext( +1 );
controller.checkProjectDependencies( context );
assertEquals( 0, context.getModifiedDependencies().size() );
assertFalse( controller.shouldBuild( context ) );
}
@Test
public void testWithNewProjects()
throws Exception
{
Project p1 = getProjectDao().getProject( projectId1 );
p1.setState( ContinuumProjectState.NEW );
getProjectDao().updateProject( p1 );
Project p2 = getProjectDao().getProject( projectId2 );
p2.setState( ContinuumProjectState.NEW );
getProjectDao().updateProject( p2 );
BuildContext context = getScheduledBuildContext();
controller.checkProjectDependencies( context );
assertEquals( 0, context.getModifiedDependencies().size() );
assertTrue( controller.shouldBuild( context ) );
}
@Test
public void testWithNewBuildDefinition()
throws Exception
{
BuildContext context = getScheduledBuildContext();
assertNull( context.getOldBuildResult() );
assertTrue( controller.shouldBuild( context ) );
}
@Test
public void testWithDependencyChanges()
throws Exception
{
BuildContext context = getContext( -1 );
controller.checkProjectDependencies( context );
assertEquals( 1, context.getModifiedDependencies().size() );
assertTrue( controller.shouldBuild( context ) );
}
@Test
public void testWithNullScmResult()
throws Exception
{
BuildContext context = getContext( +1 );
context.setScmResult( null );
controller.checkProjectDependencies( context );
assertEquals( 0, context.getModifiedDependencies().size() );
assertFalse( controller.shouldBuild( context ) );
}
@Test
public void testForcedBuildTriggeredByField()
throws Exception
{
BuildContext context = getForcedBuildContext();
assertEquals( FORCED_BUILD_USER, context.getBuildTrigger().getTriggeredBy() );
}
@Test
public void testScheduledBuildTriggeredByField()
throws Exception
{
BuildContext context = getScheduledBuildContext();
assertEquals( SCHEDULE_NAME, context.getBuildTrigger().getTriggeredBy() );
}
@Test
public void testScheduledBuildTriggeredByField_UsernameProvided()
throws Exception
{
BuildTrigger buildTrigger = new BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "test-user" );
BuildContext context = controller.initializeBuildContext( projectId2, buildDefinitionId2, buildTrigger,
new ScmResult() );
String contextTriggeredBy = context.getBuildTrigger().getTriggeredBy();
assertFalse( "test-user".equals( contextTriggeredBy ) );
assertEquals( SCHEDULE_NAME, contextTriggeredBy );
}
private File getWorkingDirectory()
throws Exception
{
File workingDirectory = getTestFile( "target/working-directory" );
if ( !workingDirectory.exists() )
{
workingDirectory.mkdir();
}
return workingDirectory;
}
private File getWorkingDirectory( Project project )
throws Exception
{
File projectDir = new File( getWorkingDirectory(), Integer.toString( project.getId() ) );
if ( !projectDir.exists() )
{
projectDir.mkdirs();
System.out.println( "projectdirectory created" + projectDir.getAbsolutePath() );
}
return projectDir;
}
private void createPomFile( Project project )
throws Exception
{
File pomFile = new File( getWorkingDirectory( project ), "pom.xml" );
BufferedWriter out = new BufferedWriter( new FileWriter( pomFile ) );
out.write( "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" );
out.write( "<modelVersion>4.0.0</modelVersion>\n" );
out.write( "<groupId>" + project.getGroupId() + "</groupId>\n" );
out.write( "<artifactId>" + project.getArtifactId() + "</artifactId>\n" );
out.write( "<version>" + project.getVersion() + "</version>\n" );
out.write( "<scm>\n" );
out.write( "<connection>" + "scm:local|" + getWorkingDirectory().getAbsolutePath() +
"|" + project.getId() + "</connection>\n" );
out.write( "</scm>" );
if ( project.getDependencies().size() > 0 )
{
out.write( "<dependencies>\n" );
List<ProjectDependency> dependencies = project.getDependencies();
for ( ProjectDependency dependency : dependencies )
{
out.write( "<dependency>\n" );
out.write( "<groupId>" + dependency.getGroupId() + "</groupId>\n" );
out.write( "<artifactId>" + dependency.getArtifactId() + "</artifactId>\n" );
out.write( "<version>" + dependency.getVersion() + "</version>\n" );
out.write( "</dependency>\n" );
}
out.write( "</dependencies>\n" );
}
out.write( "</project>" );
out.close();
System.out.println( "pom file created" );
}
}
| 5,040 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/maven/continuum/buildcontroller/BuildProjectTaskExecutorTest.java | package org.apache.maven.continuum.buildcontroller;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.taskqueue.BuildProjectTask;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.continuum.utils.file.FileSystemManager;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.core.action.AbstractContinuumAction;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilderException;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.continuum.project.builder.maven.MavenTwoContinuumProjectBuilder;
import org.codehaus.plexus.action.ActionManager;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a>
*/
public class BuildProjectTaskExecutorTest
extends AbstractContinuumTest
{
private ContinuumProjectBuilder projectBuilder;
private TaskQueue buildQueue;
private TaskQueueExecutor taskQueueExecutor;
private ActionManager actionManager;
@Before
public void setUp()
throws Exception
{
projectBuilder = lookup( ContinuumProjectBuilder.class, MavenTwoContinuumProjectBuilder.ID );
buildQueue = lookup( TaskQueue.class, "build-project" );
taskQueueExecutor = lookup( TaskQueueExecutor.class, "build-project" );
actionManager = lookup( ActionManager.class );
}
@Test
public void testAutomaticCancellation()
throws Exception
{
runTimeoutProject( 13000 );
long taskStartTime = System.currentTimeMillis();
// should be killed in 5 secs, plus slack
waitForTaskDead( 10000 );
// the project will sleep for 15 seconds and then write a file.
// Make sure we sleep at least that long and then check for the file;
// it should not be there.
long taskWaitTime = 15000 - ( System.currentTimeMillis() - taskStartTime );
System.err.println( "Sleeping " + taskWaitTime + "ms" );
Thread.sleep( taskWaitTime );
assertFalse( "Build completed", getTestFile( "src/test-projects/timeout/target/TEST-COMPLETED" ).exists() );
}
@Test
public void testManualCancellation()
throws Exception
{
BuildProjectTask task = runTimeoutProject( 0 );
assertFalse( "Build completed", getTestFile( "src/test-projects/timeout/target/TEST-COMPLETED" ).exists() );
long taskStartTime = System.currentTimeMillis();
assertTrue( taskQueueExecutor.cancelTask( task ) );
waitForTaskDead( 5000 );
long taskWaitTime = 15000 - ( System.currentTimeMillis() - taskStartTime );
System.err.println( "Sleeping " + taskWaitTime + "ms" );
Thread.sleep( taskWaitTime );
assertFalse( "Build completed", getTestFile( "src/test-projects/timeout/target/TEST-COMPLETED" ).exists() );
}
@Test
public void testNoCancellation()
throws Exception
{
runTimeoutProject( 0 );
waitForFile( "src/test-projects/timeout/target/TEST-COMPLETED", 20000 );
waitForTaskDead( 10000 );
}
private void waitForFile( String file, int max )
throws InterruptedException
{
long time = System.currentTimeMillis();
for ( int i = 0; i < max / 10; i++ )
{
if ( getTestFile( file ).exists() )
{
break;
}
Thread.sleep( 10 );
}
System.err.println( "Waited " + ( System.currentTimeMillis() - time ) + "ms for file " + file );
assertTrue( "File " + file, getTestFile( file ).exists() );
}
private void waitForTaskDead( int maxWait )
throws InterruptedException
{
for ( int i = 0; i < maxWait / 10; i++ )
{
if ( taskQueueExecutor.getCurrentTask() == null )
{
break;
}
Thread.sleep( 10 );
}
assertNull( "No current task", taskQueueExecutor.getCurrentTask() );
}
/**
* Runs the timeout test project through the build queue and return when the unit test in it has started. The
* project contains a unit test that sleeps for 15 seconds.
*
* @param maxRunTime maximum time the build may run before it's auto cancelled; 0 means forever.
* @return
* @throws Exception
*/
private BuildProjectTask runTimeoutProject( int maxRunTime )
throws Exception
{
BuildProjectTask task = createTask( maxRunTime );
FileSystemManager fsManager = getFileSystemManager();
fsManager.delete( getTestFile( "src/test-projects/timeout/target/TEST-STARTED" ) );
fsManager.delete( getTestFile( "src/test-projects/timeout/target/TEST-COMPLETED" ) );
System.err.println( "Queueing build" );
this.buildQueue.put( task );
System.err.println( "Waiting for task to start" );
Task curTask;
// Sleep at most 10 seconds for the task to start
for ( int i = 0; i < 1000; i++ )
{
curTask = taskQueueExecutor.getCurrentTask();
if ( curTask != null )
{
break;
}
Thread.sleep( 10 );
}
assertNotNull( "Task not started", task );
// wait for the start file to be written
waitForFile( "src/test-projects/timeout/target/TEST-STARTED", 10000 );
System.err.println( "Task started, TEST-STARTED file created." );
return task;
}
private BuildProjectTask createTask( int maxRunTime )
throws Exception
{
ProjectGroup projectGroup = getProjectGroup( "src/test-projects/timeout/pom.xml" );
Project project = projectGroup.getProjects().get( 0 );
BuildDefinition buildDefinition = new BuildDefinition();
buildDefinition.setId( 0 );
buildDefinition.setGoals( "install" );
projectGroup.addBuildDefinition( buildDefinition );
Map<String, Object> pgContext = new HashMap<String, Object>();
AbstractContinuumAction.setWorkingDirectory( pgContext, project.getWorkingDirectory() );
AbstractContinuumAction.setUnvalidatedProjectGroup( pgContext, projectGroup );
actionManager.lookup( "validate-project-group" ).execute( pgContext );
actionManager.lookup( "store-project-group" ).execute( pgContext );
int projectGroupId = AbstractContinuumAction.getProjectGroupId( pgContext );
projectGroup = getProjectGroupDao().getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId );
project = projectGroup.getProjects().get( 0 );
buildDefinition = projectGroup.getBuildDefinitions().get( 0 );
BuildProjectTask task = new BuildProjectTask( project.getId(), buildDefinition.getId(),
new BuildTrigger( 0, "" ),
project.getName(), buildDefinition.getDescription(), null,
projectGroupId );
task.setMaxExecutionTime( maxRunTime );
return task;
}
private ProjectGroup getProjectGroup( String pomResource )
throws ContinuumProjectBuilderException, IOException
{
File pom = getTestFile( pomResource );
assertNotNull( "Can't find project " + pomResource, pom );
ContinuumProjectBuildingResult result = projectBuilder.buildProjectsFromMetadata( pom.toURL(), null, null );
// some assertions to make sure our expectations match. This is NOT
// meant as a unit test for the projectbuilder!
assertNotNull( "Project list not null", result.getProjects() );
assertEquals( "#Projectgroups", 1, result.getProjectGroups().size() );
ProjectGroup pg = result.getProjectGroups().get( 0 );
// If the next part fails, remove this code! Then result.getProjects
// might be empty, and result.projectgroups[0].getProjects contains
// the single project!
assertEquals( "#Projects in result", 1, result.getProjects().size() );
Project p = result.getProjects().get( 0 );
pg.addProject( p );
p.setWorkingDirectory( pom.getParent() );
return pg;
}
}
| 5,041 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/AbstractAddProjectTest.java | package org.apache.continuum;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.utils.m2.LocalRepositoryHelper;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.execution.SettingsConfigurationException;
import java.io.File;
import java.io.IOException;
public abstract class AbstractAddProjectTest
extends AbstractContinuumTest
{
private static void mkdirs( File directory )
throws IOException
{
if ( !directory.exists() && !directory.mkdirs() )
{
throw new IOException( "Unable to create repository " + directory );
}
}
protected void createLocalRepository()
throws IOException, SettingsConfigurationException
{
LocalRepositoryHelper helper = lookup( LocalRepositoryHelper.class );
ArtifactRepository repo = helper.getLocalRepository();
File localRepo = new File( repo.getBasedir() );
mkdirs( localRepo );
File artifact = new File( localRepo,
"org/apache/maven/continuum/continuum-parent/1.0.3/continuum-parent-1.0.3.pom" );
mkdirs( artifact.getParentFile() );
getFileSystemManager().copyFile( getTestFile( "src/test/resources/projects/continuum/pom.xml" ), artifact );
}
}
| 5,042 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/taskqueue/DefaultOverallBuildQueueTest.java | package org.apache.continuum.taskqueue;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.taskqueueexecutor.ParallelBuildsThreadedTaskQueueExecutor;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* DefaultOverallBuildQueueTest
*
* @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
*/
public class DefaultOverallBuildQueueTest
extends PlexusSpringTestCase
{
private DefaultOverallBuildQueue overallQueue;
private BuildDefinitionDao buildDefinitionDao;
private ParallelBuildsThreadedTaskQueueExecutor buildTaskQueueExecutor;
private ParallelBuildsThreadedTaskQueueExecutor checkoutTaskQueueExecutor;
private ParallelBuildsThreadedTaskQueueExecutor prepareBuildTaskQueueExecutor;
@Before
public void setUp()
throws Exception
{
overallQueue = new DefaultOverallBuildQueue();
buildDefinitionDao = mock( BuildDefinitionDao.class );
buildTaskQueueExecutor = mock( ParallelBuildsThreadedTaskQueueExecutor.class, "build-queue-executor" );
checkoutTaskQueueExecutor = mock( ParallelBuildsThreadedTaskQueueExecutor.class, "checkout-queue-executor" );
prepareBuildTaskQueueExecutor = mock( ParallelBuildsThreadedTaskQueueExecutor.class,
"prepare-build-queue-executor" );
overallQueue.setBuildDefinitionDao( buildDefinitionDao );
overallQueue.setBuildTaskQueueExecutor( buildTaskQueueExecutor );
overallQueue.setCheckoutTaskQueueExecutor( checkoutTaskQueueExecutor );
overallQueue.setPrepareBuildTaskQueueExecutor( prepareBuildTaskQueueExecutor );
}
// checkout queue
@Test
public void testAddToCheckoutQueue()
throws Exception
{
CheckOutTask checkoutTask = new CheckOutTask( 1, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-1", "dummy", "dummypass", null,
null );
TaskQueue checkoutQueue = mock( TaskQueue.class, "checkout-queue" );
when( checkoutTaskQueueExecutor.getQueue() ).thenReturn( checkoutQueue );
overallQueue.addToCheckoutQueue( checkoutTask );
verify( checkoutQueue ).put( checkoutTask );
}
@Test
public void testGetProjectsInCheckoutQueue()
throws Exception
{
TaskQueue checkoutQueue = mock( TaskQueue.class, "checkout-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new CheckOutTask( 1, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-1", "dummy", "dummypass", null, null ) );
when( checkoutTaskQueueExecutor.getQueue() ).thenReturn( checkoutQueue );
when( checkoutQueue.getQueueSnapshot() ).thenReturn( tasks );
List<CheckOutTask> returnedTasks = overallQueue.getProjectsInCheckoutQueue();
assertNotNull( returnedTasks );
assertEquals( 1, returnedTasks.size() );
}
@Test
public void testIsInCheckoutQueue()
throws Exception
{
TaskQueue checkoutQueue = mock( TaskQueue.class, "checkout-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new CheckOutTask( 1, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-1", "dummy", "dummypass", null, null ) );
when( checkoutTaskQueueExecutor.getQueue() ).thenReturn( checkoutQueue );
when( checkoutQueue.getQueueSnapshot() ).thenReturn( tasks );
assertTrue( overallQueue.isInCheckoutQueue( 1 ) );
}
@Test
public void testRemoveProjectFromCheckoutQueue()
throws Exception
{
Task checkoutTask = new CheckOutTask( 1, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-1", "dummy", "dummypass", null, null );
TaskQueue checkoutQueue = mock( TaskQueue.class, "checkout-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( checkoutTask );
when( checkoutTaskQueueExecutor.getQueue() ).thenReturn( checkoutQueue );
when( checkoutQueue.getQueueSnapshot() ).thenReturn( tasks );
overallQueue.removeProjectFromCheckoutQueue( 1 );
verify( checkoutQueue ).remove( checkoutTask );
}
// build queue
@Test
public void testAddToBuildQueue()
throws Exception
{
BuildProjectTask buildTask = new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ),
"continuum-project-test-2", "BUILD_DEF", null, 2 );
TaskQueue buildQueue = mock( TaskQueue.class, "build-queue" );
when( buildTaskQueueExecutor.getQueue() ).thenReturn( buildQueue );
overallQueue.addToBuildQueue( buildTask );
verify( buildQueue ).put( buildTask );
}
@Test
public void testGetProjectsFromBuildQueue()
throws Exception
{
TaskQueue buildQueue = mock( TaskQueue.class, "build-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ), "continuum-project-test-2",
"BUILD_DEF", null, 2 ) );
when( buildTaskQueueExecutor.getQueue() ).thenReturn( buildQueue );
when( buildQueue.getQueueSnapshot() ).thenReturn( tasks );
List<BuildProjectTask> returnedTasks = overallQueue.getProjectsInBuildQueue();
assertNotNull( returnedTasks );
assertEquals( 1, returnedTasks.size() );
}
@Test
public void testIsInBuildQueue()
throws Exception
{
TaskQueue buildQueue = mock( TaskQueue.class, "build-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ), "continuum-project-test-2",
"BUILD_DEF", null, 2 ) );
when( buildTaskQueueExecutor.getQueue() ).thenReturn( buildQueue );
when( buildQueue.getQueueSnapshot() ).thenReturn( tasks );
assertTrue( overallQueue.isInBuildQueue( 2 ) );
}
@Test
public void testCancelBuildTask()
throws Exception
{
Task buildTask = new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ),
"continuum-project-test-2", "BUILD_DEF", null, 2 );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( buildTask );
overallQueue.cancelBuildTask( 2 );
verify( buildTaskQueueExecutor ).cancelTask( buildTask );
}
@Test
public void testCancelCurrentBuild()
throws Exception
{
Task buildTask = new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ),
"continuum-project-test-2", "BUILD_DEF", null, 2 );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( buildTask );
overallQueue.cancelCurrentBuild();
verify( buildTaskQueueExecutor ).cancelTask( buildTask );
}
@Test
public void testRemoveProjectFromBuildQueueWithGivenBuildDefinition()
throws Exception
{
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setDescription( "Test build definition" );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( buildDef );
TaskQueue buildQueue = mock( TaskQueue.class, "build-queue" );
when( buildTaskQueueExecutor.getQueue() ).thenReturn( buildQueue );
overallQueue.removeProjectFromBuildQueue( 1, 1, new BuildTrigger( 1, "test-user" ), "continuum-project-test-1",
1 );
verify( buildQueue ).remove( any( Task.class ) );
}
@Test
public void testRemoveProjectFromBuildQueue()
throws Exception
{
TaskQueue buildQueue = mock( TaskQueue.class, "build-queue" );
when( buildTaskQueueExecutor.getQueue() ).thenReturn( buildQueue );
Task buildTask = new BuildProjectTask( 1, 1, new BuildTrigger( 1, "test-user" ),
"continuum-project-test-2", "BUILD_DEF", null, 1 );
List<Task> tasks = new ArrayList<Task>();
tasks.add( buildTask );
when( buildQueue.getQueueSnapshot() ).thenReturn( tasks );
overallQueue.removeProjectFromBuildQueue( 1 );
verify( buildQueue ).remove( buildTask );
}
// prepare build queue
@Test
public void testAddToPrepareBuildQueue()
throws Exception
{
PrepareBuildProjectsTask prepareBuildTask = new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(),
new BuildTrigger( 1,
"test-user" ),
1, "Project Group A",
"http://scmRootAddress", 1 );
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
overallQueue.addToPrepareBuildQueue( prepareBuildTask );
verify( prepareBuildQueue ).put( prepareBuildTask );
}
@Test
public void testCancelCurrentPrepareBuild()
throws Exception
{
Task prepareBuildTask = new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(),
new BuildTrigger( 1, "test-user" ), 1,
"Project Group A", "http://scm.root.address", 1 );
when( prepareBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( prepareBuildTask );
overallQueue.cancelCurrentPrepareBuild();
verify( prepareBuildTaskQueueExecutor ).cancelTask( prepareBuildTask );
}
@Test
public void testCancelPrepareBuildTaskByProject()
throws Exception
{
Map<Integer, Integer> buildDefMap = new HashMap<Integer, Integer>();
buildDefMap.put( 1, 1 );
Task prepareBuildTask = new PrepareBuildProjectsTask( buildDefMap, new BuildTrigger( 1, "test-user" ), 1,
"Project Group A", "http://scm.root.address", 1 );
when( prepareBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( prepareBuildTask );
overallQueue.cancelPrepareBuildTask( 1 );
verify( prepareBuildTaskQueueExecutor ).cancelTask( prepareBuildTask );
}
@Test
public void testCancelPrepareBuildTaskByProjectGroup()
throws Exception
{
Map<Integer, Integer> buildDefMap = new HashMap<Integer, Integer>();
buildDefMap.put( 1, 1 );
Task prepareBuildTask = new PrepareBuildProjectsTask( buildDefMap, new BuildTrigger( 1, "test-user" ), 1,
"Project Group A", "http://scm.root.address", 2 );
when( prepareBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( prepareBuildTask );
overallQueue.cancelPrepareBuildTask( 1, 2 );
verify( prepareBuildTaskQueueExecutor ).cancelTask( prepareBuildTask );
}
@Test
public void testGetProjectsFromPrepareBuildQueue()
throws Exception
{
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(), new BuildTrigger( 1, "test-user" ), 2,
"Project Group A", "http://scm.root.address", 2 ) );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
List<PrepareBuildProjectsTask> returnedTasks = overallQueue.getProjectsInPrepareBuildQueue();
assertNotNull( returnedTasks );
assertEquals( 1, returnedTasks.size() );
}
@Test
public void testIsInPrepareBuildQueueByProject()
throws Exception
{
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
Map<Integer, Integer> buildDefMap = new HashMap<Integer, Integer>();
buildDefMap.put( 2, 1 );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new PrepareBuildProjectsTask( buildDefMap, new BuildTrigger( 1, "test-user" ), 1, "Project Group A",
"http://scm.root.address", 2 ) );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
assertTrue( overallQueue.isInPrepareBuildQueue( 2 ) );
}
@Test
public void testIsInPrepareBuildQueueByProjectGroupAndScmRootId()
throws Exception
{
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
Map<Integer, Integer> buildDefMap = new HashMap<Integer, Integer>();
buildDefMap.put( 2, 1 );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new PrepareBuildProjectsTask( buildDefMap, new BuildTrigger( 1, "test-user" ), 1, "Project Group A",
"http://scm.root.address", 2 ) );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
assertTrue( overallQueue.isInPrepareBuildQueue( 1, 2 ) );
}
@Test
public void testIsInPrepareBuildQueueByProjectGroupAndScmRootAddress()
throws Exception
{
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put( 2, 1 );
List<Task> tasks = new ArrayList<Task>();
tasks.add( new PrepareBuildProjectsTask( map, new BuildTrigger( 1, "test-user" ), 1, "Project Group A",
"http://scm.root.address", 2 ) );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
assertTrue( overallQueue.isInPrepareBuildQueue( 1, "http://scm.root.address" ) );
}
@Test
public void testRemoveProjectsFromPrepareBuildQueueByProjectGroupAndScmRootId()
throws Exception
{
Task prepareBuildTask = new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(), new BuildTrigger(
1, "test-user" ), 1, "Project Group A", "http://scm.root.address", 1 );
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( prepareBuildTask );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
overallQueue.removeProjectFromPrepareBuildQueue( 1, 1 );
verify( prepareBuildQueue ).remove( prepareBuildTask );
}
@Test
public void testRemoveProjectsFromPrepareBuildQueueByProjectGroupAndScmRootAddress()
throws Exception
{
Task prepareBuildTask = new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(), new BuildTrigger(
1, "test-user" ), 1, "Project Group A", "http://scm.root.address", 1 );
TaskQueue prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
List<Task> tasks = new ArrayList<Task>();
tasks.add( prepareBuildTask );
when( prepareBuildTaskQueueExecutor.getQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
overallQueue.removeProjectFromPrepareBuildQueue( 1, "http://scm.root.address" );
verify( prepareBuildQueue ).remove( prepareBuildTask );
}
}
| 5,043 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/repository/DefaultRepositoryServiceTest.java | package org.apache.continuum.repository;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.RepositoryPurgeConfigurationDao;
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.model.repository.RepositoryPurgeConfiguration;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/**
* @author Maria Catherine Tan
* @since 25 jul 07
*/
public class DefaultRepositoryServiceTest
extends AbstractContinuumTest
{
private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao;
private RepositoryService repositoryService;
private LocalRepository repository;
@Before
public void setUp()
throws Exception
{
repositoryPurgeConfigurationDao = lookup( RepositoryPurgeConfigurationDao.class );
repositoryService = lookup( RepositoryService.class );
setupDefaultRepository();
}
@Test
public void testRemoveRepository()
throws Exception
{
repositoryService.removeLocalRepository( repository.getId() );
List<LocalRepository> repositories = repositoryService.getAllLocalRepositories();
assertEquals( "check # repositories", 0, repositories.size() );
ProjectGroup group = getDefaultProjectGroup();
assertNull( group.getLocalRepository() );
List<RepositoryPurgeConfiguration> purgeConfigs =
repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsByLocalRepository( repository.getId() );
assertEquals( "check # purge configs of repository", 0, purgeConfigs.size() );
}
private void setupDefaultRepository()
throws Exception
{
repository = new LocalRepository();
repository.setName( "DefaultRepo" );
repository.setLocation( getTestFile( "target/default-repo" ).getAbsolutePath() );
repository = repositoryService.addLocalRepository( repository );
ProjectGroup group = getDefaultProjectGroup();
group.setLocalRepository( repository );
getProjectGroupDao().updateProjectGroup( group );
RepositoryPurgeConfiguration repoConfig = new RepositoryPurgeConfiguration();
repoConfig.setRepository( repository );
repoConfig = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoConfig );
List<LocalRepository> repositories = repositoryService.getAllLocalRepositories();
assertEquals( "check # repositories", 1, repositories.size() );
assertTrue( "check if repository was added", repositories.contains( repository ) );
LocalRepository repo = repositoryService.getLocalRepositoryByName( "DefaultRepo" );
assertNotNull( repo );
assertEquals( "check if repository name is the same", repository.getName(), repo.getName() );
repo = repositoryService.getLocalRepositoryByLocation( repository.getLocation() );
assertNotNull( repo );
assertEquals( "check if repository location is the same", repository.getLocation(), repo.getLocation() );
ProjectGroup retrievedGroup = getDefaultProjectGroup();
assertNotNull( retrievedGroup.getLocalRepository() );
assertEquals( "check if repository is the same", repository, retrievedGroup.getLocalRepository() );
List<RepositoryPurgeConfiguration> purgeConfigs =
repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsByLocalRepository( repository.getId() );
assertEquals( "check # purge configs found", 1, purgeConfigs.size() );
assertEquals( "check if purge configuration is the same", repoConfig, purgeConfigs.get( 0 ) );
}
} | 5,044 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/notification | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/notification/mail/MockJavaMailSender.java | package org.apache.continuum.notification.mail;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.ArrayList;
import java.util.List;
import javax.mail.internet.MimeMessage;
/**
* @author <a href="mailto:olamy@apache.org">olamy</a>
* @since 26 sept. 2008
*/
public class MockJavaMailSender
extends JavaMailSenderImpl
implements JavaMailSender
{
private final List<MimeMessage> receivedEmails = new ArrayList<MimeMessage>();
/**
*
*/
public MockJavaMailSender()
{
}
@Override
public void send( MimeMessage mimeMessage )
throws MailException
{
receivedEmails.add( mimeMessage );
}
public List<MimeMessage> getReceivedEmails()
{
return receivedEmails;
}
}
| 5,045 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/release/distributed | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/release/distributed/manager/DefaultDistributedReleaseManagerTest.java | package org.apache.continuum.release.distributed.manager;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildResultDao;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.apache.maven.continuum.model.project.BuildResult;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* DefaultDistributedReleaseManagerTest
*/
public class DefaultDistributedReleaseManagerTest
extends PlexusSpringTestCase
{
private DefaultDistributedReleaseManager distributedReleaseManager;
private BuildResultDao buildResultDao;
@Before
public void setUp()
throws Exception
{
distributedReleaseManager = new DefaultDistributedReleaseManager();
buildResultDao = mock( BuildResultDao.class );
distributedReleaseManager.setBuildResultDao( buildResultDao );
}
@Test
public void testGetDefaultBuildagent()
throws Exception
{
String defaultBuildagentUrl = "http://localhost:8181/continuum-buildagent/xmlrpc";
BuildResult buildResult = new BuildResult();
buildResult.setBuildUrl( defaultBuildagentUrl );
when( buildResultDao.getLatestBuildResultForProject( 0 ) ).thenReturn( buildResult );
String returnedBuildagent = distributedReleaseManager.getDefaultBuildagent( 0 );
assertNotNull( returnedBuildagent );
assertEquals( returnedBuildagent, defaultBuildagentUrl );
}
@Test
public void testGetDefaultBuildagentNullBuildResult()
throws Exception
{
BuildResult buildResult = null;
when( buildResultDao.getLatestBuildResultForProject( 0 ) ).thenReturn( buildResult );
String returnedBuildagent = distributedReleaseManager.getDefaultBuildagent( 0 );
assertNull( returnedBuildagent );
}
}
| 5,046 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/AbstractPurgeTest.java | package org.apache.continuum.purge;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.DaoUtils;
import org.apache.continuum.dao.DirectoryPurgeConfigurationDao;
import org.apache.continuum.dao.DistributedDirectoryPurgeConfigurationDao;
import org.apache.continuum.dao.LocalRepositoryDao;
import org.apache.continuum.dao.RepositoryPurgeConfigurationDao;
import org.apache.continuum.model.repository.DirectoryPurgeConfiguration;
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.model.repository.RepositoryPurgeConfiguration;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.apache.maven.continuum.jdo.MemoryJdoFactory;
import org.codehaus.plexus.jdo.JdoFactory;
import org.jpox.SchemaTool;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.io.File;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Maria Catherine Tan
*/
public abstract class AbstractPurgeTest
extends PlexusSpringTestCase
{
private static final String TEST_DEFAULT_REPO_DIR = "target/default-repository";
private static final String TEST_DEFAULT_REPO_NAME = "defaultRepo";
private static final String TEST_DEFAULT_RELEASES_DIR = "target/working-directory";
private static final String TEST_DEFAULT_BUILDOUTPUT_DIR = "target/build-output-directory";
protected static final String TEST_BUILD_AGENT_URL = "http://localhost:8181/continuum-buildagent/xmlrpc";
protected static final int TEST_DAYS_OLDER = 30;
protected static final int TEST_RETENTION_COUNT = 2;
protected static final String TEST_RELEASES_DIRECTORY_TYPE = "releases";
protected static final String TEST_BUILDOUTPUT_DIRECTORY_TYPE = "buildOutput";
protected static final String TEST_WORKING_DIRECTORY_TYPE = "working";
protected LocalRepositoryDao localRepositoryDao;
protected DirectoryPurgeConfigurationDao directoryPurgeConfigurationDao;
protected RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao;
protected DistributedDirectoryPurgeConfigurationDao distributedDirectoryPurgeConfigurationDao;
protected RepositoryPurgeConfiguration defaultRepoPurge;
protected DirectoryPurgeConfiguration defaultReleasesDirPurge;
protected DirectoryPurgeConfiguration defaultBuildOutputDirPurge;
protected LocalRepository defaultRepository;
@Rule
public TestName testName = new TestName();
protected String getName()
{
return testName.getMethodName();
}
@Before
public void createInitialSetup()
throws Exception
{
init();
localRepositoryDao = lookup( LocalRepositoryDao.class );
repositoryPurgeConfigurationDao = lookup( RepositoryPurgeConfigurationDao.class );
directoryPurgeConfigurationDao = lookup( DirectoryPurgeConfigurationDao.class );
distributedDirectoryPurgeConfigurationDao = lookup( DistributedDirectoryPurgeConfigurationDao.class );
if ( localRepositoryDao.getAllLocalRepositories().size() == 0 )
{
createDefaultRepository();
assertEquals( "check # repository", 1, localRepositoryDao.getAllLocalRepositories().size() );
createDefaultRepoPurgeConfiguration();
}
else
{
assertEquals( "check # repository", 1, localRepositoryDao.getAllLocalRepositories().size() );
defaultRepository = localRepositoryDao.getLocalRepositoryByName( TEST_DEFAULT_REPO_NAME );
defaultRepoPurge = repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsByLocalRepository(
defaultRepository.getId() ).get( 0 );
}
if ( directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsByType(
TEST_RELEASES_DIRECTORY_TYPE ).size() == 0 )
{
createDefaultReleasesDirPurgeConfiguration();
}
else
{
defaultReleasesDirPurge = directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsByType(
TEST_RELEASES_DIRECTORY_TYPE ).get( 0 );
}
if ( directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsByType(
TEST_BUILDOUTPUT_DIRECTORY_TYPE ).size() == 0 )
{
createDefaultBuildOutputDirPurgeConfiguration();
}
else
{
defaultBuildOutputDirPurge = directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsByType(
TEST_BUILDOUTPUT_DIRECTORY_TYPE ).get( 0 );
}
}
@After
public void wipeTestData()
{
lookup( DaoUtils.class ).eraseDatabase();
}
protected void init()
throws Exception
{
// ----------------------------------------------------------------------
// Set up the JDO factory
// ----------------------------------------------------------------------
MemoryJdoFactory jdoFactory = (MemoryJdoFactory) lookup( JdoFactory.class, "continuum" );
assertEquals( MemoryJdoFactory.class.getName(), jdoFactory.getClass().getName() );
String url = "jdbc:hsqldb:mem:" + getClass().getName() + "." + getName();
jdoFactory.setUrl( url );
jdoFactory.reconfigure();
// ----------------------------------------------------------------------
// Check the configuration
// ----------------------------------------------------------------------
PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
assertNotNull( pmf );
assertEquals( url, pmf.getConnectionURL() );
PersistenceManager pm = pmf.getPersistenceManager();
pm.close();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
Properties properties = jdoFactory.getProperties();
for ( Map.Entry entry : properties.entrySet() )
{
System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
}
SchemaTool.createSchemaTables( new URL[] { getClass().getResource( "/package.jdo" ) }, new URL[] {}, null,
false,
null );
lookup( DaoUtils.class ).rebuildStore();
}
protected File getDefaultRepositoryLocation()
{
File repositoryLocation = getTestFile( TEST_DEFAULT_REPO_DIR );
if ( !repositoryLocation.exists() )
{
repositoryLocation.mkdirs();
}
return repositoryLocation;
}
protected File getReleasesDirectoryLocation()
{
File releasesDirectory = getTestFile( TEST_DEFAULT_RELEASES_DIR );
if ( !releasesDirectory.exists() )
{
releasesDirectory.mkdirs();
}
return releasesDirectory;
}
protected File getBuildOutputDirectoryLocation()
{
File buildOutputDir = getTestFile( TEST_DEFAULT_BUILDOUTPUT_DIR );
if ( !buildOutputDir.exists() )
{
buildOutputDir.mkdirs();
}
return buildOutputDir;
}
private void createDefaultRepository()
throws Exception
{
defaultRepository = localRepositoryDao.getLocalRepositoryByName( TEST_DEFAULT_REPO_NAME );
if ( defaultRepository == null )
{
LocalRepository repository = new LocalRepository();
repository.setName( TEST_DEFAULT_REPO_NAME );
repository.setLocation( getDefaultRepositoryLocation().getAbsolutePath() );
defaultRepository = localRepositoryDao.addLocalRepository( repository );
}
}
private void createDefaultRepoPurgeConfiguration()
throws Exception
{
RepositoryPurgeConfiguration repoPurge = new RepositoryPurgeConfiguration();
repoPurge.setRepository( defaultRepository );
repoPurge.setDeleteAll( true );
defaultRepoPurge = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoPurge );
}
private void createDefaultReleasesDirPurgeConfiguration()
throws Exception
{
DirectoryPurgeConfiguration dirPurge = new DirectoryPurgeConfiguration();
dirPurge.setLocation( getReleasesDirectoryLocation().getAbsolutePath() );
dirPurge.setDirectoryType( "releases" );
dirPurge.setDeleteAll( true );
defaultReleasesDirPurge = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirPurge );
}
private void createDefaultBuildOutputDirPurgeConfiguration()
throws Exception
{
DirectoryPurgeConfiguration dirPurge = new DirectoryPurgeConfiguration();
dirPurge.setLocation( getBuildOutputDirectoryLocation().getAbsolutePath() );
dirPurge.setDirectoryType( "buildOutput" );
dirPurge.setDeleteAll( true );
defaultBuildOutputDirPurge = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirPurge );
}
}
| 5,047 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/DefaultContinuumPurgeManagerTest.java | package org.apache.continuum.purge;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.DirectoryPurgeConfigurationDao;
import org.apache.continuum.dao.DistributedDirectoryPurgeConfigurationDao;
import org.apache.continuum.dao.LocalRepositoryDao;
import org.apache.continuum.dao.RepositoryPurgeConfigurationDao;
import org.apache.continuum.model.repository.DirectoryPurgeConfiguration;
import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration;
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.model.repository.RepositoryPurgeConfiguration;
import org.apache.continuum.purge.task.PurgeTask;
import org.apache.continuum.taskqueue.manager.TaskQueueManager;
import org.apache.maven.continuum.AbstractContinuumTest;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Maria Catherine Tan
* @since 25 jul 07
*/
public class DefaultContinuumPurgeManagerTest
extends AbstractContinuumTest
{
private LocalRepositoryDao localRepositoryDao;
private DirectoryPurgeConfigurationDao directoryPurgeConfigurationDao;
private DistributedDirectoryPurgeConfigurationDao distributedDirectoryPurgeConfigurationDao;
private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao;
private ContinuumPurgeManager purgeManager;
private TaskQueue purgeQueue;
private RepositoryPurgeConfiguration repoPurge;
private DirectoryPurgeConfiguration dirPurge;
private DistributedDirectoryPurgeConfiguration distDirPurge;
private TaskQueueManager taskQueueManager;
@Before
public void setUp()
throws Exception
{
localRepositoryDao = lookup( LocalRepositoryDao.class );
directoryPurgeConfigurationDao = lookup( DirectoryPurgeConfigurationDao.class );
repositoryPurgeConfigurationDao = lookup( RepositoryPurgeConfigurationDao.class );
distributedDirectoryPurgeConfigurationDao = lookup( DistributedDirectoryPurgeConfigurationDao.class );
purgeManager = lookup( ContinuumPurgeManager.class );
purgeQueue = lookup( TaskQueue.class, "purge" );
taskQueueManager = lookup( TaskQueueManager.class );
setupDefaultPurgeConfigurations();
}
@Test
public void testPurgingWithSinglePurgeConfiguration()
throws Exception
{
purgeManager.purgeRepository( repoPurge );
assertNextBuildIs( repoPurge.getId() );
assertNextBuildIsNull();
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeRepository( repoPurge );
assertNextBuildIs( repoPurge.getId() );
assertNextBuildIsNull();
}
@Test
public void testPurgingWithMultiplePurgeConfiguration()
throws Exception
{
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeDirectory( dirPurge );
assertNextBuildIs( repoPurge.getId() );
assertNextBuildIs( dirPurge.getId() );
assertNextBuildIsNull();
for ( int i = 0; i < 5; i++ )
{
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeDirectory( dirPurge );
}
assertNextBuildIs( repoPurge.getId() );
assertNextBuildIs( dirPurge.getId() );
assertNextBuildIsNull();
}
@Test
public void testRemoveFromPurgeQueue()
throws Exception
{
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeDirectory( dirPurge );
purgeManager.purgeDistributedDirectory( distDirPurge );
assertNextBuildIs( repoPurge.getId() );
assertNextBuildIs( dirPurge.getId() );
assertNextBuildIs( distDirPurge.getId() );
assertNextBuildIsNull();
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeDirectory( dirPurge );
taskQueueManager.removeFromPurgeQueue( repoPurge.getId() );
assertNextBuildIs( dirPurge.getId() );
assertNextBuildIsNull();
purgeManager.purgeRepository( repoPurge );
purgeManager.purgeDirectory( dirPurge );
taskQueueManager.removeFromPurgeQueue( dirPurge.getId() );
assertNextBuildIs( repoPurge.getId() );
assertNextBuildIsNull();
}
private void setupDefaultPurgeConfigurations()
throws Exception
{
LocalRepository repository = new LocalRepository();
repository.setName( "defaultRepo" );
repository.setLocation( getTestFile( "target/default-repository" ).getAbsolutePath() );
repository = localRepositoryDao.addLocalRepository( repository );
repoPurge = new RepositoryPurgeConfiguration();
repoPurge.setRepository( repository );
repoPurge = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoPurge );
dirPurge = new DirectoryPurgeConfiguration();
dirPurge.setDirectoryType( "releases" );
dirPurge.setLocation( getTestFile( "target/working-directory" ).getAbsolutePath() );
dirPurge = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirPurge );
distDirPurge = new DistributedDirectoryPurgeConfiguration();
distDirPurge.setDirectoryType( "releases" );
distDirPurge.setBuildAgentUrl( "http://localhost:8186/continuum-buildagent/xmlrpc" );
distDirPurge = distributedDirectoryPurgeConfigurationDao.addDistributedDirectoryPurgeConfiguration(
distDirPurge );
}
private void assertNextBuildIs( int expectedPurgeConfigId )
throws Exception
{
Task task = purgeQueue.take();
assertEquals( PurgeTask.class.getName(), task.getClass().getName() );
PurgeTask purgeTask = (PurgeTask) task;
assertEquals( "Didn't get the expected purge config id.", expectedPurgeConfigId,
purgeTask.getPurgeConfigurationId() );
}
private void assertNextBuildIsNull()
throws Exception
{
Task task = purgeQueue.take();
if ( task != null )
{
fail( "Got a non-null purge task returned. Purge Config id: " +
( (PurgeTask) task ).getPurgeConfigurationId() );
}
}
} | 5,048 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/DefaultPurgeConfigurationServiceTest.java | package org.apache.continuum.purge;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.model.repository.DirectoryPurgeConfiguration;
import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration;
import org.apache.continuum.model.repository.RepositoryPurgeConfiguration;
import org.apache.continuum.purge.repository.content.ManagedDefaultRepositoryContent;
import org.apache.continuum.purge.repository.content.RepositoryManagedContent;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/**
* @author Maria Catherine Tan
*/
public class DefaultPurgeConfigurationServiceTest
extends AbstractPurgeTest
{
private PurgeConfigurationService purgeConfigurationService;
@Before
public void setUp()
throws Exception
{
purgeConfigurationService = (PurgeConfigurationService) lookup( PurgeConfigurationService.ROLE );
}
@Test
public void testRepositoryPurgeConfiguration()
throws Exception
{
RepositoryPurgeConfiguration repoConfig = new RepositoryPurgeConfiguration();
repoConfig.setRepository( defaultRepository );
repoConfig.setDaysOlder( TEST_DAYS_OLDER );
repoConfig.setRetentionCount( TEST_RETENTION_COUNT );
repoConfig = purgeConfigurationService.addRepositoryPurgeConfiguration( repoConfig );
assertNotNull( repoConfig );
RepositoryPurgeConfiguration retrieved = repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration(
repoConfig.getId() );
assertEquals( repoConfig, retrieved );
purgeConfigurationService.removeRepositoryPurgeConfiguration( repoConfig );
List<RepositoryPurgeConfiguration> repoConfigs =
purgeConfigurationService.getAllRepositoryPurgeConfigurations();
assertFalse( "check if repo purge configuration was removed", repoConfigs.contains( repoConfig ) );
assertNotNull( "check if repository still exists", localRepositoryDao.getLocalRepository(
defaultRepository.getId() ) );
}
@Test
public void testDirectoryPurgeConfiguration()
throws Exception
{
DirectoryPurgeConfiguration dirConfig = new DirectoryPurgeConfiguration();
dirConfig.setLocation( getReleasesDirectoryLocation().getAbsolutePath() );
dirConfig.setDirectoryType( TEST_RELEASES_DIRECTORY_TYPE );
dirConfig.setDaysOlder( TEST_DAYS_OLDER );
dirConfig.setRetentionCount( TEST_RETENTION_COUNT );
dirConfig = purgeConfigurationService.addDirectoryPurgeConfiguration( dirConfig );
assertNotNull( dirConfig );
DirectoryPurgeConfiguration retrieved = directoryPurgeConfigurationDao.getDirectoryPurgeConfiguration(
dirConfig.getId() );
assertEquals( dirConfig, retrieved );
dirConfig.setDirectoryType( TEST_BUILDOUTPUT_DIRECTORY_TYPE );
purgeConfigurationService.updateDirectoryPurgeConfiguration( dirConfig );
retrieved = directoryPurgeConfigurationDao.getDirectoryPurgeConfiguration( dirConfig.getId() );
assertEquals( dirConfig, retrieved );
purgeConfigurationService.removeDirectoryPurgeConfiguration( dirConfig );
List<DirectoryPurgeConfiguration> dirConfigs = purgeConfigurationService.getAllDirectoryPurgeConfigurations();
assertFalse( "check if dir purge configuration was removed", dirConfigs.contains( dirConfig ) );
}
@Test
public void testDistributedDirectoryPurgeConfiguration()
throws Exception
{
DistributedDirectoryPurgeConfiguration dirConfig = new DistributedDirectoryPurgeConfiguration();
dirConfig.setBuildAgentUrl( TEST_BUILD_AGENT_URL );
dirConfig.setDirectoryType( TEST_RELEASES_DIRECTORY_TYPE );
dirConfig.setDaysOlder( TEST_DAYS_OLDER );
dirConfig.setRetentionCount( TEST_RETENTION_COUNT );
dirConfig = purgeConfigurationService.addDistributedDirectoryPurgeConfiguration( dirConfig );
assertNotNull( dirConfig );
DistributedDirectoryPurgeConfiguration retrieved =
distributedDirectoryPurgeConfigurationDao.getDistributedDirectoryPurgeConfiguration( dirConfig.getId() );
assertEquals( dirConfig, retrieved );
dirConfig.setDirectoryType( TEST_WORKING_DIRECTORY_TYPE );
purgeConfigurationService.updateDistributedDirectoryPurgeConfiguration( dirConfig );
retrieved = distributedDirectoryPurgeConfigurationDao.getDistributedDirectoryPurgeConfiguration(
dirConfig.getId() );
assertEquals( dirConfig, retrieved );
purgeConfigurationService.removeDistributedDirectoryPurgeConfiguration( dirConfig );
List<DistributedDirectoryPurgeConfiguration> dirConfigs =
purgeConfigurationService.getAllDistributedDirectoryPurgeConfigurations();
assertFalse( "check if dir purge configuration was removed", dirConfigs.contains( dirConfig ) );
}
@Test
public void testRepositoryManagedContent()
throws Exception
{
RepositoryManagedContent repo = purgeConfigurationService.getManagedRepositoryContent(
defaultRepository.getId() );
assertTrue( "check repository managed content", ( repo instanceof ManagedDefaultRepositoryContent ) );
assertEquals( "check repository of the managed content", defaultRepository, repo.getRepository() );
}
}
| 5,049 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/ReleasedSnapshotsRepositoryPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Before;
import org.junit.Test;
/**
* Tests were taken from Archiva and added a check if metadata was deleted.
*/
public class ReleasedSnapshotsRepositoryPurgeExecutorTest
extends AbstractPurgeExecutorTest
{
@Before
public void setUp()
throws Exception
{
populateDefaultRepositoryForReleasedSnapshots();
purgeDefaultRepoTask = getReleasedSnapshotsRepoPurgeTask();
}
@Test
public void testDefaultRepoReleasedSnapshotsPurging()
throws Exception
{
String repoRoot = getDefaultRepositoryLocation().getAbsolutePath();
String projectRoot1 = repoRoot + "/org/apache/maven/plugins/maven-assembly-plugin";
String projectRoot2 = repoRoot + "/org/apache/maven/plugins/maven-install-plugin";
String projectRoot3 = repoRoot + "/org/apache/maven/plugins/maven-plugin-plugin";
purgeExecutor.executeTask( purgeDefaultRepoTask );
assertMetadataDeleted( projectRoot1 );
assertMetadataDeleted( projectRoot2 );
assertMetadataDeleted( projectRoot3 );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar.sha1" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar.md5" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom.sha1" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom.md5" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar.md5" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar.sha1" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom.md5" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom.sha1" );
// check if the snapshot version was removed
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT" );
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT/maven-plugin-plugin-2.3-SNAPSHOT.jar" );
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT/maven-plugin-plugin-2.3-SNAPSHOT.jar.md5" );
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT/maven-plugin-plugin-2.3-SNAPSHOT.jar.sha1" );
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT/maven-plugin-plugin-2.3-SNAPSHOT.pom" );
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT/maven-plugin-plugin-2.3-SNAPSHOT.pom.md5" );
assertDeleted( projectRoot3 + "/2.3-SNAPSHOT/maven-plugin-plugin-2.3-SNAPSHOT.pom.sha1" );
// check if the released version was not removed
assertExists( projectRoot3 + "/2.2" );
assertExists( projectRoot3 + "/2.2/maven-plugin-plugin-2.2.jar" );
assertExists( projectRoot3 + "/2.2/maven-plugin-plugin-2.2.jar.md5" );
assertExists( projectRoot3 + "/2.2/maven-plugin-plugin-2.2.jar.sha1" );
assertExists( projectRoot3 + "/2.2/maven-plugin-plugin-2.2.pom" );
assertExists( projectRoot3 + "/2.2/maven-plugin-plugin-2.2.pom.md5" );
assertExists( projectRoot3 + "/2.2/maven-plugin-plugin-2.2.pom.sha1" );
assertExists( projectRoot3 + "/2.3" );
assertExists( projectRoot3 + "/2.3/maven-plugin-plugin-2.3.jar" );
assertExists( projectRoot3 + "/2.3/maven-plugin-plugin-2.3.jar.md5" );
assertExists( projectRoot3 + "/2.3/maven-plugin-plugin-2.3.jar.sha1" );
assertExists( projectRoot3 + "/2.3/maven-plugin-plugin-2.3.pom" );
assertExists( projectRoot3 + "/2.3/maven-plugin-plugin-2.3.pom.md5" );
assertExists( projectRoot3 + "/2.3/maven-plugin-plugin-2.3.pom.sha1" );
}
}
| 5,050 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/RetentionCountRepositoryPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Before;
import org.junit.Test;
/**
* Tests were taken from Archiva and just added a check if the metadata was deleted.
*/
public class RetentionCountRepositoryPurgeExecutorTest
extends AbstractPurgeExecutorTest
{
@Before
public void setUp()
throws Exception
{
purgeDefaultRepoTask = getRetentionCountRepoPurgeTask();
}
@Test
public void testRetentionCountPurging()
throws Exception
{
populateDefaultRepositoryForRetentionCount();
String repoRoot = getDefaultRepositoryLocation().getAbsolutePath();
String projectRoot1 = repoRoot + "/org/jruby/plugins/jruby-rake-plugin";
String projectRoot2 = repoRoot + "/org/codehaus/castor/castor-anttasks";
purgeExecutor.executeTask( purgeDefaultRepoTask );
// assert if metadata was removed
assertMetadataDeleted( projectRoot1 );
assertMetadataDeleted( projectRoot2 );
// assert if removed from repo
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.153317-1.jar" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.153317-1.jar.md5" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.153317-1.jar.sha1" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.153317-1.pom" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.153317-1.pom.md5" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.153317-1.pom.sha1" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.160758-2.jar" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.160758-2.jar.md5" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.160758-2.jar.sha1" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.160758-2.pom" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.160758-2.pom.md5" );
assertDeleted( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070504.160758-2.pom.sha1" );
// assert if not removed from repo
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070505.090015-3.jar" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070505.090015-3.jar.md5" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070505.090015-3.jar.sha1" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070505.090015-3.pom" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070505.090015-3.pom.md5" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070505.090015-3.pom.sha1" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070506.090132-4.jar" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070506.090132-4.jar.md5" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070506.090132-4.jar.sha1" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070506.090132-4.pom" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070506.090132-4.pom.md5" );
assertExists( projectRoot1 + "/1.0RC1-SNAPSHOT/jruby-rake-plugin-1.0RC1-20070506.090132-4.pom.sha1" );
// assert if removed from repo
assertDeleted( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070427.065136-1.jar" );
assertDeleted( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070427.065136-1.jar.md5" );
assertDeleted( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070427.065136-1.jar.sha1" );
assertDeleted( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070427.065136-1.pom" );
assertDeleted( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070427.065136-1.pom.md5" );
assertDeleted( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070427.065136-1.pom.sha1" );
// assert if not removed from repo
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070615.105019-3.pom" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070615.105019-3.pom.md5" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070615.105019-3.pom.sha1" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070615.105019-3.jar" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070615.105019-3.jar.md5" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070615.105019-3.jar.sha1" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070506.163513-2.pom" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070506.163513-2.pom.md5" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070506.163513-2.pom.sha1" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070506.163513-2.jar" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070506.163513-2.jar.md5" );
assertExists( projectRoot2 + "/1.1.2-SNAPSHOT/castor-anttasks-1.1.2-20070506.163513-2.jar.sha1" );
}
@Test
public void testOrderOfDeletion()
throws Exception
{
populateDefaultRepository();
String repoRoot = getDefaultRepositoryLocation().getAbsolutePath();
String projectRoot1 = repoRoot + "/org/apache/maven/plugins/maven-assembly-plugin";
String projectRoot2 = repoRoot + "/org/apache/maven/plugins/maven-install-plugin";
purgeExecutor.executeTask( purgeDefaultRepoTask );
assertMetadataDeleted( projectRoot1 );
assertMetadataDeleted( projectRoot2 );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar.sha1" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar.md5" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom.sha1" );
assertDeleted( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar.md5" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom.sha1" );
assertExists( projectRoot1 + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom.md5" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar.md5" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar.sha1" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom.md5" );
assertDeleted( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar.sha1" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom.md5" );
assertExists( projectRoot2 + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom.sha1" );
}
}
| 5,051 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/CleanAllPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.maven.archiva.consumers.core.repository.ArtifactFilenameFilter;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import static org.junit.Assert.assertEquals;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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 Maria Catherine Tan
*/
public class CleanAllPurgeExecutorTest
extends AbstractPurgeExecutorTest
{
@Before
public void setUp()
throws Exception
{
purgeDefaultRepoTask = getCleanAllDefaultRepoPurgeTask();
purgeReleasesDirTask = getCleanAllReleasesDirPurgeTask();
purgeBuildOutputDirTask = getCleanAllBuildOutputDirPurgeTask();
}
@Test
public void testCleanAllRepositoryPurging()
throws Exception
{
populateDefaultRepository();
purgeExecutor.executeTask( purgeDefaultRepoTask );
assertIsEmpty( getDefaultRepositoryLocation() );
}
@Test
public void testCleanAllReleasesPurging()
throws Exception
{
populateReleasesDirectory();
File workingDir = getReleasesDirectoryLocation();
FilenameFilter filter = new ArtifactFilenameFilter( "releases-" );
File[] releasesDir = workingDir.listFiles( filter );
assertExists( workingDir.getAbsolutePath() + "/1" );
assertEquals( "check # of releases directory", 3, releasesDir.length );
purgeExecutor.executeTask( purgeReleasesDirTask );
// check if no releases dir
releasesDir = workingDir.listFiles( filter );
assertEquals( "releases directory must be empty", 0, releasesDir.length );
assertExists( workingDir.getAbsolutePath() + "/1" );
}
@Test
public void testCleanAllBuildOutputPurging()
throws Exception
{
populateBuildOutputDirectory();
File buildOutputDir = getBuildOutputDirectoryLocation();
purgeExecutor.executeTask( purgeBuildOutputDirTask );
FileFilter filter = DirectoryFileFilter.DIRECTORY;
File[] projectsDir = buildOutputDir.listFiles( filter );
for ( File projectDir : projectsDir )
{
assertIsEmpty( projectDir );
}
}
}
| 5,052 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/DaysOldRepositoryPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Before;
import org.junit.Test;
/**
* Tests were taken from Archiva and just added a check if the metadata was deleted.
*/
public class DaysOldRepositoryPurgeExecutorTest
extends AbstractPurgeExecutorTest
{
@Before
public void setUp()
throws Exception
{
populateDefaultRepository();
purgeDefaultRepoTask = getDaysOldRepoPurgeTask();
}
@Test
public void testDefaultRepoPurgingByLastModified()
throws Exception
{
String repoRoot = getDefaultRepositoryLocation().getAbsolutePath();
String projectRoot = repoRoot + "/org/apache/maven/plugins/maven-install-plugin";
setLastModified( projectRoot + "/2.2-SNAPSHOT/", 1179382029, true );
purgeExecutor.executeTask( purgeDefaultRepoTask );
assertMetadataDeleted( projectRoot );
assertDeleted( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar" );
assertDeleted( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar.md5" );
assertDeleted( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.jar.sha1" );
assertDeleted( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom" );
assertDeleted( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom.md5" );
assertDeleted( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-SNAPSHOT.pom.sha1" );
// shouldn't be deleted because even if older than 30 days (because retention count = 2)
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar.md5" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.jar.sha1" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom.md5" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20070513.034619-5.pom.sha1" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar.md5" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.jar.sha1" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom.md5" );
assertExists( projectRoot + "/2.2-SNAPSHOT/maven-install-plugin-2.2-20061118.060401-2.pom.sha1" );
}
@Test
public void testDefaultRepoOrderOfDeletion()
throws Exception
{
String repoRoot = getDefaultRepositoryLocation().getAbsolutePath();
String projectRoot = repoRoot + "/org/apache/maven/plugins/maven-assembly-plugin";
setLastModified( projectRoot + "/1.1.2-SNAPSHOT/", 1179382029, true );
purgeExecutor.executeTask( purgeDefaultRepoTask );
assertMetadataDeleted( projectRoot );
assertDeleted( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar" );
assertDeleted( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar.sha1" );
assertDeleted( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.jar.md5" );
assertDeleted( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom" );
assertDeleted( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom.sha1" );
assertDeleted( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070427.065136-1.pom.md5" );
// the following should not have been deleted
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar.sha1" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.jar.md5" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom.sha1" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070506.163513-2.pom.md5" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar.sha1" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.jar.md5" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom.sha1" );
assertExists( projectRoot + "/1.1.2-SNAPSHOT/maven-assembly-plugin-1.1.2-20070615.105019-3.pom.md5" );
}
}
| 5,053 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/DaysOldDirectoryPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.junit.Before;
import org.junit.Test;
/**
* @author Maria Catherine Tan
*/
public class DaysOldDirectoryPurgeExecutorTest
extends AbstractPurgeExecutorTest
{
@Before
public void setUp()
throws Exception
{
purgeReleasesDirTask = getDaysOldReleasesDirPurgeTask();
purgeBuildOutputDirTask = getDaysOldBuildOutputDirPurgeTask();
}
@Test
public void testReleasesDirPurgingByLastModified()
throws Exception
{
populateReleasesDirectory();
String dirPath = getReleasesDirectoryLocation().getAbsolutePath();
setLastModified( dirPath, 1179382029, true );
setLastModified( dirPath + "/releases-1234567809", 1023453892, false );
purgeExecutor.executeTask( purgeReleasesDirTask );
assertDeleted( dirPath + "/releases-1234567809" );
assertExists( dirPath + "/1" );
assertExists( dirPath + "/releases-1234567890" );
assertExists( dirPath + "/releases-4234729018" );
}
@Test
public void testReleasesDirPurgingByOrderOfDeletion()
throws Exception
{
populateReleasesDirectory();
String dirPath = getReleasesDirectoryLocation().getAbsolutePath();
setLastModified( dirPath + "/releases-4234729018", new Long( "1234567809" ), false );
setLastModified( dirPath + "/releases-1234567809", new Long( "4234729018" ), false );
setLastModified( dirPath + "/releases-1234567890", new Long( "2234567890" ), false );
purgeExecutor.executeTask( purgeReleasesDirTask );
assertDeleted( dirPath + "/releases-4234729018" );
assertExists( dirPath + "/1" );
assertExists( dirPath + "/releases-1234567890" );
assertExists( dirPath + "/releases-1234567809" );
}
@Test
public void testBuildOutputPurgingByLastModified()
throws Exception
{
populateBuildOutputDirectory();
String dirPath = getBuildOutputDirectoryLocation().getAbsolutePath();
setLastModified( dirPath, 1179382029, true );
setLastModified( dirPath + "/1/1", 1023453892, false );
setLastModified( dirPath + "/1/1.log.txt", 1023453892, false );
setLastModified( dirPath + "/2/4", 1023453892, false );
setLastModified( dirPath + "/2/4.log.txt", 1023453892, false );
purgeExecutor.executeTask( purgeBuildOutputDirTask );
assertDeleted( dirPath + "/1/1" );
assertDeleted( dirPath + "/1/1.log.txt" );
assertExists( dirPath + "/1/3" );
assertExists( dirPath + "/1/3.log.txt" );
assertExists( dirPath + "/1/6" );
assertExists( dirPath + "/1/6.log.txt" );
assertDeleted( dirPath + "/2/4" );
assertDeleted( dirPath + "/2/4.log.txt" );
assertExists( dirPath + "/2/7" );
assertExists( dirPath + "/2/7.log.txt" );
assertExists( dirPath + "/2/9" );
assertExists( dirPath + "/2/9.log.txt" );
}
@Test
public void testBuildOutputPurgingByOrderOfDeletion()
throws Exception
{
populateBuildOutputDirectory();
String dirPath = getBuildOutputDirectoryLocation().getAbsolutePath();
setLastModified( dirPath + "/1/6", new Long( "1234567809" ), false );
setLastModified( dirPath + "/1/6.log.txt", new Long( "1234567809" ), false );
setLastModified( dirPath + "/1/1", new Long( "4234729018" ), false );
setLastModified( dirPath + "/1/1.log.txt", new Long( "4234729018" ), false );
setLastModified( dirPath + "/1/3", new Long( "2234567890" ), false );
setLastModified( dirPath + "/1/3.log.txt", new Long( "2234567890" ), false );
setLastModified( dirPath + "/2/7", new Long( "1234567809" ), false );
setLastModified( dirPath + "/2/7.log.txt", new Long( "1234567809" ), false );
setLastModified( dirPath + "/2/4", new Long( "4234729018" ), false );
setLastModified( dirPath + "/2/4.log.txt", new Long( "4234729018" ), false );
setLastModified( dirPath + "/2/9", new Long( "2234567890" ), false );
setLastModified( dirPath + "/2/9.log.txt", new Long( "2234567890" ), false );
purgeExecutor.executeTask( purgeBuildOutputDirTask );
assertDeleted( dirPath + "/1/6" );
assertDeleted( dirPath + "/1/6.log.txt" );
assertExists( dirPath + "/1/3" );
assertExists( dirPath + "/1/3.log.txt" );
assertExists( dirPath + "/1/1" );
assertExists( dirPath + "/1/1.log.txt" );
assertDeleted( dirPath + "/2/7" );
assertDeleted( dirPath + "/2/7.log.txt" );
assertExists( dirPath + "/2/4" );
assertExists( dirPath + "/2/4.log.txt" );
assertExists( dirPath + "/2/9" );
assertExists( dirPath + "/2/9.log.txt" );
}
}
| 5,054 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/AbstractPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.model.repository.DirectoryPurgeConfiguration;
import org.apache.continuum.model.repository.RepositoryPurgeConfiguration;
import org.apache.continuum.purge.AbstractPurgeTest;
import org.apache.continuum.purge.task.PurgeTask;
import org.apache.continuum.utils.file.FileSystemManager;
import org.codehaus.plexus.taskqueue.execution.TaskExecutor;
import org.junit.After;
import org.junit.Before;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* @author Maria Catherine Tan
*/
public abstract class AbstractPurgeExecutorTest
extends AbstractPurgeTest
{
private static final String[] jar_extensions = new String[] { ".jar", ".jar.md5", ".jar.sha1" };
private static final String[] pom_extensions = new String[] { ".pom", ".pom.md5", ".pom.sha1" };
private static final String[] metadata_extensions = new String[] { ".xml", ".xml.sha1", ".xml.md5" };
private static final String TEST_MAVEN_METADATA = "maven-metadata-central";
private RepositoryPurgeConfiguration repoConfig;
private DirectoryPurgeConfiguration dirConfig;
protected TaskExecutor purgeExecutor;
protected PurgeTask purgeDefaultRepoTask;
protected PurgeTask purgeReleasesDirTask;
protected PurgeTask purgeBuildOutputDirTask;
protected FileSystemManager fsManager;
@Before
public void setupPurgeTaskAndTools()
throws Exception
{
if ( purgeExecutor == null )
{
purgeExecutor = lookup( TaskExecutor.class, "purge" );
}
fsManager = lookup( FileSystemManager.class );
}
@After
public void removeOutputDirs()
throws Exception
{
fsManager.removeDir( getDefaultRepositoryLocation() );
fsManager.removeDir( getReleasesDirectoryLocation() );
fsManager.removeDir( getBuildOutputDirectoryLocation() );
}
protected PurgeTask getDaysOldRepoPurgeTask()
throws Exception
{
repoConfig = new RepositoryPurgeConfiguration();
repoConfig.setRepository( defaultRepository );
repoConfig.setDaysOlder( AbstractPurgeTest.TEST_DAYS_OLDER );
repoConfig = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoConfig );
return new PurgeTask( repoConfig.getId() );
}
protected PurgeTask getRetentionCountRepoPurgeTask()
throws Exception
{
repoConfig = new RepositoryPurgeConfiguration();
repoConfig.setRepository( defaultRepository );
repoConfig.setDaysOlder( -1 );
repoConfig.setRetentionCount( AbstractPurgeTest.TEST_RETENTION_COUNT );
repoConfig = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoConfig );
return new PurgeTask( repoConfig.getId() );
}
protected PurgeTask getReleasedSnapshotsRepoPurgeTask()
throws Exception
{
repoConfig = new RepositoryPurgeConfiguration();
repoConfig.setRepository( defaultRepository );
repoConfig.setDaysOlder( -1 );
repoConfig.setRetentionCount( AbstractPurgeTest.TEST_RETENTION_COUNT );
repoConfig.setDeleteReleasedSnapshots( true );
repoConfig = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoConfig );
return new PurgeTask( repoConfig.getId() );
}
protected PurgeTask getDaysOldReleasesDirPurgeTask()
throws Exception
{
dirConfig = new DirectoryPurgeConfiguration();
dirConfig.setDirectoryType( AbstractPurgeTest.TEST_RELEASES_DIRECTORY_TYPE );
dirConfig.setLocation( getReleasesDirectoryLocation().getAbsolutePath() );
dirConfig.setDaysOlder( AbstractPurgeTest.TEST_DAYS_OLDER );
dirConfig = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirConfig );
return new PurgeTask( dirConfig.getId() );
}
protected PurgeTask getDaysOldBuildOutputDirPurgeTask()
throws Exception
{
dirConfig = new DirectoryPurgeConfiguration();
dirConfig.setDirectoryType( AbstractPurgeTest.TEST_BUILDOUTPUT_DIRECTORY_TYPE );
dirConfig.setLocation( getBuildOutputDirectoryLocation().getAbsolutePath() );
dirConfig.setDaysOlder( AbstractPurgeTest.TEST_DAYS_OLDER );
dirConfig = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirConfig );
return new PurgeTask( dirConfig.getId() );
}
protected PurgeTask getRetentionCountReleasesDirPurgeTask()
throws Exception
{
dirConfig = new DirectoryPurgeConfiguration();
dirConfig.setDirectoryType( AbstractPurgeTest.TEST_RELEASES_DIRECTORY_TYPE );
dirConfig.setLocation( getReleasesDirectoryLocation().getAbsolutePath() );
dirConfig.setDaysOlder( -1 );
dirConfig.setRetentionCount( AbstractPurgeTest.TEST_RETENTION_COUNT );
dirConfig = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirConfig );
return new PurgeTask( dirConfig.getId() );
}
protected PurgeTask getRetentionCountBuildOutputDirPurgeTask()
throws Exception
{
dirConfig = new DirectoryPurgeConfiguration();
dirConfig.setDirectoryType( AbstractPurgeTest.TEST_BUILDOUTPUT_DIRECTORY_TYPE );
dirConfig.setLocation( getBuildOutputDirectoryLocation().getAbsolutePath() );
dirConfig.setDaysOlder( -1 );
dirConfig.setRetentionCount( AbstractPurgeTest.TEST_RETENTION_COUNT );
dirConfig = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirConfig );
return new PurgeTask( dirConfig.getId() );
}
protected PurgeTask getCleanAllDefaultRepoPurgeTask()
throws Exception
{
return new PurgeTask( defaultRepoPurge.getId() );
}
protected PurgeTask getCleanAllReleasesDirPurgeTask()
throws Exception
{
return new PurgeTask( defaultReleasesDirPurge.getId() );
}
protected PurgeTask getCleanAllBuildOutputDirPurgeTask()
throws Exception
{
return new PurgeTask( defaultBuildOutputDirPurge.getId() );
}
protected void setLastModified( String dirPath, long lastModified, boolean recurse )
{
File dir = new File( dirPath );
if ( recurse )
{
for ( File content : dir.listFiles() )
{
content.setLastModified( lastModified );
if ( content.list() != null && content.list().length > 0 )
{
setLastModified( content.getAbsolutePath(), lastModified, true );
}
}
}
else
{
dir.setLastModified( lastModified );
}
}
protected void assertIsEmpty( File dir )
{
File[] files = dir.listFiles();
assertEquals( "Directory should be clean: " + dir.getName(), 0, files.length );
}
protected void assertDeleted( String path )
{
assertFalse( "File should have been deleted: " + path, new File( path ).exists() );
}
protected void assertExists( String path )
{
assertTrue( "File should exist: " + path, new File( path ).exists() );
}
protected void assertMetadataDeleted( String projectRoot )
{
assertDeleted( projectRoot + "/" + TEST_MAVEN_METADATA + ".xml" );
assertDeleted( projectRoot + "/" + TEST_MAVEN_METADATA + ".xml.sha1" );
assertDeleted( projectRoot + "/" + TEST_MAVEN_METADATA + ".xml.md5" );
}
protected void populateDefaultRepositoryForRetentionCount()
throws Exception
{
prepareTestFolders();
List<String> versions = new ArrayList<String>();
versions.add( "1.0RC1-20070504.153317-1" );
versions.add( "1.0RC1-20070504.160758-2" );
versions.add( "1.0RC1-20070505.090015-3" );
versions.add( "1.0RC1-20070506.090132-4" );
createDefaultRepoFiles( "/org/jruby/plugins/jruby-rake-plugin/1.0RC1-SNAPSHOT", "jruby-rake-plugin", versions );
versions = new ArrayList<String>();
versions.add( "1.1.2-20070427.065136-1" );
versions.add( "1.1.2-20070615.105019-3" );
versions.add( "1.1.2-20070506.163513-2" );
createDefaultRepoFiles( "/org/codehaus/castor/castor-anttasks/1.1.2-SNAPSHOT", "castor-anttasks", versions );
}
protected void populateDefaultRepository()
throws Exception
{
prepareTestFolders();
List<String> versions = new ArrayList<String>();
versions.add( "1.1.2-20070427.065136-1" );
versions.add( "1.1.2-20070506.163513-2" );
versions.add( "1.1.2-20070615.105019-3" );
createDefaultRepoFiles( "/org/apache/maven/plugins/maven-assembly-plugin/1.1.2-SNAPSHOT",
"maven-assembly-plugin", versions );
versions = new ArrayList<String>();
versions.add( "2.2-20061118.060401-2" );
versions.add( "2.2-20070513.034619-5" );
versions.add( "2.2-SNAPSHOT" );
createDefaultRepoFiles( "/org/apache/maven/plugins/maven-install-plugin/2.2-SNAPSHOT", "maven-install-plugin",
versions );
}
protected void populateDefaultRepositoryForReleasedSnapshots()
throws Exception
{
populateDefaultRepository();
List<String> versions = new ArrayList<String>();
versions.add( "2.2" );
createDefaultRepoFiles( "/org/apache/maven/plugins/maven-plugin-plugin/2.2", "maven-plugin-plugin", versions );
versions = new ArrayList<String>();
versions.add( "2.3" );
createDefaultRepoFiles( "/org/apache/maven/plugins/maven-plugin-plugin/2.3", "maven-plugin-plugin", versions );
versions = new ArrayList<String>();
versions.add( "2.3-SNAPSHOT" );
createDefaultRepoFiles( "/org/apache/maven/plugins/maven-plugin-plugin/2.3-SNAPSHOT", "maven-plugin-plugin",
versions );
}
protected void populateReleasesDirectory()
throws Exception
{
prepareTestFolders();
String repoPath = getReleasesDirectoryLocation().getAbsolutePath();
String[] folders =
new String[] { "1", "releases-4234729018", "", "releases-1234567809", "releases-1234567890" };
for ( String folder : folders )
{
File dir = new File( repoPath, folder );
dir.mkdir();
}
}
protected void populateBuildOutputDirectory()
throws Exception
{
prepareTestFolders();
String repoPath = getBuildOutputDirectoryLocation().getAbsolutePath();
File projectDir1 = new File( repoPath, "1" );
projectDir1.mkdir();
File projectDir2 = new File( repoPath, "2" );
projectDir2.mkdir();
String[] buildOutputs1 = new String[] { "1", "3", "6" };
String[] buildOutputs2 = new String[] { "4", "7", "9" };
for ( int i = 0; i < 3; i++ )
{
File outputDir1 = new File( projectDir1.getAbsolutePath(), buildOutputs1[i] );
outputDir1.mkdir();
File outputFile1 = new File( projectDir1.getAbsolutePath(), buildOutputs1[i] + ".log.txt" );
outputFile1.createNewFile();
File outputDir2 = new File( projectDir2.getAbsolutePath(), buildOutputs2[i] );
outputDir2.mkdir();
File outputFile2 = new File( projectDir2.getAbsolutePath(), buildOutputs2[i] + ".log.txt" );
outputFile2.createNewFile();
}
}
private void createDefaultRepoFiles( String versionPath, String artifactId, List<String> versions )
throws Exception
{
String repoPath = getDefaultRepositoryLocation().getAbsolutePath();
File versionDir = new File( repoPath + versionPath );
if ( !versionDir.exists() )
{
versionDir.mkdirs();
// create maven-metadata* files
for ( String metadata_extension : metadata_extensions )
{
File metadata = new File( versionDir.getParentFile().getAbsolutePath(),
TEST_MAVEN_METADATA + metadata_extension );
metadata.createNewFile();
}
}
for ( String version : versions )
{
for ( String jar_extension : jar_extensions )
{
File file = new File( versionDir.getAbsolutePath(), artifactId + "-" + version + jar_extension );
file.createNewFile();
}
for ( String pom_extension : pom_extensions )
{
File file = new File( versionDir.getAbsolutePath(), artifactId + "-" + version + pom_extension );
file.createNewFile();
}
}
}
private void prepareTestFolders()
throws Exception
{
fsManager.wipeDir( getDefaultRepositoryLocation() );
fsManager.wipeDir( getReleasesDirectoryLocation() );
fsManager.wipeDir( getBuildOutputDirectoryLocation() );
}
}
| 5,055 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/purge/executor/RetentionCountDirectoryPurgeExecutorTest.java | package org.apache.continuum.purge.executor;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.maven.archiva.consumers.core.repository.ArtifactFilenameFilter;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import static org.junit.Assert.assertEquals;
/**
* @author Maria Catherine Tan
*/
public class RetentionCountDirectoryPurgeExecutorTest
extends AbstractPurgeExecutorTest
{
@Before
public void setUp()
throws Exception
{
purgeReleasesDirTask = getRetentionCountReleasesDirPurgeTask();
purgeBuildOutputDirTask = getRetentionCountBuildOutputDirPurgeTask();
}
@Test
public void testReleasesDirPurging()
throws Exception
{
populateReleasesDirectory();
String dirPath = getReleasesDirectoryLocation().getAbsolutePath();
FilenameFilter filter = new ArtifactFilenameFilter( "releases-" );
File[] workingDir = new File( dirPath ).listFiles();
File[] releasesDir = new File( dirPath ).listFiles( filter );
assertEquals( "# of folders inside working directory", 4, workingDir.length );
assertEquals( "# of releases folders inside working directory", 3, releasesDir.length );
assertExists( dirPath + "/1" );
purgeExecutor.executeTask( purgeReleasesDirTask );
workingDir = new File( dirPath ).listFiles();
releasesDir = new File( dirPath ).listFiles( filter );
assertEquals( "# of folders inside working directory", 3, workingDir.length );
assertEquals( "# of releases folders inside working directory", 2, releasesDir.length );
assertExists( dirPath + "/1" );
}
@Test
public void testBuildOutputDirPurging()
throws Exception
{
populateBuildOutputDirectory();
String dirPath = getBuildOutputDirectoryLocation().getAbsolutePath();
File projectPath1 = new File( dirPath, "1" );
File projectPath2 = new File( dirPath, "2" );
FileFilter filter = DirectoryFileFilter.DIRECTORY;
File[] files1 = projectPath1.listFiles( filter );
File[] files2 = projectPath2.listFiles( filter );
assertEquals( "check # of build output dir", 3, files1.length );
assertEquals( "check # of build output dir", 3, files2.length );
purgeExecutor.executeTask( purgeBuildOutputDirTask );
files1 = projectPath1.listFiles( filter );
files2 = projectPath2.listFiles( filter );
assertEquals( "check # of build output dir", 2, files1.length );
assertEquals( "check # of build output dir", 2, files2.length );
for ( File file : files1 )
{
assertExists( file.getAbsolutePath() + ".log.txt" );
}
for ( File file : files2 )
{
assertExists( file.getAbsolutePath() + ".log.txt" );
}
}
}
| 5,056 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/buildmanager/ParallelBuildsManagerTest.java | package org.apache.continuum.buildmanager;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildqueue.BuildQueueService;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.taskqueue.BuildProjectTask;
import org.apache.continuum.taskqueue.CheckOutTask;
import org.apache.continuum.taskqueue.OverallBuildQueue;
import org.apache.continuum.taskqueue.PrepareBuildProjectsTask;
import org.apache.continuum.taskqueueexecutor.ParallelBuildsThreadedTaskQueueExecutor;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildQueue;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.Schedule;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.codehaus.plexus.taskqueue.TaskQueueException;
import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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 static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* ParallelBuildsManagerTest
*
* @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
*/
public class ParallelBuildsManagerTest
extends PlexusSpringTestCase
{
private ParallelBuildsManager buildsManager;
private BuildDefinitionDao buildDefinitionDao;
private ProjectDao projectDao;
private ConfigurationService configurationService;
private OverallBuildQueue overallBuildQueue;
private TaskQueue buildQueue;
private TaskQueue checkoutQueue;
private TaskQueue prepareBuildQueue;
private List<Project> projects;
private TaskQueueExecutor buildTaskQueueExecutor;
private TaskQueueExecutor checkoutTaskQueueExecutor;
private TaskQueueExecutor prepareBuildTaskQueueExecutor;
@Before
public void setUp()
throws Exception
{
buildsManager = (ParallelBuildsManager) lookup( BuildsManager.class, "parallel" );
buildDefinitionDao = mock( BuildDefinitionDao.class );
configurationService = mock( ConfigurationService.class );
prepareBuildTaskQueueExecutor = mock( TaskQueueExecutor.class, "prepare-build-task-queue" );
buildQueue = mock( TaskQueue.class, "build-queue" );
checkoutQueue = mock( TaskQueue.class, "checkout-queue" );
prepareBuildQueue = mock( TaskQueue.class, "prepare-build-queue" );
projectDao = mock( ProjectDao.class );
buildTaskQueueExecutor = mock( TaskQueueExecutor.class, "build-task-queue" );
checkoutTaskQueueExecutor = mock( TaskQueueExecutor.class, "checkout-task-queue" );
BuildQueueService buildQueueService = mock( BuildQueueService.class );
buildsManager.setBuildDefinitionDao( buildDefinitionDao );
buildsManager.setConfigurationService( configurationService );
buildsManager.setBuildQueueService( buildQueueService );
buildsManager.setProjectDao( projectDao );
}
@After
public void tearDown()
throws Exception
{
buildsManager = null;
}
private List<BuildQueue> getBuildQueues( int start, int end )
{
List<BuildQueue> buildQueues = new ArrayList<BuildQueue>();
for ( int i = start; i <= end; i++ )
{
BuildQueue buildQueue = new BuildQueue();
buildQueue.setId( i );
if ( i == 1 )
{
buildQueue.setName( ConfigurationService.DEFAULT_BUILD_QUEUE_NAME );
}
else
{
buildQueue.setName( "BUILD_QUEUE_" + String.valueOf( i ) );
}
buildQueues.add( buildQueue );
}
return buildQueues;
}
private Schedule getSchedule( int id, int start, int end )
{
Schedule schedule = new Schedule();
schedule.setId( id );
schedule.setName( "DEFAULT_SCHEDULE" );
schedule.setCronExpression( "0 0 * * * ?" );
schedule.setDelay( 100 );
schedule.setMaxJobExecutionTime( 10000 );
schedule.setBuildQueues( getBuildQueues( start, end ) );
return schedule;
}
public void setupMockOverallBuildQueues()
throws Exception
{
Map<Integer, OverallBuildQueue> overallBuildQueues = Collections.synchronizedMap(
new HashMap<Integer, OverallBuildQueue>() );
overallBuildQueue = mock( OverallBuildQueue.class );
for ( int i = 1; i <= 5; i++ )
{
overallBuildQueues.put( i, overallBuildQueue );
}
buildsManager.setOverallBuildQueues( overallBuildQueues );
}
// build project recordings
private void setupStartOfBuildProjectSequence()
throws TaskQueueException, ContinuumStoreException
{
when( overallBuildQueue.isInBuildQueue( anyInt() ) ).thenReturn( false );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( projectDao.getProjectsInGroup( anyInt() ) ).thenReturn( projects );
when( configurationService.getNumberOfBuildsInParallel() ).thenReturn( 2 );
when( overallBuildQueue.getBuildQueue() ).thenReturn( buildQueue );
when( overallBuildQueue.getBuildTaskQueueExecutor() ).thenReturn( buildTaskQueueExecutor );
}
private void setupBuildProjectBuildQueuesAreEmpty()
throws TaskQueueException, ContinuumStoreException
{
// shouldn't only the build queues attached to the schedule be checked?
setupStartOfBuildProjectSequence();
List<Task> tasks = new ArrayList<Task>();
when( buildQueue.getQueueSnapshot() ).thenReturn( tasks );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_2" );
}
// checkout project recordings
private void recordStartOfCheckoutProjectSequence()
throws TaskQueueException
{
when( overallBuildQueue.isInCheckoutQueue( anyInt() ) ).thenReturn( false );
when( configurationService.getNumberOfBuildsInParallel() ).thenReturn( 2 );
when( overallBuildQueue.getCheckoutQueue() ).thenReturn( checkoutQueue );
when( overallBuildQueue.getCheckoutTaskQueueExecutor() ).thenReturn( checkoutTaskQueueExecutor );
}
private void setupCheckoutProjectBuildQueuesAreEmpty()
throws TaskQueueException
{
when( overallBuildQueue.isInCheckoutQueue( anyInt() ) ).thenReturn( false );
when( configurationService.getNumberOfBuildsInParallel() ).thenReturn( 2 );
when( overallBuildQueue.getCheckoutQueue() ).thenReturn( checkoutQueue );
when( overallBuildQueue.getCheckoutTaskQueueExecutor() ).thenReturn( checkoutTaskQueueExecutor );
when( checkoutQueue.getQueueSnapshot() ).thenReturn( new ArrayList<Task>() );
when( checkoutTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_2" );
}
// prepare build project recordings
private void setupStartOfPrepareBuildProjectSequence()
throws TaskQueueException, ContinuumStoreException
{
final BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
when( overallBuildQueue.isInPrepareBuildQueue( anyInt(), anyInt() ) ).thenReturn( false );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( buildDef );
when( configurationService.getNumberOfBuildsInParallel() ).thenReturn( 2 );
when( overallBuildQueue.getPrepareBuildQueue() ).thenReturn( prepareBuildQueue );
when( overallBuildQueue.getPrepareBuildTaskQueueExecutor() ).thenReturn( prepareBuildTaskQueueExecutor );
}
// start of test cases..
@Test
public void testContainer()
throws Exception
{
buildsManager.setContainer( getContainer() );
buildsManager.isProjectInAnyCurrentBuild( 1 );
assertTrue( true ); // why is this necessary?
}
@Test
public void testBuildProjectNoProjectQueuedInAnyOverallBuildQueues()
throws Exception
{
setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
setupBuildProjectBuildQueuesAreEmpty();
buildsManager.buildProject( 1, buildDef, "continuum-project-test-1", new BuildTrigger( 1, "test-user" ), null,
1 );
verify( overallBuildQueue ).addToBuildQueue( any( BuildProjectTask.class ) );
}
@Test
public void testBuildProjectProjectsAreAlreadyQueuedInOverallBuildQueues()
throws Exception
{
setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
setupBuildProjectBuildQueuesAreEmpty();
buildsManager.buildProject( 1, buildDef, "continuum-project-test-1", new BuildTrigger( 1, "test-user" ), null,
1 );
verify( overallBuildQueue ).addToBuildQueue( any( BuildProjectTask.class ) );
//queue second project - 1st queue is not empty, 2nd queue is empty
reset( overallBuildQueue );
setupStartOfBuildProjectSequence();
// the first build queue already has a task queued
final List<Task> tasks = new ArrayList<Task>();
final List<Task> tasksOfFirstBuildQueue = new ArrayList<Task>();
tasksOfFirstBuildQueue.add( new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ),
"continuum-project-test-2", buildDef.getDescription(), null,
2 ) );
when( buildQueue.getQueueSnapshot() ).thenReturn( tasksOfFirstBuildQueue, tasks );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_3" );
buildsManager.buildProject( 2, buildDef, "continuum-project-test-2", new BuildTrigger( 1, "test-user" ), null,
2 );
verify( overallBuildQueue ).addToBuildQueue( any( BuildProjectTask.class ) );
// queue third project - both queues have 1 task queued each
reset( overallBuildQueue );
setupStartOfBuildProjectSequence();
// both queues have 1 task each
when( buildQueue.getQueueSnapshot() ).thenReturn( tasksOfFirstBuildQueue, tasksOfFirstBuildQueue );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_2" );
buildsManager.buildProject( 3, buildDef, "continuum-project-test-3", new BuildTrigger( 1, "test-user" ), null,
3 );
verify( overallBuildQueue ).addToBuildQueue( any( BuildProjectTask.class ) );
}
@Test
public void testRemoveProjectFromBuildQueue()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.isInBuildQueue( 1 ) ).thenReturn( true );
buildsManager.removeProjectFromBuildQueue( 1 );
verify( overallBuildQueue ).removeProjectFromBuildQueue( 1 );
}
@Test
public void testRemoveProjectsFromBuildQueue()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.isInBuildQueue( anyInt() ) ).thenReturn( true );
int[] projectIds = new int[] { 1, 2, 3 };
buildsManager.removeProjectsFromBuildQueue( projectIds );
for ( int projectId : projectIds )
verify( overallBuildQueue ).removeProjectFromBuildQueue( projectId );
}
@Test
public void testCheckoutProjectSingle()
throws Exception
{
setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
setupCheckoutProjectBuildQueuesAreEmpty();
buildsManager.checkoutProject( 1, "continuum-project-test-1",
new File( getBasedir(), "/target/test-working-dir/1" ), null,
"dummy", "dummypass", buildDef, null );
verify( overallBuildQueue ).addToCheckoutQueue( any( CheckOutTask.class ) );
}
@Test
public void testCheckoutProjectMultiple()
throws Exception
{
setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
setupCheckoutProjectBuildQueuesAreEmpty();
buildsManager.checkoutProject( 1, "continuum-project-test-1",
new File( getBasedir(), "/target/test-working-dir/1" ), null,
"dummy", "dummypass", buildDef, null );
verify( overallBuildQueue ).addToCheckoutQueue( any( CheckOutTask.class ) );
// queue second project - 1st queue has 1 task while 2nd queue is empty; project should be queued in 2nd queue
reset( overallBuildQueue );
recordStartOfCheckoutProjectSequence();
List<Task> tasks = new ArrayList<Task>();
List<Task> tasksInFirstCheckoutQueue = new ArrayList<Task>();
tasksInFirstCheckoutQueue.add( new CheckOutTask( 1,
new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-1", "dummy", "dummypass", null,
null ) );
when( checkoutQueue.getQueueSnapshot() ).thenReturn( tasksInFirstCheckoutQueue, tasks );
when( checkoutTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_3" );
buildsManager.checkoutProject( 2, "continuum-project-test-2", new File( getBasedir(),
"/target/test-working-dir/1" ), null,
"dummy", "dummypass", buildDef, null );
verify( overallBuildQueue ).addToCheckoutQueue( any( CheckOutTask.class ) );
reset( overallBuildQueue );
recordStartOfCheckoutProjectSequence();
// queue third project - both queues have 1 task queued each; third project should be queued in 1st queue
when( checkoutQueue.getQueueSnapshot() ).thenReturn( tasksInFirstCheckoutQueue );
when( checkoutTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_2" );
buildsManager.checkoutProject( 3, "continuum-project-test-3",
new File( getBasedir(), "/target/test-working-dir/1" ), null,
"dummy", "dummypass", buildDef, null );
verify( overallBuildQueue ).addToCheckoutQueue( any( CheckOutTask.class ) );
}
@Test
public void testRemoveProjectFromCheckoutQueue()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.isInCheckoutQueue( 1 ) ).thenReturn( true );
buildsManager.removeProjectFromCheckoutQueue( 1 );
verify( overallBuildQueue ).removeProjectFromCheckoutQueue( 1 );
}
@Test
public void testRemoveProjectsFromCheckoutQueue()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.isInCheckoutQueue( anyInt() ) ).thenReturn( true );
int[] projectIds = new int[] { 1, 2, 3 };
buildsManager.removeProjectsFromCheckoutQueue( projectIds );
for ( int projectId : projectIds )
verify( overallBuildQueue ).removeProjectFromCheckoutQueue( projectId );
}
@Test
public void testRemoveProjectFromCheckoutQueueProjectNotFound()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.isInCheckoutQueue( 1 ) ).thenReturn( false );
// shouldn't only the project's build queues be checked instead of all the overall build queues?
buildsManager.removeProjectFromCheckoutQueue( 1 );
verify( overallBuildQueue, never() ).removeProjectFromCheckoutQueue( 1 );
}
@Test
public void testRemoveDefaultOverallBuildQueue()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.getName() ).thenReturn( ConfigurationService.DEFAULT_BUILD_QUEUE_NAME );
try
{
buildsManager.removeOverallBuildQueue( 1 );
fail( "An exception should have been thrown." );
}
catch ( BuildManagerException e )
{
assertEquals( "Cannot remove default build queue.", e.getMessage() );
}
}
@Test
public void testRemoveOverallBuildQueueNoTasksCurrentlyExecuting()
throws Exception
{
// queued tasks (both checkout & build tasks) must be transferred to the other queues!
setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
List<BuildProjectTask> buildTasks = new ArrayList<BuildProjectTask>();
buildTasks.add( new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ), "continuum-project-test-2",
"BUILD_DEF", null, 2 ) );
List<CheckOutTask> checkoutTasks = new ArrayList<CheckOutTask>();
checkoutTasks.add( new CheckOutTask( 2, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-2", "dummy", "dummypass", null, null ) );
List<PrepareBuildProjectsTask> prepareBuildTasks = new ArrayList<PrepareBuildProjectsTask>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put( 1, 1 );
prepareBuildTasks.add( new PrepareBuildProjectsTask( map, new BuildTrigger( 1, "test-user" ), 1,
"Project Group A", "http://scm.root.address", 2 ) );
ParallelBuildsThreadedTaskQueueExecutor buildTaskQueueExecutor = mock(
ParallelBuildsThreadedTaskQueueExecutor.class, "parallel-build-task-executor" );
ParallelBuildsThreadedTaskQueueExecutor checkoutTaskQueueExecutor = mock(
ParallelBuildsThreadedTaskQueueExecutor.class, "parallel-checkout-task-executor" );
ParallelBuildsThreadedTaskQueueExecutor prepareBuildTaskQueueExecutor = mock(
ParallelBuildsThreadedTaskQueueExecutor.class, "parallel-prepare-build-task-executor" );
List<Task> tasks = new ArrayList<Task>();
when( configurationService.getNumberOfBuildsInParallel() ).thenReturn( 2 );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_5", "BUILD_QUEUE_2" );
// get all queued build tasks & remove them
when( overallBuildQueue.getProjectsInBuildQueue() ).thenReturn( buildTasks );
when( overallBuildQueue.getBuildQueue() ).thenReturn( buildQueue );
when( buildQueue.getQueueSnapshot() ).thenReturn( tasks );
// get all queued checkout tasks & remove them
when( overallBuildQueue.getProjectsInCheckoutQueue() ).thenReturn( checkoutTasks );
when( overallBuildQueue.getCheckoutQueue() ).thenReturn( checkoutQueue );
when( checkoutQueue.getQueueSnapshot() ).thenReturn( tasks );
// get all queued prepare build tasks & remove them
when( overallBuildQueue.getProjectsInPrepareBuildQueue() ).thenReturn( prepareBuildTasks );
when( overallBuildQueue.getPrepareBuildQueue() ).thenReturn( prepareBuildQueue );
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasks );
// stop the build & checkout task queue executors
when( overallBuildQueue.getBuildTaskQueueExecutor() ).thenReturn( buildTaskQueueExecutor );
when( overallBuildQueue.getCheckoutTaskQueueExecutor() ).thenReturn( checkoutTaskQueueExecutor );
when( overallBuildQueue.getPrepareBuildTaskQueueExecutor() ).thenReturn( prepareBuildTaskQueueExecutor );
// TODO: test scenario when there are no longer build queues configured aside from the one removed?
// - the behaviour should be that the default build queue will be used!
when( projectDao.getProjectsInGroup( anyInt() ) ).thenReturn( projects );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( buildDef );
when( buildDefinitionDao.getDefaultBuildDefinition( 2 ) ).thenReturn( buildDef );
when( overallBuildQueue.isInBuildQueue( anyInt() ) ).thenReturn( false );
when( overallBuildQueue.isInCheckoutQueue( anyInt() ) ).thenReturn( false );
when( overallBuildQueue.isInPrepareBuildQueue( anyInt(), anyInt() ) ).thenReturn( false );
buildsManager.removeOverallBuildQueue( 5 );
verify( buildQueue ).removeAll( buildTasks );
verify( checkoutQueue ).removeAll( checkoutTasks );
verify( prepareBuildQueue ).removeAll( prepareBuildTasks );
verify( buildTaskQueueExecutor ).stop();
verify( checkoutTaskQueueExecutor ).stop();
verify( prepareBuildTaskQueueExecutor ).stop();
verify( overallBuildQueue ).addToBuildQueue( any( BuildProjectTask.class ) );
verify( overallBuildQueue ).addToCheckoutQueue( any( CheckOutTask.class ) );
verify( overallBuildQueue ).addToPrepareBuildQueue( any( PrepareBuildProjectsTask.class ) );
Map<Integer, OverallBuildQueue> overallBuildQueues = buildsManager.getOverallBuildQueues();
assertNull( overallBuildQueues.get( 5 ) );
}
@Test
public void testRemoveOverallBuildQueueTasksCurrentlyExecuting()
throws Exception
{
setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
TaskQueueExecutor buildQueueExecutor = mock( TaskQueueExecutor.class, "build-queue-executor" );
Task buildTask = new BuildProjectTask( 1, 1, new BuildTrigger( 1, "test-user" ),
"continuum-project-test-1", "BUILD_DEF", null, 1 );
List<BuildProjectTask> buildTasks = new ArrayList<BuildProjectTask>();
buildTasks.add( new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ), "continuum-project-test-2",
"BUILD_DEF", null, 2 ) );
List<CheckOutTask> checkoutTasks = new ArrayList<CheckOutTask>();
checkoutTasks.add( new CheckOutTask( 2, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-2", "dummy", "dummypass", null, null ) );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_5" );
when( overallBuildQueue.getBuildTaskQueueExecutor() ).thenReturn( buildQueueExecutor );
when( buildQueueExecutor.getCurrentTask() ).thenReturn( buildTask );
try
{
buildsManager.removeOverallBuildQueue( 5 );
fail( "An exception should have been thrown." );
}
catch ( BuildManagerException e )
{
assertEquals( "Cannot remove build queue. A task is currently executing.", e.getMessage() );
}
}
@Test
public void testNoBuildQueuesConfigured()
throws Exception
{
Map<Integer, OverallBuildQueue> overallBuildQueues =
Collections.synchronizedMap( new HashMap<Integer, OverallBuildQueue>() );
overallBuildQueue = mock( OverallBuildQueue.class );
overallBuildQueues.put( 1, overallBuildQueue );
buildsManager.setOverallBuildQueues( overallBuildQueues );
Schedule schedule = new Schedule();
schedule.setId( 1 );
schedule.setName( "DEFAULT_SCHEDULE" );
schedule.setCronExpression( "0 0 * * * ?" );
schedule.setDelay( 100 );
schedule.setMaxJobExecutionTime( 10000 );
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( schedule );
when( overallBuildQueue.isInBuildQueue( anyInt() ) ).thenReturn( false );
when( overallBuildQueue.getBuildTaskQueueExecutor() ).thenReturn( buildTaskQueueExecutor );
when( buildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( projectDao.getProjectsInGroup( anyInt() ) ).thenReturn( projects );
when( configurationService.getNumberOfBuildsInParallel() ).thenReturn( 2 );
when( overallBuildQueue.getName() ).thenReturn( ConfigurationService.DEFAULT_BUILD_QUEUE_NAME );
buildsManager.buildProject( 1, buildDef, "continuum-project-test-1", new BuildTrigger( 1, "test-user" ), null,
1 );
verify( overallBuildQueue ).addToBuildQueue( any( BuildProjectTask.class ) );
}
@Test
public void testGetProjectsInBuildQueue()
throws Exception
{
setupMockOverallBuildQueues();
List<BuildProjectTask> tasks = new ArrayList<BuildProjectTask>();
tasks.add(
new BuildProjectTask( 2, 1, new BuildTrigger( 1, "test-user" ), "continuum-project-test-2", "BUILD_DEF",
null, 2 ) );
String queueName = "BUILD_QUEUE";
when( overallBuildQueue.getName() ).thenReturn( queueName );
when( overallBuildQueue.getProjectsInBuildQueue() ).thenReturn( tasks );
Map<String, List<BuildProjectTask>> result = buildsManager.getProjectsInBuildQueues();
assertEquals( 1, result.size() );
assertTrue( queueName + " should be present in result", result.containsKey( queueName ) );
assertEquals( tasks, result.get( queueName ) );
}
@Test
public void testGetProjectsInCheckoutQueue()
throws Exception
{
setupMockOverallBuildQueues();
List<CheckOutTask> tasks = new ArrayList<CheckOutTask>();
tasks.add( new CheckOutTask( 2, new File( getBasedir(), "/target/test-working-dir/1" ),
"continuum-project-test-2", "dummy", "dummypass", null, null ) );
String queueName = "BUILD_QUEUE";
when( overallBuildQueue.getName() ).thenReturn( queueName );
when( overallBuildQueue.getProjectsInCheckoutQueue() ).thenReturn( tasks );
Map<String, List<CheckOutTask>> result = buildsManager.getProjectsInCheckoutQueues();
assertEquals( 1, result.size() );
assertTrue( queueName + " should be present in result", result.containsKey( queueName ) );
assertEquals( tasks, result.get( queueName ) );
}
// prepare build queue
@Test
public void testPrepareBuildProjectNoProjectQueuedInAnyOverallBuildQueues()
throws Exception
{
setupMockOverallBuildQueues();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put( 1, 1 );
setupStartOfPrepareBuildProjectSequence();
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( new ArrayList<Task>() );
when( prepareBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_2" );
buildsManager.prepareBuildProjects( map, new BuildTrigger( 1, "test-user" ), 1, "Project Group A",
"http://scm.root.address", 1 );
verify( overallBuildQueue ).addToPrepareBuildQueue( any( PrepareBuildProjectsTask.class ) );
}
@Test
public void testPrepareBuildProjectsAlreadyQueued()
throws Exception
{
setupMockOverallBuildQueues();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put( 1, 1 );
//queue second project - 1st queue is not empty, 2nd queue is empty
setupStartOfPrepareBuildProjectSequence();
List<Task> tasks = new ArrayList<Task>();
List<Task> tasksOfFirstPrepareBuildQueue = new ArrayList<Task>();
tasksOfFirstPrepareBuildQueue.add( new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(),
new BuildTrigger( 1, "test-user" ), 1,
"Project Group B", "http://scm.root.address2",
2 ) );
// the first prepare build queue already has a task queued
// the second prepare build queue has no tasks queued, so it should return 0
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasksOfFirstPrepareBuildQueue, tasks );
when( prepareBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_3" );
buildsManager.prepareBuildProjects( map, new BuildTrigger( 1, "test-user" ), 1, "Project Group A",
"http://scm.root.address", 1 );
verify( overallBuildQueue ).addToPrepareBuildQueue( any( PrepareBuildProjectsTask.class ) );
// queue third project - both queues have 1 task queued each
reset( overallBuildQueue );
setupStartOfPrepareBuildProjectSequence(); // Redundant
// both queues have 1 task each
when( prepareBuildQueue.getQueueSnapshot() ).thenReturn( tasksOfFirstPrepareBuildQueue );
when( prepareBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallBuildQueue.getName() ).thenReturn( "BUILD_QUEUE_2" );
buildsManager.prepareBuildProjects( map, new BuildTrigger( 1, "test-user" ), 1, "Project Group A",
"http://scm.root.address", 1 );
verify( overallBuildQueue ).addToPrepareBuildQueue( any( PrepareBuildProjectsTask.class ) );
}
@Test
public void testGetProjectsInPrepareBuildQueue()
throws Exception
{
setupMockOverallBuildQueues();
List<PrepareBuildProjectsTask> tasks = new ArrayList<PrepareBuildProjectsTask>();
tasks.add( new PrepareBuildProjectsTask( new HashMap<Integer, Integer>(), new BuildTrigger( 1, "test-user" ), 1,
"Project Group A", "http://scm.root.address", 2 ) );
String queueName = "PREPARE_BUILD_QUEUE";
when( overallBuildQueue.getName() ).thenReturn( queueName );
when( overallBuildQueue.getProjectsInPrepareBuildQueue() ).thenReturn( tasks );
Map<String, List<PrepareBuildProjectsTask>> result = buildsManager.getProjectsInPrepareBuildQueue();
assertEquals( 1, result.size() );
assertTrue( queueName + " should be present in result", result.containsKey( queueName ) );
assertEquals( tasks, result.get( queueName ) );
}
@Test
public void testRemoveProjectFromPrepareBuildQueue()
throws Exception
{
setupMockOverallBuildQueues();
when( overallBuildQueue.isInPrepareBuildQueue( 1, 2 ) ).thenReturn( true );
buildsManager.removeProjectFromPrepareBuildQueue( 1, 2 );
verify( overallBuildQueue ).removeProjectFromPrepareBuildQueue( 1, 2 );
}
/*
public void testNumOfAllowedParallelBuildsIsLessThanConfiguredBuildQueues()
throws Exception
{
}
public void testPrepareBuildProjects()
throws Exception
{
}
public void testRemoveProjectFromPrepareBuildQueue()
throws Exception
{
}
*/
}
| 5,057 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/OrphanBuildStatusUpdaterTest.java | package org.apache.continuum.builder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.builder.distributed.work.BuildStatusUpdater;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.maven.continuum.AbstractContinuumTest;
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.store.ContinuumStoreException;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.apache.maven.continuum.project.ContinuumProjectState.*;
import static org.junit.Assert.assertEquals;
public class OrphanBuildStatusUpdaterTest
extends AbstractContinuumTest
{
private final int ageCutoff = 2;
private BuildResultDao resultDao;
private BuildDefinitionDao buildDefDao;
private List<BuildResult> aged = new ArrayList<BuildResult>();
private List<BuildResult> recent = new ArrayList<BuildResult>();
private BuildDefinition defOne;
private BuildDefinition defTwo;
private OrphanBuildStatusUpdater updater;
@Before
public void populateTestData()
throws Exception
{
updater = (OrphanBuildStatusUpdater) lookup( BuildStatusUpdater.class, "orphans" );
resultDao = lookup( BuildResultDao.class );
buildDefDao = lookup( BuildDefinitionDao.class );
defOne = addBuildDef();
defTwo = addBuildDef();
// NOTE: Build results added in build order - last added is most recent build
Project p1 = addProject( "One Too Young" );
addRecent( p1, defOne, BUILDING );
Project p2 = addProject( "One Orphan" );
addAged( p2, defOne, BUILDING );
Project p3 = addProject( "Two Orphans, Interleaved Success" );
addAged( p3, defTwo, BUILDING );
addRecent( p3, defTwo, OK );
addAged( p3, defTwo, BUILDING );
Project p4 = addProject( "Two Orphans, Interleaved Success, One Too Young" );
addAged( p4, defTwo, BUILDING );
addRecent( p4, defTwo, OK );
addAged( p4, defTwo, BUILDING );
addRecent( p4, defTwo, BUILDING );
Project p5 = addProject( "Two In-Progress, No Orphans" );
addAged( p5, defOne, BUILDING );
addAged( p5, defTwo, BUILDING );
Project p6 = addProject( "Two In-Progress, No Orphans (Diff Build Defs)" );
addRecent( p6, defOne, BUILDING );
addRecent( p6, defTwo, BUILDING );
updater.setOrphanAfterHours( ageCutoff );
}
@Test
public void testOrphansCanceled()
throws ContinuumStoreException
{
updater.performScan();
verifyUntouched( recent );
verifyCanceled( aged );
}
@Test
public void testDisabledByZeroCutoff()
throws ContinuumStoreException
{
updater.setOrphanAfterHours( 0 );
updater.performScan();
verifyUntouched( recent, aged );
}
@Test
public void testDisabledByNegativeCutoff()
throws ContinuumStoreException
{
updater.setOrphanAfterHours( Integer.MIN_VALUE );
updater.performScan();
verifyUntouched( recent, aged );
}
private void verifyUntouched( List<BuildResult>... resultLists )
throws ContinuumStoreException
{
for ( List<BuildResult> list : resultLists )
{
for ( BuildResult br : list )
{
assertEquals( "Status should not have been touched: " + br, br.getState(),
resultDao.getBuildResult( br.getId() ).getState() );
}
}
}
private void verifyCanceled( List<BuildResult>... resultLists )
throws ContinuumStoreException
{
for ( List<BuildResult> list : resultLists )
{
for ( BuildResult br : list )
{
assertEquals( "Status should be canceled: " + br, CANCELLED,
resultDao.getBuildResult( br.getId() ).getState() );
}
}
}
private BuildDefinition addBuildDef()
throws ContinuumStoreException
{
BuildDefinition def = new BuildDefinition();
def.setAlwaysBuild( false );
def.setBuildFresh( false );
def.setDefaultForProject( false );
def.setTemplate( false );
def = buildDefDao.addBuildDefinition( def );
return def;
}
private void addRecent( Project project, BuildDefinition buildDef, int state )
throws ContinuumStoreException
{
addResult( project, buildDef, state, recent, ageCutoff - 1 );
}
private void addAged( Project project, BuildDefinition buildDef, int state )
throws ContinuumStoreException
{
addResult( project, buildDef, state, aged, ageCutoff + 1 );
}
private void addResult( Project project, BuildDefinition buildDef, int state, List<BuildResult> expected,
long ageInHours )
throws ContinuumStoreException
{
BuildResult br = new BuildResult();
// nullability constraints
br.setBuildNumber( 0 );
br.setEndTime( 0 );
br.setExitCode( 0 );
br.setStartTime( System.currentTimeMillis() - ( 1000 * 60 * 60 * ageInHours ) );
br.setTrigger( 0 );
// associate relationship
br.setBuildDefinition( buildDef );
// set the build result
br.setState( state );
// persist the result
resultDao.addBuildResult( project, br );
br = resultDao.getBuildResult( br.getId() );
expected.add( br );
}
}
| 5,058 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed/stubs/DefaultDistributedBuildManagerStub.java | package org.apache.continuum.builder.distributed.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.builder.distributed.manager.DefaultDistributedBuildManager;
import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService;
public class DefaultDistributedBuildManagerStub
extends DefaultDistributedBuildManager
{
@Override
public SlaveBuildAgentTransportService createSlaveBuildAgentTransportClientConnection( String buildAgentUrl )
{
return new SlaveBuildAgentTransportClientStub();
}
}
| 5,059 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed/stubs/SlaveBuildAgentTransportClientStub.java | package org.apache.continuum.builder.distributed.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class SlaveBuildAgentTransportClientStub
implements SlaveBuildAgentTransportService
{
public Boolean buildProjects( List<Map<String, Object>> projectsBuildContext )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean cancelBuild()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public String generateWorkingCopyContent( int projectId, String directory, String baseUrl, String imagesBaseUrl )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public List<Map<String, String>> getAvailableInstallations()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Map<String, Object> getBuildResult( int projectId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Integer getBuildSizeOfAgent()
throws Exception
{
// TODO Auto-generated method stub
return 0;
}
public Map getListener( String releaseId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public String getPreparedReleaseName( String releaseId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Map<String, Object> getProjectCurrentlyBuilding()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Map<String, Object> getProjectCurrentlyPreparingBuild()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Map<String, Object> getProjectFile( int projectId, String directory, String filename )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public List<Map<String, Object>> getProjectsInBuildQueue()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public List<Map<String, Object>> getProjectsInPrepareBuildQueue()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Map getReleasePluginParameters( int projectId, String pomFilename )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Map<String, Object> getReleaseResult( String releaseId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectGroupInQueue( int projectGroupId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectScmRootInQueue( int projectScmRootId, List<Integer> projectIds )
{
return true;
}
public Boolean isProjectInBuildQueue( int projectId, int buildDefinitionId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean ping()
throws Exception
{
return true;
}
public List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public String releaseCleanup( String releaseId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile,
Map repository, String username )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
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
{
// TODO Auto-generated method stub
return null;
}
public String releasePrepare( Map project, Properties properties, Map releaseVersion, Map developmentVersion,
Map environments, String username )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean releaseRollback( String releaseId, int projectId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean removeFromBuildQueue( int projectId, int buildDefinitionId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean removeFromBuildQueue( List<String> hashCodes )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean removeFromPrepareBuildQueue( List<String> hashCodes )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean removeListener( String releaseId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public List<Map<String, Object>> getProjectsAndBuildDefinitionsCurrentlyPreparingBuild()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public List<Map<String, Object>> getProjectsAndBuildDefinitionsInPrepareBuildQueue()
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectGroupInPrepareBuildQueue( int projectGroupId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public String getBuildAgentPlatform()
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public Boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId )
throws Exception
{
// TODO Auto-generated method stub
return null;
}
public void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll )
throws Exception
{
// TODO Auto-generated method stub
}
public void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll,
boolean deleteReleasedSnapshots )
throws Exception
{
}
}
| 5,060 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed/manager/DefaultDistributedBuildManagerTest.java | package org.apache.continuum.builder.distributed.manager;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.builder.distributed.executor.ThreadedDistributedBuildTaskQueueExecutor;
import org.apache.continuum.builder.distributed.stubs.DefaultDistributedBuildManagerStub;
import org.apache.continuum.configuration.BuildAgentConfiguration;
import org.apache.continuum.configuration.BuildAgentGroupConfiguration;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.dao.ProjectScmRootDao;
import org.apache.continuum.model.project.ProjectRunSummary;
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.continuum.taskqueue.BuildProjectTask;
import org.apache.continuum.taskqueue.OverallDistributedBuildQueue;
import org.apache.continuum.taskqueue.PrepareBuildProjectsTask;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.PlexusSpringTestCase;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.system.Profile;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.codehaus.plexus.taskqueue.Task;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class DefaultDistributedBuildManagerTest
extends PlexusSpringTestCase
{
private final String TEST_BUILD_AGENT1 = "http://sampleagent";
private final String TEST_BUILD_AGENT2 = "http://testagent";
private final String TEST_BUILD_AGENT_GROUP1 = "buildAgentGroup1";
private DefaultDistributedBuildManager distributedBuildManager;
private DefaultDistributedBuildManager distributedBuildManagerStub = new DefaultDistributedBuildManagerStub();
private OverallDistributedBuildQueue overallDistributedBuildQueue1;
private OverallDistributedBuildQueue overallDistributedBuildQueue2;
private BuildDefinitionDao buildDefinitionDao;
private BuildResultDao buildResultDao;
private ProjectDao projectDao;
private ProjectScmRootDao projectScmRootDao;
private ConfigurationService configurationService;
private List<BuildAgentConfiguration> buildAgents;
private BuildAgentConfiguration buildAgent1;
private BuildAgentConfiguration buildAgent2;
private ThreadedDistributedBuildTaskQueueExecutor distributedBuildTaskQueueExecutor;
private TaskQueue distributedBuildQueue;
private Project project;
private Project project2;
private ProjectGroup projectGroup;
private BuildDefinition buildDefinition;
private BuildAgentGroupConfiguration buildAgentGroup;
@Before
public void setUp()
throws Exception
{
distributedBuildManager = (DefaultDistributedBuildManager) lookup( DistributedBuildManager.class );
buildDefinitionDao = mock( BuildDefinitionDao.class );
distributedBuildManager.setBuildDefinitionDao( buildDefinitionDao );
distributedBuildManagerStub.setBuildDefinitionDao( buildDefinitionDao );
buildResultDao = mock( BuildResultDao.class );
distributedBuildManager.setBuildResultDao( buildResultDao );
distributedBuildManagerStub.setBuildResultDao( buildResultDao );
projectDao = mock( ProjectDao.class );
distributedBuildManager.setProjectDao( projectDao );
distributedBuildManagerStub.setProjectDao( projectDao );
projectScmRootDao = mock( ProjectScmRootDao.class );
distributedBuildManager.setProjectScmRootDao( projectScmRootDao );
distributedBuildManagerStub.setProjectScmRootDao( projectScmRootDao );
distributedBuildManagerStub.setContainer( getContainer() );
configurationService = mock( ConfigurationService.class );
distributedBuildManager.setConfigurationService( configurationService );
distributedBuildManagerStub.setConfigurationService( configurationService );
distributedBuildTaskQueueExecutor =
mock( ThreadedDistributedBuildTaskQueueExecutor.class, "distributed-build-project" );
distributedBuildQueue = mock( TaskQueue.class, "distributed-build-queue" );
overallDistributedBuildQueue1 = mock( OverallDistributedBuildQueue.class, TEST_BUILD_AGENT1 );
overallDistributedBuildQueue2 = mock( OverallDistributedBuildQueue.class, TEST_BUILD_AGENT2 );
init();
}
private void init()
{
buildAgent1 = new BuildAgentConfiguration();
buildAgent1.setEnabled( true );
buildAgent1.setUrl( TEST_BUILD_AGENT1 );
buildAgent2 = new BuildAgentConfiguration();
buildAgent2.setEnabled( true );
buildAgent2.setUrl( TEST_BUILD_AGENT2 );
List<BuildAgentConfiguration> buildAgents = new ArrayList<BuildAgentConfiguration>();
buildAgents.add( buildAgent1 );
buildAgents.add( buildAgent2 );
setUpBuildAgentGroup( buildAgents );
setupBuildDefinition();
projectGroup = new ProjectGroup();
projectGroup.setId( 1 );
projectGroup.setGroupId( "group" );
project = new Project();
project.setId( 1 );
project.setGroupId( "groupId" );
project.setArtifactId( "artifactId" );
project.setVersion( "1.0" );
project.setProjectGroup( projectGroup );
project2 = new Project();
project2.setId( 2 );
project2.setGroupId( "groupId" );
project2.setArtifactId( "artifactId" );
project2.setVersion( "1.0" );
project2.setProjectGroup( projectGroup );
}
@Test
public void testViewQueuesAfterBuildAgentIsLost()
throws Exception
{
distributedBuildManager.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 1 ) );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
when( configurationService.getSharedSecretPassword() ).thenReturn( null );
when( overallDistributedBuildQueue1.getDistributedBuildTaskQueueExecutor() ).thenReturn(
distributedBuildTaskQueueExecutor );
when( distributedBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallDistributedBuildQueue1.getProjectsInQueue() ).thenReturn(
new ArrayList<PrepareBuildProjectsTask>() );
when( overallDistributedBuildQueue1.getDistributedBuildQueue() ).thenReturn( distributedBuildQueue );
Map<String, List<PrepareBuildProjectsTask>> prepareBuildQueues =
distributedBuildManager.getProjectsInPrepareBuildQueue();
Map<String, List<BuildProjectTask>> buildQueues = distributedBuildManager.getProjectsInBuildQueue();
Map<String, PrepareBuildProjectsTask> currentPrepareBuild =
distributedBuildManager.getProjectsCurrentlyPreparingBuild();
Map<String, BuildProjectTask> currentBuild = distributedBuildManager.getProjectsCurrentlyBuilding();
assertEquals( prepareBuildQueues.size(), 0 );
assertEquals( buildQueues.size(), 0 );
assertEquals( currentPrepareBuild.size(), 0 );
assertEquals( currentBuild.size(), 0 );
verify( configurationService ).updateBuildAgent( buildAgent1 );
verify( configurationService ).store();
verify( distributedBuildQueue ).removeAll( anyList() );
verify( distributedBuildTaskQueueExecutor ).stop();
}
@Test
public void testDisableBuildAgentWhenUnavailableToPing()
throws Exception
{
distributedBuildManager.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 1 ) );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
when( configurationService.getSharedSecretPassword() ).thenReturn( null );
distributedBuildManager.isAgentAvailable( TEST_BUILD_AGENT1 );
verify( configurationService ).updateBuildAgent( buildAgent1 );
verify( configurationService ).store();
assertFalse( "build agent should have been disabled", buildAgent1.isEnabled() );
}
@Test
public void testViewQueuesWhen2BuildAgentsAreLost()
throws Exception
{
distributedBuildManager.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 2 ) );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
when( configurationService.getSharedSecretPassword() ).thenReturn( null );
when( overallDistributedBuildQueue1.getDistributedBuildTaskQueueExecutor() ).thenReturn(
distributedBuildTaskQueueExecutor );
when( overallDistributedBuildQueue2.getDistributedBuildTaskQueueExecutor() ).thenReturn(
distributedBuildTaskQueueExecutor );
when( distributedBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallDistributedBuildQueue1.getProjectsInQueue() ).thenReturn(
new ArrayList<PrepareBuildProjectsTask>() );
when( overallDistributedBuildQueue2.getProjectsInQueue() ).thenReturn(
new ArrayList<PrepareBuildProjectsTask>() );
when( overallDistributedBuildQueue1.getDistributedBuildQueue() ).thenReturn( distributedBuildQueue );
when( overallDistributedBuildQueue2.getDistributedBuildQueue() ).thenReturn( distributedBuildQueue );
Map<String, List<PrepareBuildProjectsTask>> prepareBuildQueues =
distributedBuildManager.getProjectsInPrepareBuildQueue();
Map<String, List<BuildProjectTask>> buildQueues = distributedBuildManager.getProjectsInBuildQueue();
Map<String, PrepareBuildProjectsTask> currentPrepareBuild =
distributedBuildManager.getProjectsCurrentlyPreparingBuild();
Map<String, BuildProjectTask> currentBuild = distributedBuildManager.getProjectsCurrentlyBuilding();
assertEquals( prepareBuildQueues.size(), 0 );
assertEquals( buildQueues.size(), 0 );
assertEquals( currentPrepareBuild.size(), 0 );
assertEquals( currentBuild.size(), 0 );
verify( configurationService ).updateBuildAgent( buildAgent1 );
verify( configurationService ).updateBuildAgent( buildAgent2 );
verify( configurationService, times( 2 ) ).store();
verify( distributedBuildQueue, times( 2 ) ).removeAll( anyList() );
verify( distributedBuildTaskQueueExecutor, times( 2 ) ).stop();
}
@Test
public void testBuildProjectWithBuildAgentGroupWithNoCurrentBuilds()
throws Exception
{
distributedBuildManagerStub.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 2 ) );
Map<Integer, Integer> projectsBuildDefinitionsMap = new HashMap<Integer, Integer>();
projectsBuildDefinitionsMap.put( 1, 1 );
projectsBuildDefinitionsMap.put( 2, 1 );
BuildTrigger buildTrigger = new BuildTrigger( 1 );
when( projectDao.getProjectWithDependencies( 1 ) ).thenReturn( project );
when( projectDao.getProjectWithDependencies( 2 ) ).thenReturn( project2 );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( buildDefinition );
when( configurationService.getBuildAgentGroup( TEST_BUILD_AGENT_GROUP1 ) ).thenReturn( buildAgentGroup );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
List<ProjectScmRoot> scmRoots = new ArrayList<ProjectScmRoot>();
ProjectScmRoot scmRoot = new ProjectScmRoot();
scmRoot.setId( 1 );
scmRoot.setProjectGroup( projectGroup );
scmRoot.setScmRootAddress( "scmRootAddress1" );
scmRoots.add( scmRoot );
scmRoot = new ProjectScmRoot();
scmRoot.setId( 2 );
scmRoot.setProjectGroup( projectGroup );
scmRoot.setScmRootAddress( "scmRootAddress2" );
scmRoots.add( scmRoot );
distributedBuildManagerStub.prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, 1, "sample",
"scmRootAddress1", 1, scmRoots );
verify( overallDistributedBuildQueue1 ).getBuildAgentUrl();
verify( overallDistributedBuildQueue1 ).addToDistributedBuildQueue( any( Task.class ) );
}
@Test
public void testBuildProjectWithBuildAgentGroupWithCurrentBuild()
throws Exception
{
distributedBuildManagerStub.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 2 ) );
Map<Integer, Integer> projectsBuildDefinitionsMap = new HashMap<Integer, Integer>();
projectsBuildDefinitionsMap.put( 1, 1 );
BuildTrigger buildTrigger = new BuildTrigger( 1 );
when( overallDistributedBuildQueue1.getDistributedBuildTaskQueueExecutor() ).thenReturn(
distributedBuildTaskQueueExecutor );
when( distributedBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( projectDao.getProjectsInGroup( 1 ) ).thenReturn( new ArrayList<Project>() );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
List<ProjectScmRoot> scmRoots = new ArrayList<ProjectScmRoot>();
ProjectScmRoot scmRoot = new ProjectScmRoot();
scmRoot.setId( 2 );
scmRoot.setProjectGroup( projectGroup );
scmRoot.setScmRootAddress( "scmRootAddress2" );
scmRoots.add( scmRoot );
scmRoot = new ProjectScmRoot();
scmRoot.setId( 1 );
scmRoot.setProjectGroup( projectGroup );
scmRoot.setScmRootAddress( "scmRootAddress1" );
scmRoots.add( scmRoot );
distributedBuildManagerStub.prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, 1, "sample",
"scmRootAddress1", 1, scmRoots );
verify( overallDistributedBuildQueue1 ).getProjectsInQueue();
verify( overallDistributedBuildQueue1 ).getBuildAgentUrl();
verify( overallDistributedBuildQueue1 ).addToDistributedBuildQueue( any( Task.class ) );
}
// CONTINUUM-2494
@Test
public void testBuildProjectWithTheSecondBuildAgentAttachedToTheBuildAgentGroup()
throws Exception
{
distributedBuildManagerStub.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 2 ) );
final List<BuildAgentConfiguration> buildAgents = new ArrayList<BuildAgentConfiguration>();
buildAgents.add( buildAgent2 );
setUpBuildAgentGroup( buildAgents );
setupBuildDefinition();
Map<Integer, Integer> projectsBuildDefinitionsMap = new HashMap<Integer, Integer>();
projectsBuildDefinitionsMap.put( 1, 1 );
BuildTrigger buildTrigger = new BuildTrigger( 1 );
when( projectDao.getProjectWithDependencies( 1 ) ).thenReturn( project );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( buildDefinition );
when( configurationService.getBuildAgentGroup( TEST_BUILD_AGENT_GROUP1 ) ).thenReturn( buildAgentGroup );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
List<ProjectScmRoot> scmRoots = new ArrayList<ProjectScmRoot>();
ProjectScmRoot scmRoot = new ProjectScmRoot();
scmRoot.setId( 1 );
scmRoot.setProjectGroup( projectGroup );
scmRoot.setScmRootAddress( "scmRootAddress1" );
scmRoots.add( scmRoot );
distributedBuildManagerStub.prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, 1, "sample",
"scmRootAddress", 1, scmRoots );
verify( overallDistributedBuildQueue2 ).getBuildAgentUrl();
verify( overallDistributedBuildQueue2 ).addToDistributedBuildQueue( any( Task.class ) );
}
@Test
public void testGetBuildAgentPlatform()
throws Exception
{
distributedBuildManager.setOverallDistributedBuildQueues( getMockOverallDistributedBuildQueues( 1 ) );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
when( configurationService.getSharedSecretPassword() ).thenReturn( null );
when( overallDistributedBuildQueue1.getDistributedBuildTaskQueueExecutor() ).thenReturn(
distributedBuildTaskQueueExecutor );
when( distributedBuildTaskQueueExecutor.getCurrentTask() ).thenReturn( null );
when( overallDistributedBuildQueue1.getProjectsInQueue() ).thenReturn(
new ArrayList<PrepareBuildProjectsTask>() );
when( overallDistributedBuildQueue1.getDistributedBuildQueue() ).thenReturn( distributedBuildQueue );
assertEquals( distributedBuildManager.getBuildAgentPlatform( TEST_BUILD_AGENT1 ), "" );
verify( configurationService ).updateBuildAgent( buildAgent1 );
verify( configurationService ).store();
verify( distributedBuildQueue ).removeAll( anyList() );
verify( distributedBuildTaskQueueExecutor ).stop();
}
@Test
public void testBuildAgentIsAvailable()
throws Exception
{
assertTrue( distributedBuildManagerStub.isAgentAvailable( TEST_BUILD_AGENT1 ) );
verify( configurationService, never() ).getBuildAgents();
verify( configurationService, never() ).updateBuildAgent( buildAgent1 );
verify( configurationService, never() ).store();
}
@Test
public void testCancelBuildStuckUpdate()
throws Exception
{
distributedBuildManagerStub.setCurrentRuns( getCurrentRuns() );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
ProjectScmRoot scmRootUpdating = getScmRoot( ContinuumProjectState.UPDATING );
when( projectScmRootDao.getProjectScmRoot( 1 ) ).thenReturn( scmRootUpdating,
getScmRoot( ContinuumProjectState.ERROR ) );
distributedBuildManagerStub.cancelBuild( 1 );
verify( projectScmRootDao ).updateProjectScmRoot( scmRootUpdating );
}
@Test
public void testCancelBuildStuckBuild()
throws Exception
{
distributedBuildManagerStub.setCurrentRuns( getCurrentRuns() );
when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
when( projectScmRootDao.getProjectScmRoot( 1 ) ).thenReturn( getScmRoot( ContinuumProjectState.OK ) );
Project proj1 = getProject( 1, ContinuumProjectState.BUILDING );
when( projectDao.getProject( 1 ) ).thenReturn( proj1 );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( new BuildDefinition() );
when( projectDao.getProject( 2 ) ).thenReturn( getProject( 2, ContinuumProjectState.OK ) );
distributedBuildManagerStub.cancelBuild( 1 );
verify( buildResultDao ).addBuildResult( any( Project.class ), any( BuildResult.class ) );
verify( projectDao ).updateProject( proj1 );
}
private List<ProjectRunSummary> getCurrentRuns()
{
List<ProjectRunSummary> runs = new ArrayList<ProjectRunSummary>();
ProjectRunSummary run1 = new ProjectRunSummary();
run1.setProjectId( 1 );
run1.setBuildDefinitionId( 1 );
run1.setProjectGroupId( 1 );
run1.setProjectScmRootId( 1 );
run1.setTrigger( 1 );
run1.setTriggeredBy( "user" );
run1.setBuildAgentUrl( "http://localhost:8181/continuum-buildagent/xmlrpc" );
runs.add( run1 );
ProjectRunSummary run2 = new ProjectRunSummary();
run2.setProjectId( 2 );
run2.setBuildDefinitionId( 2 );
run2.setProjectGroupId( 1 );
run2.setProjectScmRootId( 1 );
run2.setTrigger( 1 );
run2.setTriggeredBy( "user" );
run2.setBuildAgentUrl( "http://localhost:8181/continuum-buildagent/xmlrpc" );
runs.add( run2 );
return runs;
}
private ProjectScmRoot getScmRoot( int state )
{
ProjectScmRoot scmRoot = new ProjectScmRoot();
scmRoot.setState( state );
return scmRoot;
}
private Project getProject( int projectId, int state )
{
Project project = new Project();
project.setId( projectId );
project.setState( state );
return project;
}
private Map<String, OverallDistributedBuildQueue> getMockOverallDistributedBuildQueues( int size )
{
Map<String, OverallDistributedBuildQueue> overallDistributedBuildQueues = Collections.synchronizedMap(
new LinkedHashMap<String, OverallDistributedBuildQueue>() );
buildAgents = new ArrayList<BuildAgentConfiguration>();
buildAgents.add( buildAgent1 );
overallDistributedBuildQueues.put( TEST_BUILD_AGENT1, overallDistributedBuildQueue1 );
if ( size == 2 )
{
buildAgents.add( buildAgent2 );
overallDistributedBuildQueues.put( TEST_BUILD_AGENT2, overallDistributedBuildQueue2 );
}
return overallDistributedBuildQueues;
}
private void setUpBuildAgentGroup( List<BuildAgentConfiguration> buildAgents )
{
buildAgentGroup = new BuildAgentGroupConfiguration();
buildAgentGroup.setName( TEST_BUILD_AGENT_GROUP1 );
buildAgentGroup.setBuildAgents( buildAgents );
}
private void setupBuildDefinition()
{
Profile buildEnv1 = new Profile();
buildEnv1.setBuildAgentGroup( TEST_BUILD_AGENT_GROUP1 );
buildDefinition = new BuildDefinition();
buildDefinition.setId( 1 );
buildDefinition.setProfile( buildEnv1 );
}
} | 5,061 |
0 | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed | Create_ds/continuum/continuum-core/src/test/java/org/apache/continuum/builder/distributed/work/DistributedBuildStatusUpdaterTest.java | package org.apache.continuum.builder.distributed.work;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.builder.distributed.manager.DistributedBuildManager;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.dao.ProjectScmRootDao;
import org.apache.continuum.model.project.ProjectRunSummary;
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.maven.continuum.PlexusSpringTestCase;
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.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.*;
public class DistributedBuildStatusUpdaterTest
extends PlexusSpringTestCase
{
private ProjectDao projectDao;
private ProjectScmRootDao projectScmRootDao;
private BuildDefinitionDao buildDefinitionDao;
private BuildResultDao buildResultDao;
private DistributedBuildManager distributedBuildManager;
private ConfigurationService configurationService;
private DistributedBuildStatusUpdater worker;
@Before
public void setUp()
throws Exception
{
projectDao = mock( ProjectDao.class );
projectScmRootDao = mock( ProjectScmRootDao.class );
buildDefinitionDao = mock( BuildDefinitionDao.class );
buildResultDao = mock( BuildResultDao.class );
configurationService = mock( ConfigurationService.class );
distributedBuildManager = mock( DistributedBuildManager.class );
worker = (DistributedBuildStatusUpdater) lookup( BuildStatusUpdater.class, "distributed" );
worker.setBuildDefinitionDao( buildDefinitionDao );
worker.setBuildResultDao( buildResultDao );
worker.setProjectDao( projectDao );
worker.setProjectScmRootDao( projectScmRootDao );
worker.setConfigurationService( configurationService );
worker.setDistributedBuildManager( distributedBuildManager );
when( configurationService.isDistributedBuildEnabled() ).thenReturn( true );
when( distributedBuildManager.getCurrentRuns() ).thenReturn( getCurrentRuns() );
}
@Test
public void testWorkerWithStuckBuild()
throws Exception
{
Project project1 = getProject( 1, ContinuumProjectState.BUILDING );
when( projectScmRootDao.getProjectScmRoot( 1 ) ).thenReturn( getScmRoot( ContinuumProjectState.OK ) );
when( projectDao.getProject( 1 ) ).thenReturn( project1 );
when( distributedBuildManager.isProjectCurrentlyBuilding( 1, 1 ) ).thenReturn( false );
when( buildDefinitionDao.getBuildDefinition( 1 ) ).thenReturn( new BuildDefinition() );
when( projectDao.getProject( 2 ) ).thenReturn( getProject( 2, ContinuumProjectState.OK ) );
worker.performScan();
verify( buildResultDao ).addBuildResult( any( Project.class ), any( BuildResult.class ) );
verify( projectDao ).updateProject( project1 );
}
@Test
public void testWorkerWithStuckScm()
throws Exception
{
ProjectScmRoot scmRootUpdating = getScmRoot( ContinuumProjectState.UPDATING );
when( projectScmRootDao.getProjectScmRoot( 1 ) ).thenReturn( scmRootUpdating,
getScmRoot( ContinuumProjectState.ERROR ) );
when( distributedBuildManager.isProjectCurrentlyPreparingBuild( 1, 1 ) ).thenReturn( false );
worker.performScan();
verify( projectScmRootDao ).updateProjectScmRoot( scmRootUpdating );
}
private List<ProjectRunSummary> getCurrentRuns()
{
List<ProjectRunSummary> runs = new ArrayList<ProjectRunSummary>();
ProjectRunSummary run1 = new ProjectRunSummary();
run1.setProjectId( 1 );
run1.setBuildDefinitionId( 1 );
run1.setProjectGroupId( 1 );
run1.setProjectScmRootId( 1 );
run1.setTrigger( 1 );
run1.setTriggeredBy( "user" );
run1.setBuildAgentUrl( "http://localhost:8181/continuum-buildagent/xmlrpc" );
runs.add( run1 );
ProjectRunSummary run2 = new ProjectRunSummary();
run2.setProjectId( 2 );
run2.setBuildDefinitionId( 2 );
run2.setProjectGroupId( 1 );
run2.setProjectScmRootId( 1 );
run2.setTrigger( 1 );
run2.setTriggeredBy( "user" );
run2.setBuildAgentUrl( "http://localhost:8181/continuum-buildagent/xmlrpc" );
runs.add( run2 );
return runs;
}
private ProjectScmRoot getScmRoot( int state )
{
ProjectScmRoot scmRoot = new ProjectScmRoot();
scmRoot.setState( state );
return scmRoot;
}
private Project getProject( int projectId, int state )
{
Project project = new Project();
project.setId( projectId );
project.setState( state );
return project;
}
}
| 5,062 |
0 | Create_ds/continuum/continuum-core/src/test-projects/project1/src/main/java/org/codehaus/continuum | Create_ds/continuum/continuum-core/src/test-projects/project1/src/main/java/org/codehaus/continuum/project1/App.java | package org.codehaus.plexus.continuum.project1;
public class App
{
public static void main( String[] args )
{
System.out.println( "OK" );
}
}
| 5,063 |
0 | Create_ds/continuum/continuum-core/src/test-projects/timeout/src/test/java/org/apache/maven/continuum/testprojects | Create_ds/continuum/continuum-core/src/test-projects/timeout/src/test/java/org/apache/maven/continuum/testprojects/timeout/TimeoutTest.java | package projects.timeout.src.test.java.org.apache.maven.continuum.testprojects.timeout;
/*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileOutputStream;
import junit.framework.TestCase;
/**
* This is a 'long running' test, with pre/post file events, allowing
* Continuum to test aborting tasks.
*
* @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a>
*/
public class TimeoutTest
extends TestCase
{
public void testTimeout()
throws Exception
{
deleteFile( "target/TEST-COMPLETED" );
createFile( "target/TEST-STARTED", "Test started" );
System.err.println( "Sleeping for 15 seconds." );
Thread.sleep( 15000 );
createFile( "target/TEST-COMPLETED", "Test completed" );
}
private static void createFile( String filename, String content )
throws Exception
{
FileOutputStream fout = new FileOutputStream( filename );
fout.write( content.getBytes() );
fout.close();
}
private static void deleteFile( String filename )
throws Exception
{
new File( filename ).delete();
}
}
| 5,064 |
0 | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-b/src/test/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-b/src/test/java/org/apache/continuum/module/b/AppTest.java | package org.apache.continuum.module.b;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 5,065 |
0 | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-b/src/main/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-b/src/main/java/org/apache/continuum/module/b/App.java | package org.apache.continuum.module.b;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| 5,066 |
0 | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-c/module-d/src/test/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-c/module-d/src/test/java/org/apache/continuum/module/d/AppTest.java | package org.apache.continuum.module.a;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 5,067 |
0 | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-c/module-d/src/main/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-c/module-d/src/main/java/org/apache/continuum/module/d/App.java | package org.apache.continuum.module.d;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| 5,068 |
0 | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-a/src/test/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-a/src/test/java/org/apache/continuum/module/a/AppTest.java | package org.apache.continuum.module.a;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 5,069 |
0 | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-a/src/main/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/flat-multi-module/module-a/src/main/java/org/apache/continuum/module/a/App.java | package org.apache.continuum.module.a;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| 5,070 |
0 | Create_ds/continuum/continuum-core/src/test-projects/project2/src/main/java/org/codehaus/continuum | Create_ds/continuum/continuum-core/src/test-projects/project2/src/main/java/org/codehaus/continuum/project2/App.java | package org.codehaus.continuum.project2;
public class App
{
public static void main( String[] args )
{
System.out.println( "OK" );
}
}
| 5,071 |
0 | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-B/src/test/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-B/src/test/java/org/apache/continuum/module/b/AppTest.java | package org.apache.continuum.module.b;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 5,072 |
0 | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-B/src/main/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-B/src/main/java/org/apache/continuum/module/b/App.java | package org.apache.continuum.module.b;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| 5,073 |
0 | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-C/module-D/src/test/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-C/module-D/src/test/java/org/apache/continuum/module/b/AppTest.java | package org.apache.continuum.module.b;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 5,074 |
0 | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-C/module-D/src/main/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-C/module-D/src/main/java/org/apache/continuum/module/c/App.java | package org.apache.continuum.module.c;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| 5,075 |
0 | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-A/test/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-A/test/java/org/apache/continuum/module/a/AppTest.java | package org.apache.continuum.module.a;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 5,076 |
0 | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-A/src/main/java/org/apache/continuum/module | Create_ds/continuum/continuum-core/src/test-projects/multi-module/module-A/src/main/java/org/apache/continuum/module/a/App.java | package org.apache.continuum.module.a;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| 5,077 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/DefaultContinuum.java | package org.apache.maven.continuum;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildagent.NoBuildAgentException;
import org.apache.continuum.buildagent.NoBuildAgentInGroupException;
import org.apache.continuum.builder.distributed.manager.DistributedBuildManager;
import org.apache.continuum.buildmanager.BuildManagerException;
import org.apache.continuum.buildmanager.BuildsManager;
import org.apache.continuum.buildqueue.BuildQueueService;
import org.apache.continuum.buildqueue.BuildQueueServiceException;
import org.apache.continuum.configuration.BuildAgentConfigurationException;
import org.apache.continuum.configuration.ContinuumConfigurationException;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ContinuumReleaseResultDao;
import org.apache.continuum.dao.DaoUtils;
import org.apache.continuum.dao.NotifierDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.continuum.dao.ProjectScmRootDao;
import org.apache.continuum.dao.ScheduleDao;
import org.apache.continuum.model.project.ProjectGroupSummary;
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.continuum.model.release.ContinuumReleaseResult;
import org.apache.continuum.purge.ContinuumPurgeManager;
import org.apache.continuum.purge.PurgeConfigurationService;
import org.apache.continuum.release.config.ContinuumReleaseDescriptor;
import org.apache.continuum.release.distributed.manager.DistributedReleaseManager;
import org.apache.continuum.release.model.PreparedRelease;
import org.apache.continuum.repository.RepositoryService;
import org.apache.continuum.taskqueue.manager.TaskQueueManager;
import org.apache.continuum.taskqueue.manager.TaskQueueManagerException;
import org.apache.continuum.utils.ProjectSorter;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.continuum.utils.file.FileSystemManager;
import org.apache.maven.continuum.build.BuildException;
import org.apache.maven.continuum.build.settings.SchedulesActivationException;
import org.apache.maven.continuum.build.settings.SchedulesActivator;
import org.apache.maven.continuum.builddefinition.BuildDefinitionService;
import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException;
import org.apache.maven.continuum.configuration.ConfigurationException;
import org.apache.maven.continuum.configuration.ConfigurationLoadingException;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.core.action.AbstractContinuumAction;
import org.apache.maven.continuum.core.action.CheckoutProjectContinuumAction;
import org.apache.maven.continuum.core.action.CreateProjectsFromMetadataAction;
import org.apache.maven.continuum.core.action.StoreProjectAction;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.initialization.ContinuumInitializationException;
import org.apache.maven.continuum.initialization.ContinuumInitializer;
import org.apache.maven.continuum.installation.InstallationService;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.BuildQueue;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.apache.maven.continuum.model.project.Schedule;
import org.apache.maven.continuum.model.scm.ChangeSet;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.profile.ProfileService;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.continuum.project.builder.maven.MavenOneContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.maven.MavenTwoContinuumProjectBuilder;
import org.apache.maven.continuum.release.ContinuumReleaseException;
import org.apache.maven.continuum.release.ContinuumReleaseManager;
import org.apache.maven.continuum.store.ContinuumObjectNotFoundException;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.apache.maven.continuum.utils.ContinuumUrlValidator;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.apache.maven.shared.release.ReleaseResult;
import org.codehaus.plexus.action.Action;
import org.codehaus.plexus.action.ActionManager;
import org.codehaus.plexus.action.ActionNotFoundException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author <a href="mailto:jason@maven.org">Jason van Zyl</a>
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl </a>
*/
@Component( role = org.apache.maven.continuum.Continuum.class, hint = "default" )
public class DefaultContinuum
implements Continuum, Initializable, Startable
{
private static final Logger log = LoggerFactory.getLogger( DefaultContinuum.class );
@Requirement
private ActionManager actionManager;
@Requirement
private ConfigurationService configurationService;
@Requirement
private DaoUtils daoUtils;
@Requirement
private BuildDefinitionDao buildDefinitionDao;
@Requirement
private BuildResultDao buildResultDao;
@Requirement
private NotifierDao notifierDao;
@Requirement
private ProjectDao projectDao;
@Requirement
private ProjectGroupDao projectGroupDao;
@Requirement
private ScheduleDao scheduleDao;
@Requirement
private ContinuumReleaseResultDao releaseResultDao;
@Requirement
private ProjectScmRootDao projectScmRootDao;
@Requirement
private ContinuumInitializer initializer;
@Requirement
private SchedulesActivator schedulesActivator;
@Requirement
private InstallationService installationService;
@Requirement
private ProfileService profileService;
@Requirement
private BuildDefinitionService buildDefinitionService;
// ----------------------------------------------------------------------
// Moved from core
// ----------------------------------------------------------------------
@Requirement
private ContinuumReleaseManager releaseManager;
@Requirement
private WorkingDirectoryService workingDirectoryService;
@Requirement
private BuildExecutorManager executorManager;
@Requirement( hint = "continuumUrl" )
private ContinuumUrlValidator urlValidator;
private boolean stopped = false;
@Requirement
private ContinuumPurgeManager purgeManager;
@Requirement
private RepositoryService repositoryService;
@Requirement
private PurgeConfigurationService purgeConfigurationService;
@Requirement
private TaskQueueManager taskQueueManager;
@Requirement( hint = "parallel" )
private BuildsManager parallelBuildsManager;
@Requirement
private BuildQueueService buildQueueService;
@Requirement
private DistributedBuildManager distributedBuildManager;
@Requirement
private DistributedReleaseManager distributedReleaseManager;
@Requirement
private FileSystemManager fsManager;
public DefaultContinuum()
{
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
stopContinuum();
}
} );
}
public ContinuumReleaseManager getReleaseManager()
{
return releaseManager;
}
public ContinuumPurgeManager getPurgeManager()
{
return purgeManager;
}
public RepositoryService getRepositoryService()
{
return repositoryService;
}
public TaskQueueManager getTaskQueueManager()
{
return taskQueueManager;
}
public PurgeConfigurationService getPurgeConfigurationService()
{
return purgeConfigurationService;
}
public BuildsManager getBuildsManager()
{
return parallelBuildsManager;
}
public DistributedReleaseManager getDistributedReleaseManager()
{
return distributedReleaseManager;
}
// ----------------------------------------------------------------------
// Project Groups
// ----------------------------------------------------------------------
public ProjectGroup getProjectGroup( int projectGroupId )
throws ContinuumException
{
try
{
return projectGroupDao.getProjectGroup( projectGroupId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "invalid group id", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while querying for project group.", e );
}
}
public ProjectGroup getProjectGroupWithProjects( int projectGroupId )
throws ContinuumException
{
try
{
return projectGroupDao.getProjectGroupWithProjects( projectGroupId );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "could not find project group containing " + projectGroupId );
}
}
public ProjectGroup getProjectGroupByProjectId( int projectId )
throws ContinuumException
{
try
{
return projectGroupDao.getProjectGroupByProjectId( projectId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "could not find project group containing " + projectId );
}
}
public void removeProjectGroup( int projectGroupId )
throws ContinuumException
{
ProjectGroup projectGroup = getProjectGroupWithProjects( projectGroupId );
if ( projectGroup != null )
{
List<Project> projects = projectGroup.getProjects();
int[] projectIds = new int[projects.size()];
int idx = 0;
for ( Project project : projects )
{
projectIds[idx] = project.getId();
idx++;
}
// check if any project is still being checked out
// canceling the checkout and proceeding with the delete results to a cannot delete directory error!
try
{
if ( parallelBuildsManager.isAnyProjectCurrentlyBeingCheckedOut( projectIds ) )
{
throw new ContinuumException(
"unable to remove group while project is being checked out" );
}
if ( parallelBuildsManager.isAnyProjectCurrentlyPreparingBuild( projectIds ) )
{
throw new ContinuumException(
"unable to remove group while build is being prepared" );
}
if ( parallelBuildsManager.isAnyProjectCurrentlyBuilding( projectIds ) )
{
throw new ContinuumException(
"unable to remove group while project is building" );
}
if ( isAnyProjectsInReleaseStage( projects ) )
{
throw new ContinuumException(
"unable to remove group while project is being released" );
}
}
catch ( BuildManagerException e )
{
throw new ContinuumException( e.getMessage() );
}
for ( int projectId : projectIds )
{
removeProject( projectId );
}
// check if there are any project scm root left
List<ProjectScmRoot> scmRoots = getProjectScmRootByProjectGroup( projectGroupId );
for ( ProjectScmRoot scmRoot : scmRoots )
{
removeProjectScmRoot( scmRoot );
}
log.info( "Remove project group " + projectGroup.getName() + "(" + projectGroup.getId() + ")" );
Map<String, Object> context = new HashMap<String, Object>();
AbstractContinuumAction.setProjectGroupId( context, projectGroup.getId() );
executeAction( "remove-assignable-roles", context );
projectGroupDao.removeProjectGroup( projectGroup );
}
}
public void addProjectGroup( ProjectGroup projectGroup )
throws ContinuumException
{
ProjectGroup pg = null;
try
{
pg = projectGroupDao.getProjectGroupByGroupId( projectGroup.getGroupId() );
}
catch ( ContinuumObjectNotFoundException e )
{
//since we want to add a new project group, we should be getting
//this exception
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Unable to add the requested project group", e );
}
if ( pg == null )
{
//CONTINUUM-1502
projectGroup.setName( projectGroup.getName().trim() );
try
{
ProjectGroup new_pg = projectGroupDao.addProjectGroup( projectGroup );
buildDefinitionService.addBuildDefinitionTemplateToProjectGroup( new_pg.getId(),
buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate() );
Map<String, Object> context = new HashMap<String, Object>();
AbstractContinuumAction.setProjectGroupId( context, new_pg.getId() );
executeAction( "add-assignable-roles", context );
log.info( "Added new project group: " + new_pg.getName() );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
else
{
throw new ContinuumException( "Unable to add the requested project group: groupId already exists." );
}
}
public List<ProjectGroup> getAllProjectGroups()
{
return new ArrayList<ProjectGroup>( projectGroupDao.getAllProjectGroups() );
}
public ProjectGroup getProjectGroupByGroupId( String groupId )
throws ContinuumException
{
try
{
return projectGroupDao.getProjectGroupByGroupId( groupId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find project group", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving", e );
}
}
public ProjectGroup getProjectGroupByGroupIdWithBuildDetails( String groupId )
throws ContinuumException
{
try
{
return projectGroupDao.getProjectGroupByGroupIdWithBuildDetails( groupId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find project group", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving", e );
}
}
public List<ProjectGroup> getAllProjectGroupsWithRepository( int repositoryId )
{
return projectGroupDao.getProjectGroupByRepository( repositoryId );
}
// ----------------------------------------------------------------------
// Projects
// ----------------------------------------------------------------------
/**
* TODO: Remove this method
*/
public Collection<Project> getProjects()
throws ContinuumException
{
return projectDao.getAllProjectsByName();
}
/**
* TODO: Remove this method
*/
public Collection<Project> getProjectsWithDependencies()
throws ContinuumException
{
return projectDao.getAllProjectsByNameWithDependencies();
}
public Map<Integer, BuildResult> getLatestBuildResults( int projectGroupId )
{
Map<Integer, BuildResult> result = buildResultDao.getLatestBuildResultsByProjectGroupId( projectGroupId );
if ( result == null )
{
result = new HashMap<Integer, BuildResult>();
}
return result;
}
public Map<Integer, BuildResult> getBuildResultsInSuccess( int projectGroupId )
{
Map<Integer, BuildResult> result = buildResultDao.getBuildResultsInSuccessByProjectGroupId( projectGroupId );
if ( result == null )
{
result = new HashMap<Integer, BuildResult>();
}
return result;
}
public BuildResult getLatestBuildResultForProject( int projectId )
{
return buildResultDao.getLatestBuildResultForProject( projectId );
}
public List<BuildResult> getBuildResultsInRange( Collection<Integer> projectGroupIds, Date fromDate, Date toDate,
int state, String triggeredBy, int offset, int length )
{
return buildResultDao.getBuildResultsInRange( fromDate, toDate, state, triggeredBy, projectGroupIds, offset,
length );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public void removeProject( int projectId )
throws ContinuumException
{
try
{
Project project = getProject( projectId );
try
{
if ( parallelBuildsManager.isProjectCurrentlyBeingCheckedOut( projectId ) )
{
throw new ContinuumException(
"Unable to remove project " + projectId + " because it is currently being checked out" );
}
if ( parallelBuildsManager.isProjectInAnyCurrentBuild( projectId ) )
{
throw new ContinuumException(
"Unable to remove project " + projectId + " because it is currently building" );
}
}
catch ( BuildManagerException e )
{
throw new ContinuumException( e.getMessage(), e );
}
if ( isProjectInReleaseStage( project ) )
{
throw new ContinuumException(
"Unable to remove project " + projectId + " because it is in release stage" );
}
try
{
parallelBuildsManager.removeProjectFromCheckoutQueue( projectId );
parallelBuildsManager.removeProjectFromBuildQueue( projectId );
}
catch ( BuildManagerException e )
{
throw new ContinuumException( e.getMessage(), e );
}
List<ContinuumReleaseResult> releaseResults = releaseResultDao.getContinuumReleaseResultsByProject(
projectId );
ProjectScmRoot scmRoot = getProjectScmRootByProject( projectId );
try
{
for ( ContinuumReleaseResult releaseResult : releaseResults )
{
releaseResultDao.removeContinuumReleaseResult( releaseResult );
}
File releaseOutputDirectory = configurationService.getReleaseOutputDirectory(
project.getProjectGroup().getId() );
if ( releaseOutputDirectory != null )
{
fsManager.removeDir( releaseOutputDirectory );
}
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while deleting continuum release result of project group", e );
}
catch ( IOException e )
{
throw logAndCreateException( "Error while deleting project group release output directory.", e );
}
log.info( "Remove project " + project.getName() + "(" + projectId + ")" );
// remove dependencies first to avoid key clash with build results
project = projectDao.getProjectWithDependencies( projectId );
project.setParent( null );
project.getDependencies().clear();
projectDao.updateProject( project );
// Remove build results in batches: the number of results could be very large
int batchSize = 100;
Collection<BuildResult> buildResults;
do
{
buildResults = buildResultDao.getBuildResultsForProject( projectId, 0, batchSize, true );
for ( BuildResult br : buildResults )
{
br.setBuildDefinition( null );
//Remove all modified dependencies to prevent SQL errors
br.getModifiedDependencies().clear();
buildResultDao.updateBuildResult( br );
removeBuildResult( br );
}
}
while ( buildResults != null && buildResults.size() > 0 );
File workingDirectory = getWorkingDirectory( projectId );
fsManager.removeDir( workingDirectory );
File buildOutputDirectory = configurationService.getBuildOutputDirectory( projectId );
fsManager.removeDir( buildOutputDirectory );
projectDao.removeProject( projectDao.getProject( projectId ) );
removeProjectScmRoot( scmRoot );
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Error while removing project in database.", ex );
}
catch ( IOException e )
{
throw logAndCreateException( "Error while deleting project working directory.", e );
}
}
/**
* @see org.apache.maven.continuum.Continuum#checkoutProject(int)
*/
public void checkoutProject( int projectId )
throws ContinuumException
{
Map<String, Object> context = new HashMap<String, Object>();
AbstractContinuumAction.setProjectId( context, projectId );
try
{
BuildDefinition buildDefinition = buildDefinitionDao.getDefaultBuildDefinition( projectId );
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
executeAction( "add-project-to-checkout-queue", context );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
public Project getProject( int projectId )
throws ContinuumException
{
try
{
return projectDao.getProject( projectId );
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Exception while getting project '" + projectId + "'.", ex );
}
}
public Project getProjectWithBuildDetails( int projectId )
throws ContinuumException
{
try
{
return projectDao.getProjectWithBuildDetails( projectId );
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Exception while getting project '" + projectId + "'.", ex );
}
}
public Map<Integer, ProjectGroupSummary> getProjectsSummaryByGroups()
{
return projectDao.getProjectsSummary();
}
// ----------------------------------------------------------------------
// Building
// ----------------------------------------------------------------------
public void buildProjects( String username )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
buildProjects( new BuildTrigger( ContinuumProjectState.TRIGGER_FORCED, username ) );
}
public void buildProjectsWithBuildDefinition( List<Project> projects, List<BuildDefinition> bds )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Collection<Project> filteredProjectsList = getProjectsNotInReleaseStage( projects );
prepareBuildProjects( filteredProjectsList, bds, true, new BuildTrigger( ContinuumProjectState.TRIGGER_FORCED,
"" ) );
}
public void buildProjectsWithBuildDefinition( List<Project> projects, int buildDefinitionId )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Collection<Project> filteredProjectsList = getProjectsNotInReleaseStage( projects );
prepareBuildProjects( filteredProjectsList, buildDefinitionId, new BuildTrigger(
ContinuumProjectState.TRIGGER_FORCED, "" ) );
}
/**
* fire of the builds of all projects across all project groups using their default build definitions
* TODO:Remove this method
*
* @param buildTrigger
* @throws ContinuumException
*/
public void buildProjects( BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Collection<Project> projectsList = getProjectsInBuildOrder();
Collection<Project> filteredProjectsList = getProjectsNotInReleaseStage( projectsList );
prepareBuildProjects( filteredProjectsList, null, true, buildTrigger );
}
/**
* fire off a build for all of the projects in a project group using their default builds
*
* @param projectGroupId
* @param buildTrigger
* @throws ContinuumException
*/
public void buildProjectGroup( int projectGroupId, BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
List<BuildDefinition> groupDefaultBDs;
if ( !isAnyProjectInGroupInReleaseStage( projectGroupId ) )
{
groupDefaultBDs = getDefaultBuildDefinitionsForProjectGroup( projectGroupId );
buildProjectGroupWithBuildDefinition( projectGroupId, groupDefaultBDs, true, buildTrigger );
}
}
/**
* fire off a build for all of the projects in a project group using their default builds.
*
* @param projectGroupId the project group id
* @param buildDefinitionId the build definition id to use
* @param buildTrigger the trigger state and the username
* @throws ContinuumException
*/
public void buildProjectGroupWithBuildDefinition( int projectGroupId, int buildDefinitionId,
BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
if ( !isAnyProjectInGroupInReleaseStage( projectGroupId ) )
{
List<BuildDefinition> bds = new ArrayList<BuildDefinition>();
BuildDefinition bd = getBuildDefinition( buildDefinitionId );
if ( bd != null )
{
bds.add( bd );
}
buildProjectGroupWithBuildDefinition( projectGroupId, bds, false, buildTrigger );
}
}
/**
* fire off a build for all of the projects in a project group using their default builds
*
* @param projectGroupId
* @param bds
* @param checkDefaultBuildDefinitionForProject
* @param buildTrigger
* @throws ContinuumException
*/
private void buildProjectGroupWithBuildDefinition( int projectGroupId, List<BuildDefinition> bds,
boolean checkDefaultBuildDefinitionForProject,
BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
if ( !isAnyProjectInGroupInReleaseStage( projectGroupId ) )
{
Collection<Project> projectsList;
projectsList = getProjectsInBuildOrder( projectDao.getProjectsWithDependenciesByGroupId( projectGroupId ) );
buildTrigger.setTrigger( ContinuumProjectState.TRIGGER_FORCED );
prepareBuildProjects( projectsList, bds, checkDefaultBuildDefinitionForProject, buildTrigger );
}
}
/**
* takes a given schedule and determines which projects need to build
* The build order is determined by the dependencies
*
* @param schedule The schedule
* @throws ContinuumException
*/
public void buildProjects( Schedule schedule )
throws ContinuumException
{
Collection<Project> projectsList;
Map<Integer, Object> projectsMap;
try
{
projectsMap = daoUtils.getAggregatedProjectIdsAndBuildDefinitionIdsBySchedule( schedule.getId() );
if ( projectsMap == null || projectsMap.size() == 0 )
{
log.debug( "no builds attached to schedule" );
try
{
schedulesActivator.unactivateOrphanBuildSchedule( schedule );
}
catch ( SchedulesActivationException e )
{
log.debug( "Can't unactivate orphan shcedule for buildDefinitions" );
}
// We don't have projects attached to this schedule. This is because it's only is setting for a
// templateBuildDefinition
return;
}
//TODO: As all projects are built in the same queue for a project group, it would be better to get them by
// project group and add them in queues in parallel to save few seconds
projectsList = getProjectsInBuildOrder();
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Can't get project list for schedule " + schedule.getName(), e );
}
Map<ProjectScmRoot, Map<Integer, Integer>> map = new HashMap<ProjectScmRoot, Map<Integer, Integer>>();
List<ProjectScmRoot> sortedScmRoot = new ArrayList<ProjectScmRoot>();
boolean signalIgnored = false;
for ( Project project : projectsList )
{
List<Integer> buildDefIds = (List<Integer>) projectsMap.get( project.getId() );
int projectId = project.getId();
if ( buildDefIds != null && !buildDefIds.isEmpty() )
{
for ( Integer buildDefId : buildDefIds )
{
try
{
assertBuildable( project.getId(), buildDefId );
}
catch ( BuildException be )
{
log.info( "project not queued for build preparation: {}", be.getLocalizedMessage() );
signalIgnored = true;
continue;
}
ProjectScmRoot scmRoot = getProjectScmRootByProject( project.getId() );
Map<Integer, Integer> projectsAndBuildDefinitionsMap = map.get( scmRoot );
if ( projectsAndBuildDefinitionsMap == null )
{
projectsAndBuildDefinitionsMap = new HashMap<Integer, Integer>();
}
projectsAndBuildDefinitionsMap.put( projectId, buildDefId );
map.put( scmRoot, projectsAndBuildDefinitionsMap );
if ( !sortedScmRoot.contains( scmRoot ) )
{
sortedScmRoot.add( scmRoot );
}
}
}
}
BuildTrigger buildTrigger = new BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, schedule.getName() );
for ( ProjectScmRoot scmRoot : sortedScmRoot )
{
try
{
prepareBuildProjects( map.get( scmRoot ), buildTrigger, scmRoot.getScmRootAddress(),
scmRoot.getProjectGroup().getId(), scmRoot.getId(), sortedScmRoot );
}
catch ( NoBuildAgentException e )
{
log.error( "Unable to build projects in project group " + scmRoot.getProjectGroup().getName() +
" because there is no build agent configured" );
}
catch ( NoBuildAgentInGroupException e )
{
log.error( "Unable to build projects in project group " + scmRoot.getProjectGroup().getName() +
" because there is no build agent configured in build agent group" );
}
}
if ( signalIgnored )
{
throw new BuildException( "some projects were not queued due to their current build state",
"build.projects.someNotQueued" );
}
}
public void buildProject( int projectId, String username )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
buildProject( projectId, new BuildTrigger( ContinuumProjectState.TRIGGER_FORCED, username ) );
}
public void buildProjectWithBuildDefinition( int projectId, int buildDefinitionId, BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
buildTrigger.setTrigger( ContinuumProjectState.TRIGGER_FORCED );
buildProject( projectId, buildDefinitionId, buildTrigger );
}
public void buildProject( int projectId, BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Project project = getProject( projectId );
if ( isProjectInReleaseStage( project ) )
{
throw new ContinuumException( "Project (id=" + projectId + ") is currently in release stage." );
}
BuildDefinition buildDef = getDefaultBuildDefinition( projectId );
if ( buildDef == null )
{
throw new ContinuumException( "Project (id=" + projectId + ") doesn't have a default build definition." );
}
assertBuildable( projectId, buildDef.getId() );
Map<Integer, Integer> projectsBuildDefinitionsMap = new HashMap<Integer, Integer>();
projectsBuildDefinitionsMap.put( projectId, buildDef.getId() );
ProjectScmRoot scmRoot = getProjectScmRootByProject( projectId );
List<ProjectScmRoot> sortedScmRoot = new ArrayList<ProjectScmRoot>();
sortedScmRoot.add( scmRoot );
prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, scmRoot.getScmRootAddress(),
scmRoot.getProjectGroup().getId(), scmRoot.getId(), sortedScmRoot );
}
public void buildProject( int projectId, int buildDefinitionId, BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Project project = getProject( projectId );
if ( isProjectInReleaseStage( project ) )
{
throw new ContinuumException( "Project (id=" + projectId + ") is currently in release stage." );
}
assertBuildable( projectId, buildDefinitionId );
Map<Integer, Integer> projectsBuildDefinitionsMap = new HashMap<Integer, Integer>();
projectsBuildDefinitionsMap.put( projectId, buildDefinitionId );
ProjectScmRoot scmRoot = getProjectScmRootByProject( projectId );
List<ProjectScmRoot> sortedScmRoot = new ArrayList<ProjectScmRoot>();
sortedScmRoot.add( scmRoot );
prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, scmRoot.getScmRootAddress(),
scmRoot.getProjectGroup().getId(), scmRoot.getId(), sortedScmRoot );
}
public BuildResult getBuildResult( int buildId )
throws ContinuumException
{
try
{
return buildResultDao.getBuildResult( buildId );
}
catch ( ContinuumStoreException e )
{
throw logAndCreateException( "Exception while getting build result for project.", e );
}
}
public void removeBuildResult( int buildId )
throws ContinuumException
{
BuildResult buildResult = getBuildResult( buildId );
// check first if build result is currently being used by a building project
Project project = buildResult.getProject();
BuildResult bResult = getLatestBuildResultForProject( project.getId() );
try
{
if ( bResult != null && buildResult.getId() == bResult.getId() &&
parallelBuildsManager.isProjectInAnyCurrentBuild( project.getId() ) )
{
throw new ContinuumException(
"Unable to remove build result because it is currently being used by a building project " +
project.getId() );
}
int projectId = buildResult.getProject().getId();
int buildDefId = buildResult.getBuildDefinition().getId();
boolean resultPending = false;
try
{
resultPending =
distributedBuildManager.getCurrentRun( projectId, buildDefId ).getBuildResultId() == buildId;
}
catch ( ContinuumException e )
{
// No current run for given project/builddef
}
if ( resultPending )
{
throw new ContinuumException(
String.format( "Unable to remove build result %s, response is pending from build agent %s.",
buildId, buildResult.getBuildUrl() ) );
}
}
catch ( BuildManagerException e )
{
throw new ContinuumException( e.getMessage(), e );
}
buildResult.getModifiedDependencies().clear();
buildResult.setBuildDefinition( null );
try
{
buildResultDao.updateBuildResult( buildResult );
}
catch ( ContinuumStoreException e )
{
throw logAndCreateException( "Error while removing build result in database.", e );
}
removeBuildResult( buildResult );
}
private void removeBuildResult( BuildResult buildResult )
{
buildResultDao.removeBuildResult( buildResult );
// cleanup some files
try
{
File buildOutputDirectory = getConfiguration().getBuildOutputDirectory( buildResult.getProject().getId() );
File buildDirectory = new File( buildOutputDirectory, Integer.toString( buildResult.getId() ) );
if ( buildDirectory.exists() )
{
fsManager.removeDir( buildDirectory );
}
File buildOutputFile = getConfiguration().getBuildOutputFile( buildResult.getId(),
buildResult.getProject().getId() );
if ( buildOutputFile.exists() )
{
fsManager.delete( buildOutputFile );
}
}
catch ( ConfigurationException e )
{
log.info( "skip error during cleanup build files " + e.getMessage(), e );
}
catch ( IOException e )
{
log.info( "skip IOException during cleanup build files " + e.getMessage(), e );
}
}
public String getBuildOutput( int projectId, int buildId )
throws ContinuumException
{
try
{
return configurationService.getBuildOutput( buildId, projectId );
}
catch ( ConfigurationException e )
{
throw logAndCreateException( "Exception while getting build result for project.", e );
}
}
/**
* TODO: Must be done by build definition
*/
public List<ChangeSet> getChangesSinceLastSuccess( int projectId, int buildResultId )
throws ContinuumException
{
List<ChangeSet> changes = new ArrayList<ChangeSet>();
/*
Assumption: users will not find changes between project addition and first success very useful.
This also prevents inadvertently computing huge change lists during exceptional conditions by defaulting
to first id.
*/
BuildResult previousSuccess = buildResultDao.getPreviousBuildResultInSuccess( projectId, buildResultId );
if ( previousSuccess != null )
{
List<BuildResult> resultsSinceLastSuccess = buildResultDao.getBuildResultsForProjectWithDetails(
projectId, previousSuccess.getId(), buildResultId );
for ( BuildResult result : resultsSinceLastSuccess )
{
ScmResult scmResult = result.getScmResult();
if ( scmResult != null )
{
changes.addAll( scmResult.getChanges() );
}
}
}
return changes.isEmpty() ? Collections.EMPTY_LIST : changes;
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
/**
* TODO: Remove this method when it won't be used
*/
private List<Project> getProjectsInBuildOrder()
throws ContinuumException
{
return getProjectsInBuildOrder( getProjectsWithDependencies() );
}
/**
* take a collection of projects and sort for order
*
* @param projects
* @return
*/
public List<Project> getProjectsInBuildOrder( Collection<Project> projects )
{
if ( projects == null || projects.isEmpty() )
{
return new ArrayList<Project>();
}
return ProjectSorter.getSortedProjects( projects, log );
}
// ----------------------------------------------------------------------
// Maven 1.x projects
// ----------------------------------------------------------------------
public ContinuumProjectBuildingResult addMavenOneProject( String metadataUrl, int projectGroupId )
throws ContinuumException
{
return addMavenOneProject( metadataUrl, projectGroupId, true );
}
public ContinuumProjectBuildingResult addMavenOneProject( String metadataUrl, int projectGroupId,
boolean checkProtocol )
throws ContinuumException
{
return addMavenOneProject( metadataUrl, projectGroupId, checkProtocol, false );
}
public ContinuumProjectBuildingResult addMavenOneProject( String metadataUrl, int projectGroupId,
boolean checkProtocol, boolean useCredentialsCache )
throws ContinuumException
{
try
{
return addMavenOneProject( metadataUrl, projectGroupId, checkProtocol, useCredentialsCache,
buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate().getId() );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
public ContinuumProjectBuildingResult addMavenOneProject( String metadataUrl, int projectGroupId,
boolean checkProtocol, boolean useCredentialsCache,
int buildDefinitionTemplateId )
throws ContinuumException
{
return executeAddProjectsFromMetadataActivity( metadataUrl, MavenOneContinuumProjectBuilder.ID, projectGroupId,
checkProtocol, useCredentialsCache, true,
buildDefinitionTemplateId, false );
}
// ----------------------------------------------------------------------
// Maven 2.x projects
// ----------------------------------------------------------------------
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl )
throws ContinuumException
{
return addMavenTwoProject( metadataUrl, true );
}
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl, boolean checkProtocol )
throws ContinuumException
{
try
{
return executeAddProjectsFromMetadataActivity( metadataUrl, MavenTwoContinuumProjectBuilder.ID, -1,
checkProtocol,
buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate().getId() );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl, int projectGroupId )
throws ContinuumException
{
return addMavenTwoProject( metadataUrl, projectGroupId, true );
}
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl, int projectGroupId,
boolean checkProtocol )
throws ContinuumException
{
return addMavenTwoProject( metadataUrl, projectGroupId, checkProtocol, false );
}
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl, int projectGroupId,
boolean checkProtocol, boolean useCredentialsCache )
throws ContinuumException
{
try
{
return executeAddProjectsFromMetadataActivity( metadataUrl, MavenTwoContinuumProjectBuilder.ID,
projectGroupId, checkProtocol, useCredentialsCache, true,
buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate().getId(),
false );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl, int projectGroupId,
boolean checkProtocol, boolean useCredentialsCache,
boolean recursiveProjects )
throws ContinuumException
{
try
{
return executeAddProjectsFromMetadataActivity( metadataUrl, MavenTwoContinuumProjectBuilder.ID,
projectGroupId, checkProtocol, useCredentialsCache,
recursiveProjects,
buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate().getId(),
false );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
public ContinuumProjectBuildingResult addMavenTwoProject( String metadataUrl, int projectGroupId,
boolean checkProtocol, boolean useCredentialsCache,
boolean recursiveProjects, int buildDefinitionTemplateId,
boolean checkoutInSingleDirectory )
throws ContinuumException
{
return executeAddProjectsFromMetadataActivity( metadataUrl, MavenTwoContinuumProjectBuilder.ID, projectGroupId,
checkProtocol, useCredentialsCache, recursiveProjects,
buildDefinitionTemplateId, checkoutInSingleDirectory );
}
// ----------------------------------------------------------------------
// Shell projects
// ----------------------------------------------------------------------
public int addProject( Project project, String executorId, int groupId )
throws ContinuumException
{
return addProject( project, executorId, groupId, -1 );
}
/**
* @see org.apache.maven.continuum.Continuum#addProject(org.apache.maven.continuum.model.project.Project, java.lang.String, int, int)
*/
public int addProject( Project project, String executorId, int groupId, int buildDefinitionTemplateId )
throws ContinuumException
{
project.setExecutorId( executorId );
return executeAddProjectFromScmActivity( project, groupId, buildDefinitionTemplateId );
}
// ----------------------------------------------------------------------
// Activities. These should end up as workflows in werkflow
// ----------------------------------------------------------------------
private int executeAddProjectFromScmActivity( Project project, int groupId, int buildDefinitionTemplateId )
throws ContinuumException
{
String executorId = project.getExecutorId();
ProjectGroup projectGroup = getProjectGroupWithBuildDetails( groupId );
Map<String, Object> context = new HashMap<String, Object>();
String scmUrl = project.getScmUrl();
List<ProjectScmRoot> scmRoots = getProjectScmRootByProjectGroup( groupId );
boolean found = false;
for ( ProjectScmRoot scmRoot : scmRoots )
{
if ( scmUrl.startsWith( scmRoot.getScmRootAddress() ) )
{
found = true;
break;
}
}
if ( !found )
{
createProjectScmRoot( projectGroup, scmUrl );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
AbstractContinuumAction.setWorkingDirectory( context, getWorkingDirectory() );
AbstractContinuumAction.setUnvalidatedProject( context, project );
AbstractContinuumAction.setUnvalidatedProjectGroup( context, projectGroup );
AbstractContinuumAction.setProjectGroupId( context, projectGroup.getId() );
StoreProjectAction.setUseScmCredentialsCache( context, project.isScmUseCache() );
// set for initial checkout
String scmUsername = project.getScmUsername();
String scmPassword = project.getScmPassword();
if ( scmUsername != null && !StringUtils.isEmpty( scmUsername ) )
{
CheckoutProjectContinuumAction.setScmUsername( context, scmUsername );
}
if ( scmPassword != null && !StringUtils.isEmpty( scmPassword ) )
{
CheckoutProjectContinuumAction.setScmPassword( context, scmPassword );
}
executeAction( "validate-project", context );
executeAction( "store-project", context );
try
{
BuildDefinitionTemplate bdt;
if ( executorId.equalsIgnoreCase( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR ) )
{
if ( buildDefinitionTemplateId <= 0 )
{
bdt = buildDefinitionService.getDefaultAntBuildDefinitionTemplate();
}
else
{
bdt = buildDefinitionService.getBuildDefinitionTemplate( buildDefinitionTemplateId );
}
}
else
{
//shell default
if ( buildDefinitionTemplateId <= 0 )
{
bdt = buildDefinitionService.getDefaultShellBuildDefinitionTemplate();
}
else
{
bdt = buildDefinitionService.getBuildDefinitionTemplate( buildDefinitionTemplateId );
}
}
buildDefinitionService.addTemplateInProject( bdt.getId(), getProject( AbstractContinuumAction.getProjectId(
context ) ) );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
if ( !configurationService.isDistributedBuildEnabled() )
{
// used by BuildManager to determine on which build queue will the project be put
BuildDefinition bd = (BuildDefinition) getProjectWithBuildDetails( AbstractContinuumAction.getProjectId(
context ) ).getBuildDefinitions().get( 0 );
AbstractContinuumAction.setBuildDefinition( context, bd );
executeAction( "add-project-to-checkout-queue", context );
}
executeAction( "add-assignable-roles", context );
return AbstractContinuumAction.getProjectId( context );
}
private ContinuumProjectBuildingResult executeAddProjectsFromMetadataActivity( String metadataUrl,
String projectBuilderId,
int projectGroupId,
boolean checkProtocol,
int buildDefinitionTemplateId )
throws ContinuumException
{
return executeAddProjectsFromMetadataActivity( metadataUrl, projectBuilderId, projectGroupId, checkProtocol,
false, false, buildDefinitionTemplateId, false );
}
protected ContinuumProjectBuildingResult executeAddProjectsFromMetadataActivity( String metadataUrl,
String projectBuilderId,
int projectGroupId,
boolean checkProtocol,
boolean useCredentialsCache,
boolean loadRecursiveProjects,
int buildDefinitionTemplateId,
boolean addAssignableRoles,
boolean checkoutInSingleDirectory )
throws ContinuumException
{
if ( checkProtocol )
{
if ( !urlValidator.validate( metadataUrl ) )
{
ContinuumProjectBuildingResult res = new ContinuumProjectBuildingResult();
res.addError( ContinuumProjectBuildingResult.ERROR_PROTOCOL_NOT_ALLOWED );
return res;
}
}
Map<String, Object> context = new HashMap<String, Object>();
CreateProjectsFromMetadataAction.setProjectBuilderId( context, projectBuilderId );
CreateProjectsFromMetadataAction.setUrl( context, metadataUrl );
CreateProjectsFromMetadataAction.setLoadRecursiveProject( context, loadRecursiveProjects );
StoreProjectAction.setUseScmCredentialsCache( context, useCredentialsCache );
AbstractContinuumAction.setWorkingDirectory( context, getWorkingDirectory() );
CreateProjectsFromMetadataAction.setCheckoutProjectsInSingleDirectory( context, checkoutInSingleDirectory );
// CreateProjectsFromMetadataAction will check null and use default
if ( buildDefinitionTemplateId > 0 )
{
try
{
AbstractContinuumAction.setBuildDefinitionTemplate( context,
buildDefinitionService.getBuildDefinitionTemplate(
buildDefinitionTemplateId ) );
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
// ----------------------------------------------------------------------
// Create the projects from the URL
// ----------------------------------------------------------------------
ProjectGroup projectGroup;
if ( projectGroupId != -1 )
{
CreateProjectsFromMetadataAction.setProjectGroupId( context, projectGroupId );
}
executeAction( "create-projects-from-metadata", context );
ContinuumProjectBuildingResult result = CreateProjectsFromMetadataAction.getProjectBuildingResult( context );
if ( log.isInfoEnabled() )
{
if ( result.getProjects() != null )
{
log.info( "Created " + result.getProjects().size() + " projects." );
}
if ( result.getProjectGroups() != null )
{
log.info( "Created " + result.getProjectGroups().size() + " project groups." );
}
log.info( result.getErrors().size() + " errors." );
// ----------------------------------------------------------------------
// Look for any errors.
// ----------------------------------------------------------------------
if ( result.hasErrors() )
{
log.info( result.getErrors().size() + " errors during project add: " );
log.info( result.getErrorsAsString() );
return result;
}
}
// ----------------------------------------------------------------------
// Save any new project groups that we've found. Currently all projects
// will go into the first project group in the list.
// ----------------------------------------------------------------------
if ( result.getProjectGroups().size() != 1 )
{
throw new ContinuumException( "The project building result has to contain exactly one project group." );
}
boolean projectGroupCreation = false;
try
{
if ( projectGroupId == -1 )
{
projectGroup = result.getProjectGroups().iterator().next();
try
{
projectGroup = projectGroupDao.getProjectGroupByGroupId( projectGroup.getGroupId() );
projectGroupId = projectGroup.getId();
log.info( "Using existing project group with the group id: '" + projectGroup.getGroupId() + "'." );
}
catch ( ContinuumObjectNotFoundException e )
{
log.info( "Creating project group with the group id: '" + projectGroup.getGroupId() + "'." );
Map<String, Object> pgContext = new HashMap<String, Object>();
AbstractContinuumAction.setWorkingDirectory( pgContext, getWorkingDirectory() );
AbstractContinuumAction.setUnvalidatedProjectGroup( pgContext, projectGroup );
executeAction( "validate-project-group", pgContext );
executeAction( "store-project-group", pgContext );
projectGroupId = AbstractContinuumAction.getProjectGroupId( pgContext );
projectGroupCreation = true;
}
}
projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId );
//String url = CreateProjectsFromMetadataAction.getUrl( context );
String url = AbstractContinuumAction.getProjectScmRootUrl( context, null );
List<ProjectScmRoot> scmRoots = getProjectScmRootByProjectGroup( projectGroup.getId() );
boolean found = false;
for ( ProjectScmRoot scmRoot : scmRoots )
{
if ( url.startsWith( scmRoot.getScmRootAddress() ) )
{
found = true;
break;
}
}
if ( !found )
{
createProjectScmRoot( projectGroup, url );
}
/* add the project group loaded from database, which has more info, like id */
result.getProjectGroups().remove( 0 );
result.getProjectGroups().add( projectGroup );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while querying for project group.", e );
}
// ----------------------------------------------------------------------
// Save all the projects if recursive mode asked
// TODO: Validate all the projects before saving them
// ----------------------------------------------------------------------
List<Project> projects = result.getProjects();
String scmUserName = null;
String scmPassword = null;
for ( Project project : projects )
{
checkForDuplicateProjectInGroup( projectGroup, project, result );
if ( result.hasErrors() )
{
log.info( result.getErrors().size() + " errors during project add: " );
log.info( result.getErrorsAsString() );
return result;
}
project.setScmUseCache( useCredentialsCache );
// values backup for first checkout
scmUserName = project.getScmUsername();
scmPassword = project.getScmPassword();
// CONTINUUM-1792 : we don't store it
if ( useCredentialsCache )
{
project.setScmUsername( null );
project.setScmPassword( null );
}
projectGroup.addProject( project );
}
try
{
projectGroupDao.updateProjectGroup( projectGroup );
if ( !checkoutInSingleDirectory )
{
for ( Project project : projects )
{
context = new HashMap<String, Object>();
Project fetchedProject = projectDao.getProjectWithBuildDetails( project.getId() );
addProjectToCheckoutQueue( projectBuilderId, buildDefinitionTemplateId, context,
projectGroupCreation, scmUserName, scmPassword, project,
isDefaultProjectBuildDefSet( fetchedProject ) );
}
}
else
{
Project project = result.getRootProject();
if ( project != null )
{
String scmRootUrl = AbstractContinuumAction.getProjectScmRootUrl( context, null );
context = new HashMap<String, Object>();
AbstractContinuumAction.setProjectScmRootUrl( context, scmRootUrl );
List<Project> projectsWithSimilarScmRoot = new ArrayList<Project>();
for ( Project projectWithSimilarScmRoot : projects )
{
projectsWithSimilarScmRoot.add( projectWithSimilarScmRoot );
}
AbstractContinuumAction.setListOfProjectsInGroupWithCommonScmRoot( context,
projectsWithSimilarScmRoot );
Project fetchedProject = projectDao.getProjectWithBuildDetails( project.getId() );
addProjectToCheckoutQueue( projectBuilderId, buildDefinitionTemplateId, context,
projectGroupCreation, scmUserName, scmPassword, project,
isDefaultProjectBuildDefSet( fetchedProject ) );
}
}
}
catch ( BuildDefinitionServiceException e )
{
throw new ContinuumException( "Error attaching buildDefintionTemplate to project ", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error adding projects from modules", e );
}
AbstractContinuumAction.setProjectGroupId( context, projectGroup.getId() );
// add the relevant security administration roles for this project
if ( addAssignableRoles )
{
executeAction( "add-assignable-roles", context );
}
return result;
}
private boolean isDefaultProjectBuildDefSet( Project project )
{
for ( BuildDefinition bd : project.getBuildDefinitions() )
{
if ( bd.isDefaultForProject() )
{
return true;
}
}
return false;
}
private void addProjectToCheckoutQueue( String projectBuilderId, int buildDefinitionTemplateId,
Map<String, Object> context, boolean projectGroupCreation,
String scmUserName, String scmPassword, Project project,
boolean defaultProjectBuildDefSet )
throws BuildDefinitionServiceException, ContinuumStoreException, ContinuumException
{
// CONTINUUM-1953 olamy : attached buildDefs from template here
// if no group creation
if ( !projectGroupCreation && buildDefinitionTemplateId > 0 && !defaultProjectBuildDefSet )
{
buildDefinitionService.addTemplateInProject( buildDefinitionTemplateId, projectDao.getProject(
project.getId() ) );
}
AbstractContinuumAction.setUnvalidatedProject( context, project );
//
// executeAction( "validate-project", context );
//
// executeAction( "store-project", context );
//
AbstractContinuumAction.setProjectId( context, project.getId() );
// does the scm username & password really have to be set in the project?
if ( !StringUtils.isEmpty( scmUserName ) )
{
project.setScmUsername( scmUserName );
CheckoutProjectContinuumAction.setScmUsername( context, scmUserName );
}
if ( !StringUtils.isEmpty( scmPassword ) )
{
project.setScmPassword( scmPassword );
CheckoutProjectContinuumAction.setScmPassword( context, scmPassword );
}
//FIXME
// olamy : read again the project to have values because store.updateProjectGroup( projectGroup );
// remove object data -> we don't display the project name in the build queue
AbstractContinuumAction.setProject( context, projectDao.getProject( project.getId() ) );
BuildDefinition defaultBuildDefinition = null;
BuildDefinitionTemplate template = null;
if ( projectBuilderId.equals( MavenTwoContinuumProjectBuilder.ID ) )
{
template = buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate();
if ( template != null && template.getBuildDefinitions().size() > 0 )
{
defaultBuildDefinition = template.getBuildDefinitions().get( 0 );
}
}
else if ( projectBuilderId.equals( MavenOneContinuumProjectBuilder.ID ) )
{
template = buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate();
if ( template != null && template.getBuildDefinitions().size() > 0 )
{
defaultBuildDefinition = template.getBuildDefinitions().get( 0 );
}
}
if ( defaultBuildDefinition == null )
{
// do not throw exception
// project already added so might as well continue with the rest
log.warn( "No default build definition found in the template. Project cannot be checked out." );
}
else
{
// used by BuildManager to determine on which build queue will the project be put
AbstractContinuumAction.setBuildDefinition( context, defaultBuildDefinition );
if ( !configurationService.isDistributedBuildEnabled() )
{
executeAction( "add-project-to-checkout-queue", context );
}
}
}
private ContinuumProjectBuildingResult executeAddProjectsFromMetadataActivity( String metadataUrl,
String projectBuilderId,
int projectGroupId,
boolean checkProtocol,
boolean useCredentialsCache,
boolean loadRecursiveProjects,
int buildDefinitionTemplateId,
boolean checkoutInSingleDirectory )
throws ContinuumException
{
return executeAddProjectsFromMetadataActivity( metadataUrl, projectBuilderId, projectGroupId, checkProtocol,
useCredentialsCache, loadRecursiveProjects,
buildDefinitionTemplateId, true, checkoutInSingleDirectory );
}
// ----------------------------------------------------------------------
// Notification
// ----------------------------------------------------------------------
// This whole section needs a scrub but will need to be dealt with generally
// when we add schedules and profiles to the mix.
public ProjectNotifier getNotifier( int projectId, int notifierId )
throws ContinuumException
{
Project project = getProjectWithAllDetails( projectId );
List<ProjectNotifier> notifiers = project.getNotifiers();
ProjectNotifier notifier = null;
for ( ProjectNotifier notif : notifiers )
{
notifier = notif;
if ( notifier.getId() == notifierId )
{
break;
}
}
return notifier;
}
public ProjectNotifier getGroupNotifier( int projectGroupId, int notifierId )
throws ContinuumException
{
ProjectGroup projectGroup = getProjectGroupWithBuildDetails( projectGroupId );
List<ProjectNotifier> notifiers = projectGroup.getNotifiers();
ProjectNotifier notifier = null;
for ( ProjectNotifier notif : notifiers )
{
notifier = notif;
if ( notifier.getId() == notifierId )
{
break;
}
}
return notifier;
}
public ProjectNotifier updateNotifier( int projectId, ProjectNotifier notifier )
throws ContinuumException
{
Project project = getProjectWithAllDetails( projectId );
ProjectNotifier notif = getNotifier( projectId, notifier.getId() );
// I remove notifier then add it instead of update it due to a ClassCastException in jpox
project.removeNotifier( notif );
updateProject( project );
return addNotifier( projectId, notifier );
}
public ProjectNotifier updateGroupNotifier( int projectGroupId, ProjectNotifier notifier )
throws ContinuumException
{
ProjectGroup projectGroup = getProjectGroupWithBuildDetails( projectGroupId );
ProjectNotifier notif = getGroupNotifier( projectGroupId, notifier.getId() );
// I remove notifier then add it instead of update it due to a ClassCastException in jpox
projectGroup.removeNotifier( notif );
try
{
projectGroupDao.updateProjectGroup( projectGroup );
}
catch ( ContinuumStoreException cse )
{
throw new ContinuumException( "Unable to update project group.", cse );
}
return addGroupNotifier( projectGroupId, notifier );
}
public ProjectNotifier addNotifier( int projectId, ProjectNotifier notifier )
throws ContinuumException
{
ProjectNotifier notif = new ProjectNotifier();
notif.setSendOnSuccess( notifier.isSendOnSuccess() );
notif.setSendOnFailure( notifier.isSendOnFailure() );
notif.setSendOnError( notifier.isSendOnError() );
notif.setSendOnWarning( notifier.isSendOnWarning() );
notif.setSendOnScmFailure( notifier.isSendOnScmFailure() );
notif.setConfiguration( notifier.getConfiguration() );
notif.setType( notifier.getType() );
notif.setFrom( ProjectNotifier.FROM_USER );
Project project = getProjectWithAllDetails( projectId );
project.addNotifier( notif );
updateProject( project );
return notif;
}
public ProjectNotifier addGroupNotifier( int projectGroupId, ProjectNotifier notifier )
throws ContinuumException
{
ProjectNotifier notif = new ProjectNotifier();
notif.setSendOnSuccess( notifier.isSendOnSuccess() );
notif.setSendOnFailure( notifier.isSendOnFailure() );
notif.setSendOnError( notifier.isSendOnError() );
notif.setSendOnWarning( notifier.isSendOnWarning() );
notif.setSendOnScmFailure( notifier.isSendOnScmFailure() );
notif.setConfiguration( notifier.getConfiguration() );
notif.setType( notifier.getType() );
notif.setFrom( ProjectNotifier.FROM_USER );
ProjectGroup projectGroup = getProjectGroupWithBuildDetails( projectGroupId );
projectGroup.addNotifier( notif );
try
{
projectGroupDao.updateProjectGroup( projectGroup );
}
catch ( ContinuumStoreException cse )
{
throw new ContinuumException( "unable to add notifier to project group", cse );
}
return notif;
}
public void removeNotifier( int projectId, int notifierId )
throws ContinuumException
{
Project project = getProjectWithAllDetails( projectId );
ProjectNotifier n = getNotifier( projectId, notifierId );
if ( n != null )
{
if ( n.isFromProject() )
{
n.setEnabled( false );
storeNotifier( n );
}
else
{
project.removeNotifier( n );
updateProject( project );
}
}
}
public void removeGroupNotifier( int projectGroupId, int notifierId )
throws ContinuumException
{
ProjectGroup projectGroup = getProjectGroupWithBuildDetails( projectGroupId );
ProjectNotifier n = getGroupNotifier( projectGroupId, notifierId );
if ( n != null )
{
if ( n.isFromProject() )
{
n.setEnabled( false );
storeNotifier( n );
}
else
{
projectGroup.removeNotifier( n );
try
{
projectGroupDao.updateProjectGroup( projectGroup );
}
catch ( ContinuumStoreException cse )
{
throw new ContinuumException( "Unable to remove notifer from project group.", cse );
}
}
}
}
// ----------------------------------------------------------------------
// Build Definition
// ----------------------------------------------------------------------
public List<BuildDefinition> getBuildDefinitions( int projectId )
throws ContinuumException
{
Project project = getProjectWithAllDetails( projectId );
return project.getBuildDefinitions();
}
public BuildDefinition getBuildDefinition( int projectId, int buildDefinitionId )
throws ContinuumException
{
List<BuildDefinition> buildDefinitions = getBuildDefinitions( projectId );
BuildDefinition buildDefinition = null;
for ( BuildDefinition bd : buildDefinitions )
{
if ( bd.getId() == buildDefinitionId )
{
buildDefinition = bd;
break;
}
}
return buildDefinition;
}
public BuildDefinition getDefaultBuildDefinition( int projectId )
throws ContinuumException
{
try
{
return buildDefinitionDao.getDefaultBuildDefinition( projectId );
}
catch ( ContinuumObjectNotFoundException cne )
{
throw new ContinuumException( "no default build definition for project", cne );
}
catch ( ContinuumStoreException cse )
{
throw new ContinuumException(
"error attempting to access default build definition for project " + projectId, cse );
}
}
public List<BuildDefinition> getDefaultBuildDefinitionsForProjectGroup( int projectGroupId )
throws ContinuumException
{
try
{
return buildDefinitionDao.getDefaultBuildDefinitionsForProjectGroup( projectGroupId );
}
catch ( ContinuumObjectNotFoundException cne )
{
throw new ContinuumException( "Project Group (id=" + projectGroupId +
") doesn't have a default build definition, this should be impossible, it should always have a default definition set." );
}
catch ( ContinuumStoreException cse )
{
throw new ContinuumException( "Project Group (id=" + projectGroupId +
") doesn't have a default build definition, this should be impossible, it should always have a default definition set." );
}
}
public BuildDefinition getBuildDefinition( int buildDefinitionId )
throws ContinuumException
{
try
{
return buildDefinitionDao.getBuildDefinition( buildDefinitionId );
}
catch ( ContinuumObjectNotFoundException cne )
{
throw new ContinuumException( "no build definition found", cne );
}
catch ( ContinuumStoreException cse )
{
throw new ContinuumException( "error attempting to access build definition", cse );
}
}
public List<BuildDefinition> getBuildDefinitionsForProject( int projectId )
throws ContinuumException
{
Project project = getProjectWithAllDetails( projectId );
return project.getBuildDefinitions();
}
public List<BuildDefinition> getBuildDefinitionsForProjectGroup( int projectGroupId )
throws ContinuumException
{
ProjectGroup projectGroup = getProjectGroupWithBuildDetails( projectGroupId );
return projectGroup.getBuildDefinitions();
}
public BuildDefinition addBuildDefinitionToProject( int projectId, BuildDefinition buildDefinition )
throws ContinuumException
{
HashMap<String, Object> context = new HashMap<String, Object>();
Schedule schedule = buildDefinition.getSchedule();
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
AbstractContinuumAction.setProjectId( context, projectId );
executeAction( "add-build-definition-to-project", context );
activeBuildDefinitionSchedule( schedule );
return AbstractContinuumAction.getBuildDefinition( context );
}
public void removeBuildDefinitionFromProject( int projectId, int buildDefinitionId )
throws ContinuumException
{
HashMap<String, Object> context = new HashMap<String, Object>();
BuildDefinition buildDefinition = getBuildDefinition( buildDefinitionId );
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
AbstractContinuumAction.setProjectId( context, projectId );
executeAction( "remove-build-definition-from-project", context );
}
public BuildDefinition updateBuildDefinitionForProject( int projectId, BuildDefinition buildDefinition )
throws ContinuumException
{
HashMap<String, Object> context = new HashMap<String, Object>();
Schedule schedule = buildDefinition.getSchedule();
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
AbstractContinuumAction.setProjectId( context, projectId );
executeAction( "update-build-definition-from-project", context );
activeBuildDefinitionSchedule( schedule );
return AbstractContinuumAction.getBuildDefinition( context );
}
public BuildDefinition addBuildDefinitionToProjectGroup( int projectGroupId, BuildDefinition buildDefinition )
throws ContinuumException
{
HashMap<String, Object> context = new HashMap<String, Object>();
Schedule schedule = buildDefinition.getSchedule();
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
AbstractContinuumAction.setProjectGroupId( context, projectGroupId );
executeAction( "add-build-definition-to-project-group", context );
activeBuildDefinitionSchedule( schedule );
return AbstractContinuumAction.getBuildDefinition( context );
}
public void removeBuildDefinitionFromProjectGroup( int projectGroupId, int buildDefinitionId )
throws ContinuumException
{
HashMap<String, Object> context = new HashMap<String, Object>();
AbstractContinuumAction.setBuildDefinition( context, getBuildDefinition( buildDefinitionId ) );
AbstractContinuumAction.setProjectGroupId( context, projectGroupId );
executeAction( "remove-build-definition-from-project-group", context );
}
public BuildDefinition updateBuildDefinitionForProjectGroup( int projectGroupId, BuildDefinition buildDefinition )
throws ContinuumException
{
HashMap<String, Object> context = new HashMap<String, Object>();
Schedule schedule = buildDefinition.getSchedule();
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
AbstractContinuumAction.setProjectGroupId( context, projectGroupId );
executeAction( "update-build-definition-from-project-group", context );
activeBuildDefinitionSchedule( schedule );
return AbstractContinuumAction.getBuildDefinition( context );
}
public void removeBuildDefinition( int projectId, int buildDefinitionId )
throws ContinuumException
{
Project project = getProjectWithAllDetails( projectId );
BuildDefinition buildDefinition = getBuildDefinition( projectId, buildDefinitionId );
if ( buildDefinition != null )
{
project.removeBuildDefinition( buildDefinition );
updateProject( project );
}
}
// ----------------------------------------------------------------------
// Schedule
// ----------------------------------------------------------------------
public Schedule getSchedule( int scheduleId )
throws ContinuumException
{
try
{
return scheduleDao.getSchedule( scheduleId );
}
catch ( Exception ex )
{
throw logAndCreateException( "Error while getting schedule.", ex );
}
}
public Schedule getScheduleByName( String scheduleName )
throws ContinuumException
{
try
{
return scheduleDao.getScheduleByName( scheduleName );
}
catch ( ContinuumStoreException e )
{
throw logAndCreateException( "Error while accessing the store.", e );
}
}
public Collection<Schedule> getSchedules()
throws ContinuumException
{
return scheduleDao.getAllSchedulesByName();
}
public void addSchedule( Schedule schedule )
throws ContinuumException
{
Schedule s;
s = getScheduleByName( schedule.getName() );
if ( s != null )
{
throw logAndCreateException( "Can't create schedule. A schedule with the same name already exists.", null );
}
s = scheduleDao.addSchedule( schedule );
try
{
schedulesActivator.activateSchedule( s, this );
}
catch ( SchedulesActivationException e )
{
throw new ContinuumException( "Error activating schedule " + s.getName() + ".", e );
}
}
public void updateSchedule( Schedule schedule )
throws ContinuumException
{
updateSchedule( schedule, true );
}
private void updateSchedule( Schedule schedule, boolean updateScheduler )
throws ContinuumException
{
Schedule old = getSchedule( schedule.getId() );
storeSchedule( schedule );
if ( updateScheduler )
{
try
{
if ( schedule.isActive() )
{
// I unactivate old shcedule (could change name) before if it's already active
schedulesActivator.unactivateSchedule( old, this );
schedulesActivator.activateSchedule( schedule, this );
}
else
{
// Unactivate old because could change name in new schedule
schedulesActivator.unactivateSchedule( old, this );
}
}
catch ( SchedulesActivationException e )
{
log.error( "Can't unactivate schedule. You need to restart Continuum.", e );
}
}
}
public void updateSchedule( int scheduleId, Map<String, String> configuration )
throws ContinuumException
{
Schedule schedule = getSchedule( scheduleId );
schedule.setName( configuration.get( "schedule.name" ) );
schedule.setDescription( configuration.get( "schedule.description" ) );
schedule.setCronExpression( configuration.get( "schedule.cronExpression" ) );
schedule.setDelay( Integer.parseInt( configuration.get( "schedule.delay" ) ) );
schedule.setActive( Boolean.valueOf( configuration.get( "schedule.active" ) ) );
updateSchedule( schedule, true );
}
public void removeSchedule( int scheduleId )
throws ContinuumException
{
Schedule schedule = getSchedule( scheduleId );
try
{
schedulesActivator.unactivateSchedule( schedule, this );
}
catch ( SchedulesActivationException e )
{
log.error( "Can't unactivate the schedule. You need to restart Continuum.", e );
}
try
{
scheduleDao.removeSchedule( schedule );
}
catch ( Exception e )
{
log.error( "Can't remove the schedule.", e );
try
{
schedulesActivator.activateSchedule( schedule, this );
}
catch ( SchedulesActivationException sae )
{
log.error( "Can't reactivate the schedule. You need to restart Continuum.", e );
}
throw new ContinuumException( "Can't remove the schedule", e );
}
}
private Schedule storeSchedule( Schedule schedule )
throws ContinuumException
{
try
{
return scheduleDao.storeSchedule( schedule );
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Error while storing schedule.", ex );
}
}
public void activePurgeSchedule( Schedule schedule )
{
try
{
schedulesActivator.activatePurgeSchedule( schedule, this );
}
catch ( SchedulesActivationException e )
{
log.error( "Can't activate schedule for purgeConfiguration" );
}
}
public void activeBuildDefinitionSchedule( Schedule schedule )
{
try
{
schedulesActivator.activateBuildSchedule( schedule, this );
}
catch ( SchedulesActivationException e )
{
log.error( "Can't activate schedule for buildDefinition" );
}
}
// ----------------------------------------------------------------------
// Working copy
// ----------------------------------------------------------------------
public File getWorkingDirectory( int projectId )
throws ContinuumException
{
try
{
return workingDirectoryService.getWorkingDirectory( projectDao.getProject( projectId ) );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Can't get files list.", e );
}
}
public String getFileContent( int projectId, String directory, String filename )
throws ContinuumException
{
String relativePath = "\\.\\./"; // prevent users from using relative paths.
Pattern pattern = Pattern.compile( relativePath );
Matcher matcher = pattern.matcher( directory );
String filteredDirectory = matcher.replaceAll( "" );
matcher = pattern.matcher( filename );
String filteredFilename = matcher.replaceAll( "" );
File workingDirectory = getWorkingDirectory( projectId );
File fileDirectory = new File( workingDirectory, filteredDirectory );
File userFile = new File( fileDirectory, filteredFilename );
try
{
return fsManager.fileContents( userFile );
}
catch ( IOException e )
{
throw new ContinuumException( "Can't read file " + filename, e );
}
}
public List<File> getFiles( int projectId, String userDirectory )
throws ContinuumException
{
File workingDirectory = getWorkingDirectory( projectId );
return getFiles( workingDirectory, null, userDirectory );
}
private List<File> getFiles( File baseDirectory, String currentSubDirectory, String userDirectory )
{
List<File> dirs = new ArrayList<File>();
File workingDirectory;
if ( currentSubDirectory != null )
{
workingDirectory = new File( baseDirectory, currentSubDirectory );
}
else
{
workingDirectory = baseDirectory;
}
String[] files = workingDirectory.list();
Arrays.sort( files, String.CASE_INSENSITIVE_ORDER );
if ( files != null )
{
for ( String file : files )
{
File current = new File( workingDirectory, file );
String currentFile;
if ( currentSubDirectory == null )
{
currentFile = file;
}
else
{
currentFile = currentSubDirectory + "/" + file;
}
if ( userDirectory != null && current.isDirectory() && userDirectory.startsWith( currentFile ) )
{
dirs.add( current );
dirs.addAll( getFiles( baseDirectory, currentFile, userDirectory ) );
}
else
{
dirs.add( current );
}
}
}
return dirs;
}
// ----------------------------------------------------------------------
// Configuration
// ----------------------------------------------------------------------
public ConfigurationService getConfiguration()
{
return configurationService;
}
public void reloadConfiguration()
throws ContinuumException
{
try
{
configurationService.reload();
}
catch ( Exception e )
{
throw new ContinuumException( "Can't reload configuration.", e );
}
}
// ----------------------------------------------------------------------
// Lifecycle Management
// ----------------------------------------------------------------------
public void initialize()
throws InitializationException
{
log.info( "Initializing Continuum." );
log.info( "Showing all groups:" );
try
{
for ( ProjectGroup group : projectGroupDao.getAllProjectGroups() )
{
createProjectScmRootForProjectGroup( group );
}
}
catch ( ContinuumException e )
{
throw new InitializationException( "Error while creating project scm root for the project group", e );
}
log.info( "Showing all projects: " );
for ( Project project : projectDao.getAllProjectsByNameWithBuildDetails() )
{
for ( ProjectNotifier notifier : (List<ProjectNotifier>) project.getNotifiers() )
{
if ( StringUtils.isEmpty( notifier.getType() ) )
{
try
{
removeNotifier( project.getId(), notifier.getId() );
}
catch ( ContinuumException e )
{
throw new InitializationException( "Database is corrupted.", e );
}
}
}
if ( project.getState() != ContinuumProjectState.NEW &&
project.getState() != ContinuumProjectState.CHECKEDOUT &&
project.getState() != ContinuumProjectState.OK && project.getState() != ContinuumProjectState.FAILED &&
project.getState() != ContinuumProjectState.ERROR )
{
int state = project.getState();
project.setState( project.getOldState() );
project.setOldState( 0 );
try
{
log.info( "Fix project state for project " + project.getId() + ":" + project.getName() + ":" +
project.getVersion() );
projectDao.updateProject( project );
Project p = projectDao.getProject( project.getId() );
if ( state == p.getState() )
{
log.info( "Can't fix the project state." );
}
}
catch ( ContinuumStoreException e )
{
throw new InitializationException( "Database is corrupted.", e );
}
}
log.info( " " + project.getId() + ":" + project.getName() + ":" + project.getVersion() + ":" +
project.getExecutorId() );
}
for ( ProjectScmRoot projectScmRoot : projectScmRootDao.getAllProjectScmRoots() )
{
if ( projectScmRoot.getState() == ContinuumProjectState.UPDATING )
{
projectScmRoot.setState( projectScmRoot.getOldState() );
projectScmRoot.setOldState( 0 );
try
{
log.info( "Fix state for projectScmRoot " + projectScmRoot.getScmRootAddress() );
projectScmRootDao.updateProjectScmRoot( projectScmRoot );
}
catch ( ContinuumStoreException e )
{
throw new InitializationException( "Database is corrupted.", e );
}
}
}
}
// --------------------------------
// Plexus Lifecycle
// --------------------------------
public void start()
throws StartingException
{
startMessage();
try
{
initializer.initialize();
configurationService.reload();
}
catch ( ConfigurationLoadingException e )
{
throw new StartingException( "Error loading the Continuum configuration.", e );
}
catch ( ContinuumConfigurationException e )
{
throw new StartingException( "Error loading the Continuum configuration.", e );
}
catch ( ContinuumInitializationException e )
{
throw new StartingException( "Cannot initializing Continuum for the first time.", e );
}
try
{
// ----------------------------------------------------------------------
// Activate all the schedules in the system
// ----------------------------------------------------------------------
schedulesActivator.activateSchedules( this );
}
catch ( SchedulesActivationException e )
{
// We don't throw an exception here, so users will can modify schedules in interface instead of database
log.error( "Error activating schedules.", e );
}
}
public void stop()
throws StoppingException
{
stopContinuum();
}
private void closeStore()
{
if ( daoUtils != null )
{
daoUtils.closeStore();
}
}
public void startup()
throws ContinuumException
{
try
{
this.start();
}
catch ( StartingException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
private void stopContinuum()
{
//TODO: Remove all projects from queues, stop scheduler and wait the end of current builds so build results will be ok
if ( stopped )
{
return;
}
try
{
if ( configurationService != null )
{
configurationService.store();
}
}
catch ( Exception e )
{
log.info( "Error storing the Continuum configuration.", e );
}
closeStore();
stopMessage();
stopped = true;
}
public long getNbBuildResultsForProject( int projectId )
{
return buildResultDao.getNbBuildResultsForProject( projectId );
}
public Collection<BuildResult> getBuildResultsForProject( int projectId, int offset, int length )
throws ContinuumException
{
return buildResultDao.getBuildResultsForProject( projectId, offset, offset + length, false );
}
// ----------------------------------------------------------------------
// Workflow
// ----------------------------------------------------------------------
protected void executeAction( String actionName, Map<String, Object> context )
throws ContinuumException
{
try
{
Action action = actionManager.lookup( actionName );
action.execute( context );
}
catch ( ActionNotFoundException e )
{
e.printStackTrace();
throw new ContinuumException( "Error while executing the action '" + actionName + "'.", e );
}
catch ( ContinuumException e )
{
throw e;
}
catch ( Exception e )
{
log.info( "exception", e );
throw new ContinuumException( "Error while executing the action '" + actionName + "'.", e );
}
}
// ----------------------------------------------------------------------
// Logging
// ----------------------------------------------------------------------
private ContinuumException logAndCreateException( String message, Throwable cause )
{
if ( cause instanceof ContinuumObjectNotFoundException )
{
return new ContinuumException( "No such object.", cause );
}
log.error( message, cause );
return new ContinuumException( message, cause );
}
// ----------------------------------------------------------------------
// Build settings
// ----------------------------------------------------------------------
// core
public void updateProject( Project project )
throws ContinuumException
{
try
{
boolean removeWorkingDirectory = false;
Project p = projectDao.getProject( project.getId() );
ProjectScmRoot projectScmRoot = null;
if ( !p.getScmUrl().equals( project.getScmUrl() ) )
{
removeWorkingDirectory = true;
projectScmRoot = getProjectScmRootByProject( project.getId() );
}
if ( !p.getProjectGroup().equals( project.getProjectGroup() ) )
{
projectScmRoot = getProjectScmRootByProject( project.getId() );
}
if ( StringUtils.isEmpty( p.getScmTag() ) && !StringUtils.isEmpty( project.getScmTag() ) )
{
removeWorkingDirectory = true;
}
else if ( !StringUtils.isEmpty( p.getScmTag() ) && StringUtils.isEmpty( project.getScmTag() ) )
{
removeWorkingDirectory = true;
}
else if ( !StringUtils.isEmpty( p.getScmTag() ) && !p.getScmTag().equals( project.getScmTag() ) )
{
removeWorkingDirectory = true;
}
if ( removeWorkingDirectory )
{
File workingDirectory = getWorkingDirectory( project.getId() );
fsManager.removeDir( workingDirectory );
}
if ( StringUtils.isEmpty( project.getScmTag() ) )
{
project.setScmTag( null );
}
projectDao.updateProject( project );
if ( projectScmRoot != null )
{
updateProjectScmRoot( projectScmRoot, project );
}
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Error while updating project.", ex );
}
catch ( IOException ex )
{
throw logAndCreateException( "Error while updating project.", ex );
}
}
public void updateProjectGroup( ProjectGroup projectGroup )
throws ContinuumException
{
//CONTINUUM-1502
projectGroup.setName( projectGroup.getName().trim() );
try
{
projectGroupDao.updateProjectGroup( projectGroup );
}
catch ( ContinuumStoreException cse )
{
throw logAndCreateException( "Error while updating project group.", cse );
}
}
private ProjectNotifier storeNotifier( ProjectNotifier notifier )
throws ContinuumException
{
try
{
return notifierDao.storeNotifier( notifier );
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Error while storing notifier.", ex );
}
}
private String getWorkingDirectory()
{
return configurationService.getWorkingDirectory().getAbsolutePath();
}
public Project getProjectWithCheckoutResult( int projectId )
throws ContinuumException
{
try
{
return projectDao.getProjectWithCheckoutResult( projectId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find the requested project", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving the requested project", e );
}
}
public Project getProjectWithAllDetails( int projectId )
throws ContinuumException
{
try
{
return projectDao.getProjectWithAllDetails( projectId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find the requested project", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving the requested project", e );
}
}
public ProjectGroup getProjectGroupWithBuildDetails( int projectGroupId )
throws ContinuumException
{
try
{
return projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find the requested project", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving the requested project", e );
}
}
public Project getProjectWithBuilds( int projectId )
throws ContinuumException
{
try
{
return projectDao.getProjectWithBuilds( projectId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find the requested project", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving the requested project", e );
}
}
public List<ProjectGroup> getAllProjectGroupsWithBuildDetails()
{
return projectGroupDao.getAllProjectGroupsWithBuildDetails();
}
public Collection<Project> getProjectsInGroup( int projectGroupId )
throws ContinuumException
{
try
{
return projectDao.getProjectsInGroup( projectGroupId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find the requested project", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving the requested project", e );
}
}
public Collection<Project> getProjectsInGroupWithDependencies( int projectGroupId )
throws ContinuumException
{
try
{
return projectDao.getProjectsInGroupWithDependencies( projectGroupId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "Unable to find the requested project", e );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error retrieving the requested project", e );
}
}
// ----------------------------------------------------------------------
// Private Utilities
// ----------------------------------------------------------------------
private void startMessage()
{
log.info( "Starting Continuum." );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
String banner = StringUtils.repeat( "-", getVersion().length() );
log.info( "" );
log.info( "" );
log.info( "< Continuum " + getVersion() + " started! >" );
log.info( "-----------------------" + banner );
log.info( " \\ ^__^" );
log.info( " \\ (oo)\\_______" );
log.info( " (__)\\ )\\/\\" );
log.info( " ||----w |" );
log.info( " || ||" );
log.info( "" );
log.info( "" );
}
private void stopMessage()
{
// Yes dorothy, this can happen!
if ( log != null )
{
log.info( "Stopping Continuum." );
log.info( "Continuum stopped." );
}
}
private String getVersion()
{
InputStream resourceAsStream = null;
try
{
Properties properties = new Properties();
String name = "META-INF/maven/org.apache.continuum/continuum-core/pom.properties";
resourceAsStream = getClass().getClassLoader().getResourceAsStream( name );
if ( resourceAsStream == null )
{
return "unknown";
}
properties.load( resourceAsStream );
return properties.getProperty( "version", "unknown" );
}
catch ( IOException e )
{
return "unknown";
}
finally
{
if ( resourceAsStream != null )
{
IOUtil.close( resourceAsStream );
}
}
}
public InstallationService getInstallationService()
{
return installationService;
}
public ProfileService getProfileService()
{
return profileService;
}
public BuildDefinitionService getBuildDefinitionService()
{
return buildDefinitionService;
}
public ContinuumReleaseResult addContinuumReleaseResult( int projectId, String releaseId, String releaseType )
throws ContinuumException
{
ReleaseResult result;
String releaseBy = "";
if ( getConfiguration().isDistributedBuildEnabled() )
{
try
{
result = (ReleaseResult) distributedReleaseManager.getReleaseResult( releaseId );
PreparedRelease preparedRelease = distributedReleaseManager.getPreparedRelease( releaseId,
releaseType );
if ( preparedRelease != null )
{
releaseBy = preparedRelease.getReleaseBy();
}
}
catch ( ContinuumReleaseException e )
{
throw new ContinuumException( "Failed to release project: " + projectId, e );
}
catch ( BuildAgentConfigurationException e )
{
throw new ContinuumException( "Failed to release project: " + projectId, e );
}
}
else
{
result = (ReleaseResult) releaseManager.getReleaseResults().get( releaseId );
ContinuumReleaseDescriptor descriptor =
(ContinuumReleaseDescriptor) releaseManager.getPreparedReleases().get( releaseId );
if ( descriptor != null )
{
releaseBy = descriptor.getReleaseBy();
}
}
if ( result != null && getContinuumReleaseResult( projectId, releaseType, result.getStartTime(),
result.getEndTime() ) == null )
{
ContinuumReleaseResult releaseResult = createContinuumReleaseResult( projectId, releaseType, result,
releaseBy );
return addContinuumReleaseResult( releaseResult );
}
return null;
}
private ContinuumReleaseResult createContinuumReleaseResult( int projectId, String releaseGoals,
ReleaseResult result, String releaseBy )
throws ContinuumException
{
ContinuumReleaseResult releaseResult = new ContinuumReleaseResult();
releaseResult.setStartTime( result.getStartTime() );
releaseResult.setEndTime( result.getEndTime() );
releaseResult.setResultCode( result.getResultCode() );
Project project = getProject( projectId );
ProjectGroup projectGroup = project.getProjectGroup();
releaseResult.setProjectGroup( projectGroup );
releaseResult.setProject( project );
releaseResult.setReleaseGoal( releaseGoals );
releaseResult.setUsername( releaseBy );
String releaseName = "releases-" + result.getStartTime();
try
{
File logFile = getConfiguration().getReleaseOutputFile( projectGroup.getId(), releaseName );
PrintWriter writer = new PrintWriter( new FileWriter( logFile ) );
writer.write( result.getOutput() );
writer.close();
}
catch ( ConfigurationException e )
{
throw new ContinuumException( e.getMessage(), e );
}
catch ( IOException e )
{
throw new ContinuumException( "Unable to write output to file", e );
}
return releaseResult;
}
public ContinuumReleaseResult addContinuumReleaseResult( ContinuumReleaseResult releaseResult )
throws ContinuumException
{
try
{
return releaseResultDao.addContinuumReleaseResult( releaseResult );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while adding continuumReleaseResult", e );
}
}
public void removeContinuumReleaseResult( int releaseResultId )
throws ContinuumException
{
ContinuumReleaseResult releaseResult = getContinuumReleaseResult( releaseResultId );
try
{
releaseResultDao.removeContinuumReleaseResult( releaseResult );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while deleting continuumReleaseResult: " + releaseResultId, e );
}
try
{
int projectGroupId = releaseResult.getProjectGroup().getId();
String name = "releases-" + releaseResult.getStartTime();
File releaseFile = getConfiguration().getReleaseOutputFile( projectGroupId, name );
if ( releaseFile.exists() )
{
try
{
fsManager.delete( releaseFile );
}
catch ( IOException e )
{
throw new ContinuumException( "Can't delete " + releaseFile.getAbsolutePath(), e );
}
}
}
catch ( ConfigurationException e )
{
log.info( "skip error during cleanup release files " + e.getMessage(), e );
}
}
public ContinuumReleaseResult getContinuumReleaseResult( int releaseResultId )
throws ContinuumException
{
try
{
return releaseResultDao.getContinuumReleaseResult( releaseResultId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "No continuumReleaseResult found: " + releaseResultId );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while retrieving continuumReleaseResult: " + releaseResultId, e );
}
}
public List<ContinuumReleaseResult> getAllContinuumReleaseResults()
{
return releaseResultDao.getAllContinuumReleaseResults();
}
public List<ContinuumReleaseResult> getContinuumReleaseResultsByProjectGroup( int projectGroupId )
{
return releaseResultDao.getContinuumReleaseResultsByProjectGroup( projectGroupId );
}
public ContinuumReleaseResult getContinuumReleaseResult( int projectId, String releaseGoal, long startTime,
long endTime )
throws ContinuumException
{
try
{
return releaseResultDao.getContinuumReleaseResult( projectId, releaseGoal, startTime, endTime );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException(
"Error while retrieving continuumReleaseResult of projectId " + projectId + " with releaseGoal: " +
releaseGoal, e );
}
}
public String getReleaseOutput( int releaseResultId )
throws ContinuumException
{
ContinuumReleaseResult releaseResult = getContinuumReleaseResult( releaseResultId );
ProjectGroup projectGroup = releaseResult.getProjectGroup();
try
{
return configurationService.getReleaseOutput( projectGroup.getId(),
"releases-" + releaseResult.getStartTime() );
}
catch ( ConfigurationException e )
{
throw new ContinuumException( "Error while retrieving release output for release: " + releaseResultId );
}
}
public List<ProjectScmRoot> getProjectScmRootByProjectGroup( int projectGroupId )
{
return projectScmRootDao.getProjectScmRootByProjectGroup( projectGroupId );
}
public ProjectScmRoot getProjectScmRoot( int projectScmRootId )
throws ContinuumException
{
try
{
return projectScmRootDao.getProjectScmRoot( projectScmRootId );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new ContinuumException( "No projectScmRoot found with the given id: " + projectScmRootId );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while retrieving projectScmRoot ", e );
}
}
public ProjectScmRoot getProjectScmRootByProject( int projectId )
throws ContinuumException
{
Project project = getProject( projectId );
ProjectGroup group = getProjectGroupByProjectId( projectId );
List<ProjectScmRoot> scmRoots = getProjectScmRootByProjectGroup( group.getId() );
for ( ProjectScmRoot scmRoot : scmRoots )
{
if ( project.getScmUrl() != null && project.getScmUrl().startsWith( scmRoot.getScmRootAddress() ) )
{
return scmRoot;
}
}
return null;
}
public ProjectScmRoot getProjectScmRootByProjectGroupAndScmRootAddress( int projectGroupId, String scmRootAddress )
throws ContinuumException
{
try
{
return projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( projectGroupId, scmRootAddress );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while retrieving project scm root for " + projectGroupId, e );
}
}
private void removeProjectScmRoot( ProjectScmRoot projectScmRoot )
throws ContinuumException
{
if ( projectScmRoot == null )
{
return;
}
//get all projects in the group
ProjectGroup group = getProjectGroupWithProjects( projectScmRoot.getProjectGroup().getId() );
List<Project> projects = group.getProjects();
boolean found = false;
for ( Project project : projects )
{
if ( project.getScmUrl() != null && project.getScmUrl().startsWith( projectScmRoot.getScmRootAddress() ) )
{
found = true;
break;
}
}
if ( !found )
{
log.info( "Removing project scm root '" + projectScmRoot.getScmRootAddress() + "'" );
try
{
projectScmRootDao.removeProjectScmRoot( projectScmRoot );
}
catch ( ContinuumStoreException e )
{
log.error( "Failed to remove project scm root '" + projectScmRoot.getScmRootAddress() + "'", e );
throw new ContinuumException(
"Error while removing project scm root '" + projectScmRoot.getScmRootAddress() + "'", e );
}
}
else
{
log.info(
"Project scm root '" + projectScmRoot.getScmRootAddress() + "' still has projects, not removing" );
}
}
public BuildQueue addBuildQueue( BuildQueue buildQueue )
throws ContinuumException
{
try
{
return buildQueueService.addBuildQueue( buildQueue );
}
catch ( BuildQueueServiceException e )
{
throw new ContinuumException( "Error adding build queue to the database.", e );
}
}
public BuildQueue getBuildQueue( int buildQueueId )
throws ContinuumException
{
try
{
return buildQueueService.getBuildQueue( buildQueueId );
}
catch ( BuildQueueServiceException e )
{
throw new ContinuumException( "Error retrieving build queue.", e );
}
}
public BuildQueue getBuildQueueByName( String buildQueueName )
throws ContinuumException
{
try
{
return buildQueueService.getBuildQueueByName( buildQueueName );
}
catch ( BuildQueueServiceException e )
{
throw new ContinuumException( "Error retrieving build queue.", e );
}
}
public void removeBuildQueue( BuildQueue buildQueue )
throws ContinuumException
{
try
{
buildQueueService.removeBuildQueue( buildQueue );
}
catch ( BuildQueueServiceException e )
{
throw new ContinuumException( "Error deleting build queue from database.", e );
}
}
public BuildQueue storeBuildQueue( BuildQueue buildQueue )
throws ContinuumException
{
try
{
return buildQueueService.updateBuildQueue( buildQueue );
}
catch ( BuildQueueServiceException e )
{
throw new ContinuumException( "Error updating build queue.", e );
}
}
public List<BuildQueue> getAllBuildQueues()
throws ContinuumException
{
try
{
return buildQueueService.getAllBuildQueues();
}
catch ( BuildQueueServiceException e )
{
throw new ContinuumException( "Error adding build queue.", e );
}
}
private void prepareBuildProjects( Collection<Project> projects, List<BuildDefinition> bds,
boolean checkDefaultBuildDefinitionForProject, BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Map<ProjectScmRoot, Map<Integer, Integer>> map = new HashMap<ProjectScmRoot, Map<Integer, Integer>>();
List<ProjectScmRoot> sortedScmRoot = new ArrayList<ProjectScmRoot>();
boolean signalIgnored = false;
for ( Project project : projects )
{
int projectId = project.getId();
int buildDefId = -1;
if ( bds != null )
{
for ( BuildDefinition bd : bds )
{
if ( project.getExecutorId().equals( bd.getType() ) || ( StringUtils.isEmpty( bd.getType() ) &&
ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( project.getExecutorId() ) ) )
{
buildDefId = bd.getId();
break;
}
}
}
if ( checkDefaultBuildDefinitionForProject )
{
BuildDefinition projectDefaultBD = null;
try
{
projectDefaultBD = buildDefinitionDao.getDefaultBuildDefinitionForProject( projectId );
}
catch ( ContinuumObjectNotFoundException e )
{
log.debug( e.getMessage() );
}
catch ( ContinuumStoreException e )
{
log.debug( e.getMessage() );
}
if ( projectDefaultBD != null )
{
buildDefId = projectDefaultBD.getId();
log.debug( "Project " + project.getId() +
" has own default build definition, will use it instead of group's." );
}
}
if ( buildDefId == -1 )
{
log.info( "Project " + projectId +
" don't have a default build definition defined in the project or project group, will not be included in group build." );
continue;
}
try
{
assertBuildable( project.getId(), buildDefId );
}
catch ( BuildException be )
{
log.info( "project not queued for build preparation: {}", be.getLocalizedMessage() );
signalIgnored = true;
continue;
}
ProjectScmRoot scmRoot = getProjectScmRootByProject( projectId );
Map<Integer, Integer> projectsAndBuildDefinitionsMap = map.get( scmRoot );
if ( projectsAndBuildDefinitionsMap == null )
{
projectsAndBuildDefinitionsMap = new HashMap<Integer, Integer>();
}
projectsAndBuildDefinitionsMap.put( projectId, buildDefId );
map.put( scmRoot, projectsAndBuildDefinitionsMap );
if ( !sortedScmRoot.contains( scmRoot ) )
{
sortedScmRoot.add( scmRoot );
}
}
prepareBuildProjects( map, buildTrigger, sortedScmRoot );
if ( signalIgnored )
{
throw new BuildException( "some projects were not queued due to their current build state",
"build.projects.someNotQueued" );
}
}
private void prepareBuildProjects( Collection<Project> projects, int buildDefinitionId, BuildTrigger buildTrigger )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
Map<ProjectScmRoot, Map<Integer, Integer>> map = new HashMap<ProjectScmRoot, Map<Integer, Integer>>();
List<ProjectScmRoot> sortedScmRoot = new ArrayList<ProjectScmRoot>();
boolean signalIgnored = false;
for ( Project project : projects )
{
int projectId = project.getId();
// check if project already in queue
try
{
assertBuildable( projectId, buildDefinitionId );
}
catch ( BuildException be )
{
log.info( "project not queued for build preparation: {}", be.getLocalizedMessage() );
signalIgnored = true;
continue;
}
ProjectScmRoot scmRoot = getProjectScmRootByProject( projectId );
Map<Integer, Integer> projectsAndBuildDefinitionsMap = map.get( scmRoot );
if ( projectsAndBuildDefinitionsMap == null )
{
projectsAndBuildDefinitionsMap = new HashMap<Integer, Integer>();
}
projectsAndBuildDefinitionsMap.put( projectId, buildDefinitionId );
map.put( scmRoot, projectsAndBuildDefinitionsMap );
if ( !sortedScmRoot.contains( scmRoot ) )
{
sortedScmRoot.add( scmRoot );
}
}
prepareBuildProjects( map, buildTrigger, sortedScmRoot );
if ( signalIgnored )
{
throw new BuildException( "some projects were not queued due to their current build state",
"build.projects.someNotQueued" );
}
}
private void prepareBuildProjects( Map<ProjectScmRoot, Map<Integer, Integer>> map, BuildTrigger buildTrigger,
List<ProjectScmRoot> scmRoots )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
for ( ProjectScmRoot scmRoot : scmRoots )
{
prepareBuildProjects( map.get( scmRoot ), buildTrigger, scmRoot.getScmRootAddress(),
scmRoot.getProjectGroup().getId(), scmRoot.getId(), scmRoots );
}
}
private void prepareBuildProjects( Map<Integer, Integer> projectsBuildDefinitionsMap, BuildTrigger buildTrigger,
String scmRootAddress, int projectGroupId, int scmRootId,
List<ProjectScmRoot> scmRoots )
throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException
{
ProjectGroup group = getProjectGroup( projectGroupId );
try
{
if ( configurationService.isDistributedBuildEnabled() )
{
distributedBuildManager.prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, projectGroupId,
group.getName(), scmRootAddress, scmRootId, scmRoots );
}
else
{
parallelBuildsManager.prepareBuildProjects( projectsBuildDefinitionsMap, buildTrigger, projectGroupId,
group.getName(), scmRootAddress, scmRootId );
}
}
catch ( BuildManagerException e )
{
throw logAndCreateException( "Error while creating enqueuing object.", e );
}
}
private void createProjectScmRootForProjectGroup( ProjectGroup projectGroup )
throws ContinuumException
{
List<Project> projectsList;
projectsList = getProjectsInBuildOrder( projectDao.getProjectsWithDependenciesByGroupId(
projectGroup.getId() ) );
List<ProjectScmRoot> scmRoots = getProjectScmRootByProjectGroup( projectGroup.getId() );
String url = "";
for ( Project project : projectsList )
{
boolean found = false;
if ( StringUtils.isEmpty( url ) || !project.getScmUrl().startsWith( url ) )
{
// this is a root project or the project is part of a flat multi module
url = project.getScmUrl();
//createProjectScmRoot( projectGroup, url );
for ( ProjectScmRoot scmRoot : scmRoots )
{
if ( url.startsWith( scmRoot.getScmRootAddress() ) )
{
found = true;
}
}
if ( !found )
{
createProjectScmRoot( projectGroup, url );
}
}
}
}
private ProjectScmRoot createProjectScmRoot( ProjectGroup projectGroup, String url )
throws ContinuumException
{
if ( StringUtils.isEmpty( url ) )
{
return null;
}
try
{
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress(
projectGroup.getId(), url );
if ( scmRoot != null )
{
return null;
}
ProjectScmRoot projectScmRoot = new ProjectScmRoot();
projectScmRoot.setProjectGroup( projectGroup );
projectScmRoot.setScmRootAddress( url );
return projectScmRootDao.addProjectScmRoot( projectScmRoot );
}
catch ( ContinuumStoreException e )
{
throw new ContinuumException( "Error while creating project scm root with scm root address:" + url );
}
}
private void updateProjectScmRoot( ProjectScmRoot oldScmRoot, Project project )
throws ContinuumException
{
try
{
removeProjectScmRoot( oldScmRoot );
ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress(
project.getProjectGroup().getId(), project.getScmUrl() );
if ( scmRoot == null )
{
ProjectScmRoot newScmRoot = new ProjectScmRoot();
if ( project.getScmUrl().equals( oldScmRoot.getScmRootAddress() ) )
{
BeanUtils.copyProperties( oldScmRoot, newScmRoot, new String[] { "id", "projectGroup" } );
}
else
{
newScmRoot.setScmRootAddress( project.getScmUrl() );
}
newScmRoot.setProjectGroup( project.getProjectGroup() );
projectScmRootDao.addProjectScmRoot( newScmRoot );
}
}
catch ( ContinuumStoreException ex )
{
throw logAndCreateException( "Error while updating project.", ex );
}
}
private boolean isProjectInReleaseStage( Project project )
throws ContinuumException
{
String releaseId = project.getGroupId() + ":" + project.getArtifactId();
try
{
return taskQueueManager.isProjectInReleaseStage( releaseId );
}
catch ( TaskQueueManagerException e )
{
throw new ContinuumException( "Error occurred while checking if project is currently being released.", e );
}
}
private boolean isAnyProjectInGroupInReleaseStage( int projectGroupId )
throws ContinuumException
{
Collection<Project> projects = getProjectsInGroup( projectGroupId );
for ( Project project : projects )
{
if ( isProjectInReleaseStage( project ) )
{
throw new ContinuumException( "Cannot build project group. Project (id=" + project.getId() +
") in group is currently in release stage." );
}
}
return false;
}
private boolean isAnyProjectsInReleaseStage( List<Project> projects )
throws ContinuumException
{
for ( Project project : projects )
{
if ( isProjectInReleaseStage( project ) )
{
return true;
}
}
return false;
}
private Collection<Project> getProjectsNotInReleaseStage( Collection<Project> projectsList )
throws ContinuumException
{
// filter the projects to be built
// projects that are in the release stage will not be built
Collection<Project> filteredProjectsList = new ArrayList<Project>();
for ( Project project : projectsList )
{
if ( !isProjectInReleaseStage( project ) )
{
filteredProjectsList.add( project );
}
else
{
log.warn(
"Project (id=" + project.getId() + ") will not be built. It is currently in the release stage." );
}
}
return filteredProjectsList;
}
private void checkForDuplicateProjectInGroup( ProjectGroup projectGroup, Project projectToCheck,
ContinuumProjectBuildingResult result )
{
List<Project> projectsInGroup = projectGroup.getProjects();
if ( projectsInGroup == null )
{
return;
}
for ( Project project : projectGroup.getProjects() )
{
// projectToCheck is first in the equals check, as projectToCheck must be a Maven project and will have
// non-null values for each. project may be an Ant or Shell project and have null values.
if ( projectToCheck.getGroupId().equals( project.getGroupId() ) && projectToCheck.getArtifactId().equals(
project.getArtifactId() ) && projectToCheck.getVersion().equals( project.getVersion() ) )
{
result.addError( ContinuumProjectBuildingResult.ERROR_DUPLICATE_PROJECTS );
return;
}
}
}
private void assertBuildable( int projectId, int buildDefinitionId )
throws ContinuumException
{
if ( configurationService.isDistributedBuildEnabled() )
{
if ( distributedBuildManager.isProjectInAnyPrepareBuildQueue( projectId, buildDefinitionId )
|| distributedBuildManager.isProjectInAnyBuildQueue( projectId, buildDefinitionId ) )
{
throw new BuildException( "project is already queued", "build.project.alreadyQueued" );
}
if ( distributedBuildManager.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId )
|| distributedBuildManager.isProjectCurrentlyBuilding( projectId, buildDefinitionId ) )
{
throw new BuildException( "project is already building", "build.project.alreadyBuilding" );
}
}
else
{
try
{
if ( parallelBuildsManager.isInAnyBuildQueue( projectId, buildDefinitionId )
|| parallelBuildsManager.isInAnyCheckoutQueue( projectId )
|| parallelBuildsManager.isInPrepareBuildQueue( projectId ) )
{
throw new BuildException( "project is already queued", "build.project.alreadyQueued" );
}
if ( parallelBuildsManager.isProjectCurrentlyPreparingBuild( projectId )
|| parallelBuildsManager.isProjectInAnyCurrentBuild( projectId ) )
{
throw new BuildException( "project is already building", "build.project.alreadyBuilding" );
}
}
catch ( BuildManagerException e )
{
throw new ContinuumException( e.getMessage(), e );
}
}
}
void setTaskQueueManager( TaskQueueManager taskQueueManager )
{
this.taskQueueManager = taskQueueManager;
}
void setProjectDao( ProjectDao projectDao )
{
this.projectDao = projectDao;
}
void setBuildResultDao( BuildResultDao buildResultDao ) {
this.buildResultDao = buildResultDao;
}
public DistributedBuildManager getDistributedBuildManager()
{
return distributedBuildManager;
}
}
| 5,078 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/trigger | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/trigger/quartz/ContinuumBuildTrigger.java | package org.apache.maven.continuum.trigger.quartz;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES 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.quartz.SimpleTrigger;
/**
* @author <a href="mailto:jason@maven.org">Jason van Zyl</a>
*/
public class ContinuumBuildTrigger
extends SimpleTrigger
{
public void setRepeatCount( int repeatCount )
{
super.setRepeatCount( SimpleTrigger.REPEAT_INDEFINITELY );
}
}
| 5,079 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/StoreCheckOutScmResultAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.taskqueue.execution.TaskExecutionException;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "store-checkout-scm-result" )
public class StoreCheckOutScmResultAction
extends AbstractContinuumAction
{
@Requirement
private ProjectDao projectDao;
public void execute( Map context )
throws TaskExecutionException
{
try
{
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
ScmResult scmResult = CheckoutProjectContinuumAction.getCheckoutScmResult( context, null );
Project project = projectDao.getProject( getProjectId( context ) );
project.setCheckoutResult( scmResult );
projectDao.updateProject( project );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error while storing the checkout result.", e );
}
}
}
| 5,080 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AbstractValidationContinuumAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.ContinuumException;
import org.codehaus.plexus.util.StringUtils;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public abstract class AbstractValidationContinuumAction
extends AbstractContinuumAction
{
protected void assertStringNotEmpty( String value, String fieldName )
throws ContinuumException
{
if ( StringUtils.isEmpty( value ) )
{
throw new ContinuumException( "The " + fieldName + " has to be set." );
}
}
}
| 5,081 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/ValidateProjectGroup.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.codehaus.plexus.component.annotations.Component;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "validate-project-group" )
public class ValidateProjectGroup
extends AbstractValidationContinuumAction
{
public void execute( Map context )
throws Exception
{
ProjectGroup projectGroup = getUnvalidatedProjectGroup( context );
// TODO: assert that the name is unique
assertStringNotEmpty( projectGroup.getName(), "name" );
assertStringNotEmpty( projectGroup.getGroupId(), "group id" );
}
}
| 5,082 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AbstractContinuumAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectDependency;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.codehaus.plexus.action.AbstractAction;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public abstract class AbstractContinuumAction
extends AbstractAction
{
// ----------------------------------------------------------------------
// Keys for the values that can be in the context
// ----------------------------------------------------------------------
private static final String KEY_PROJECT_ID = "project-id";
private static final String KEY_PROJECT = "project";
private static final String KEY_PROJECTS = "projects";
private static final String KEY_PROJECTS_BUILD_DEFINITIONS_MAP = "projects-build-definitions";
private static final String KEY_BUILD_DEFINITION_TEMPLATE = "build-definition-template";
private static final String KEY_BUILD_DEFINITION = "build-definition";
private static final String KEY_BUILD_DEFINITION_ID = "build-definition-id";
private static final String KEY_UNVALIDATED_PROJECT = "unvalidated-project";
private static final String KEY_PROJECT_GROUP_ID = "project-group-id";
private static final String KEY_UNVALIDATED_PROJECT_GROUP = "unvalidated-project-group";
private static final String KEY_BUILD_ID = "build-id";
private static final String KEY_WORKING_DIRECTORY = "working-directory";
private static final String KEY_UPDATE_DEPENDENCIES = "update-dependencies";
private static final String KEY_BUILD_TRIGGER = "buildTrigger";
private static final String KEY_SCM_RESULT = "scmResult";
private static final String KEY_OLD_SCM_RESULT = "old-scmResult";
private static final String KEY_PROJECT_SCM_ROOT = "projectScmRoot";
/**
* SCM root url. Used in these actions add-project-to-checkout-queue, checkout-project, clean-working-directory,
* create-projects-from-metadata, update-project-from-working-directory,
* update-working-directory-from-scm
*/
private static final String KEY_PROJECT_SCM_ROOT_URL = "projectScmRootUrl";
/**
* List of projects in a project group with a common scm root url.
*/
private static final String KEY_PROJECTS_IN_GROUP_WITH_COMMON_SCM_ROOT = "projects-in-group-with-common-scm-root";
private static final String KEY_OLD_BUILD_ID = "old-buildResult-id";
private static final String KEY_SCM_RESULT_MAP = "scm-result-map";
private static final String KEY_ROOT_DIRECTORY = "root-directory";
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public static int getProjectId( Map<String, Object> context )
{
return getInteger( context, KEY_PROJECT_ID );
}
public static void setProjectId( Map<String, Object> context, int projectId )
{
context.put( KEY_PROJECT_ID, projectId );
}
public static Project getProject( Map<String, Object> context )
{
return (Project) getObject( context, KEY_PROJECT );
}
public static Project getProject( Map<String, Object> context, Project defaultValue )
{
return (Project) getObject( context, KEY_PROJECT, defaultValue );
}
public static void setProject( Map<String, Object> context, Project p )
{
context.put( KEY_PROJECT, p );
}
public static int getProjectGroupId( Map<String, Object> context )
{
return getInteger( context, KEY_PROJECT_GROUP_ID );
}
public static void setProjectGroupId( Map<String, Object> context, int projectGroupId )
{
context.put( KEY_PROJECT_GROUP_ID, projectGroupId );
}
public static BuildDefinitionTemplate getBuildDefinitionTemplate( Map<String, Object> context )
{
return (BuildDefinitionTemplate) getObject( context, KEY_BUILD_DEFINITION_TEMPLATE, null );
}
public static void setBuildDefinitionTemplate( Map<String, Object> context, BuildDefinitionTemplate bdt )
{
context.put( KEY_BUILD_DEFINITION_TEMPLATE, bdt );
}
public static BuildDefinition getBuildDefinition( Map<String, Object> context )
{
return (BuildDefinition) getObject( context, KEY_BUILD_DEFINITION, null );
}
public static void setBuildDefinition( Map<String, Object> context, BuildDefinition bd )
{
context.put( KEY_BUILD_DEFINITION, bd );
}
public static int getBuildDefinitionId( Map<String, Object> context )
{
return getInteger( context, KEY_BUILD_DEFINITION_ID );
}
public static void setBuildDefinitionId( Map<String, Object> context, int buildDefintionId )
{
context.put( KEY_BUILD_DEFINITION_ID, buildDefintionId );
}
public static String getBuildId( Map<String, Object> context )
{
return getString( context, KEY_BUILD_ID );
}
public static String getBuildId( Map<String, Object> context, String defaultValue )
{
return getString( context, KEY_BUILD_ID, defaultValue );
}
public static void setBuildId( Map<String, Object> context, String buildId )
{
context.put( KEY_BUILD_ID, buildId );
}
public static BuildTrigger getBuildTrigger( Map<String, Object> context )
{
BuildTrigger defaultValue = new BuildTrigger( 0, "" );
return (BuildTrigger) getObject( context, KEY_BUILD_TRIGGER, defaultValue );
}
public static void setBuildTrigger( Map<String, Object> context, BuildTrigger buildTrigger )
{
context.put( KEY_BUILD_TRIGGER, buildTrigger );
}
public static Project getUnvalidatedProject( Map<String, Object> context )
{
return (Project) getObject( context, KEY_UNVALIDATED_PROJECT );
}
public static void setUnvalidatedProject( Map<String, Object> context, Project p )
{
context.put( KEY_UNVALIDATED_PROJECT, p );
}
public static ProjectGroup getUnvalidatedProjectGroup( Map<String, Object> context )
{
return (ProjectGroup) getObject( context, KEY_UNVALIDATED_PROJECT_GROUP );
}
public static void setUnvalidatedProjectGroup( Map<String, Object> context, ProjectGroup pg )
{
context.put( KEY_UNVALIDATED_PROJECT_GROUP, pg );
}
public static File getWorkingDirectory( Map<String, Object> context )
{
return new File( getString( context, KEY_WORKING_DIRECTORY ) );
}
public static void setWorkingDirectory( Map<String, Object> context, String workingDirectory )
{
context.put( KEY_WORKING_DIRECTORY, workingDirectory );
}
public static List<ProjectDependency> getUpdatedDependencies( Map<String, Object> context )
{
return getUpdatedDependencies( context, null );
}
public static List<ProjectDependency> getUpdatedDependencies( Map<String, Object> context,
List<ProjectDependency> defaultValue )
{
return (List<ProjectDependency>) getObject( context, KEY_UPDATE_DEPENDENCIES, defaultValue );
}
public static void setUpdatedDependencies( Map<String, Object> context, List<ProjectDependency> dependencies )
{
context.put( KEY_UPDATE_DEPENDENCIES, dependencies );
}
public static ScmResult getScmResult( Map<String, Object> context )
{
return getScmResult( context, null );
}
public static ScmResult getScmResult( Map<String, Object> context, ScmResult defaultValue )
{
return (ScmResult) getObject( context, KEY_SCM_RESULT, defaultValue );
}
public static void setScmResult( Map<String, Object> context, ScmResult scmResult )
{
context.put( KEY_SCM_RESULT, scmResult );
}
public static ScmResult getOldScmResult( Map<String, Object> context )
{
return getOldScmResult( context, null );
}
public static ScmResult getOldScmResult( Map<String, Object> context, ScmResult defaultValue )
{
return (ScmResult) getObject( context, KEY_OLD_SCM_RESULT, defaultValue );
}
public static void setOldScmResult( Map<String, Object> context, ScmResult oldScmResult )
{
context.put( KEY_OLD_SCM_RESULT, oldScmResult );
}
public static ProjectScmRoot getProjectScmRoot( Map<String, Object> context )
{
return (ProjectScmRoot) getObject( context, KEY_PROJECT_SCM_ROOT );
}
public static void setProjectScmRoot( Map<String, Object> context, ProjectScmRoot projectScmRoot )
{
context.put( KEY_PROJECT_SCM_ROOT, projectScmRoot );
}
public static int getOldBuildId( Map<String, Object> context )
{
return getInteger( context, KEY_OLD_BUILD_ID );
}
public static void setOldBuildId( Map<String, Object> context, int oldBuildId )
{
context.put( KEY_OLD_BUILD_ID, oldBuildId );
}
public static List<Project> getListOfProjects( Map<String, Object> context )
{
return (List<Project>) getObject( context, KEY_PROJECTS );
}
public static void setListOfProjects( Map<String, Object> context, List<Project> projects )
{
context.put( KEY_PROJECTS, projects );
}
public static List<Project> getListOfProjectsInGroupWithCommonScmRoot( Map<String, Object> context )
{
return (List<Project>) getObject( context, KEY_PROJECTS_IN_GROUP_WITH_COMMON_SCM_ROOT,
new ArrayList<Integer>() );
}
public static void setListOfProjectsInGroupWithCommonScmRoot( Map<String, Object> context, List<Project> projects )
{
context.put( KEY_PROJECTS_IN_GROUP_WITH_COMMON_SCM_ROOT, projects );
}
public static Map<Integer, BuildDefinition> getProjectsBuildDefinitionsMap( Map<String, Object> context )
{
return (Map<Integer, BuildDefinition>) getObject( context, KEY_PROJECTS_BUILD_DEFINITIONS_MAP );
}
public static void setProjectsBuildDefinitionsMap( Map<String, Object> context,
Map<Integer, BuildDefinition> projectsBuildDefinitionsMap )
{
context.put( KEY_PROJECTS_BUILD_DEFINITIONS_MAP, projectsBuildDefinitionsMap );
}
public static Map<Integer, ScmResult> getScmResultMap( Map<String, Object> context )
{
return (Map<Integer, ScmResult>) getObject( context, KEY_SCM_RESULT_MAP );
}
public static void setScmResultMap( Map<String, Object> context, Map<Integer, ScmResult> scmResultMap )
{
context.put( KEY_SCM_RESULT_MAP, scmResultMap );
}
public static boolean isRootDirectory( Map<String, Object> context )
{
return getBoolean( context, KEY_ROOT_DIRECTORY, true );
}
public static void setRootDirectory( Map<String, Object> context, boolean isRootDirectory )
{
context.put( KEY_ROOT_DIRECTORY, isRootDirectory );
}
public static String getProjectScmRootUrl( Map<String, Object> context, String projectScmRootUrl )
{
return getString( context, KEY_PROJECT_SCM_ROOT_URL, projectScmRootUrl );
}
public static void setProjectScmRootUrl( Map<String, Object> context, String projectScmRootUrl )
{
context.put( KEY_PROJECT_SCM_ROOT_URL, projectScmRootUrl );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public static String getString( Map<String, Object> context, String key )
{
return (String) getObject( context, key );
}
public static String getString( Map<String, Object> context, String key, String defaultValue )
{
return (String) getObject( context, key, defaultValue );
}
public static boolean getBoolean( Map<String, Object> context, String key )
{
return (Boolean) getObject( context, key );
}
public static boolean getBoolean( Map<String, Object> context, String key, boolean defaultValue )
{
return (Boolean) getObject( context, key, defaultValue );
}
protected static int getInteger( Map<String, Object> context, String key )
{
Object obj = getObject( context, key, null );
if ( obj == null )
{
return 0;
}
else
{
return (Integer) obj;
}
}
protected static Object getObject( Map<String, Object> context, String key )
{
if ( !context.containsKey( key ) )
{
throw new RuntimeException( "Missing key '" + key + "'." );
}
Object value = context.get( key );
if ( value == null )
{
throw new RuntimeException( "Missing value for key '" + key + "'." );
}
return value;
}
protected static Object getObject( Map<String, Object> context, String key, Object defaultValue )
{
Object value = context.get( key );
if ( value == null )
{
return defaultValue;
}
return value;
}
}
| 5,083 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/DeployArtifactContinuumAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.utils.m2.LocalRepositoryHelper;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.deployer.ArtifactDeployer;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.execution.ContinuumBuildExecutor;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.io.File;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "deploy-artifact" )
public class DeployArtifactContinuumAction
extends AbstractContinuumAction
{
@Requirement
private ConfigurationService configurationService;
@Requirement
private BuildExecutorManager buildExecutorManager;
@Requirement
private WorkingDirectoryService workingDirectoryService;
@Requirement
private ArtifactDeployer artifactDeployer;
@Requirement
private LocalRepositoryHelper localRepositoryHelper;
@Requirement
private ArtifactRepositoryFactory artifactRepositoryFactory;
public void execute( Map context )
throws Exception
{
// ----------------------------------------------------------------------
// Get parameters from the context
// ----------------------------------------------------------------------
File deploymentRepositoryDirectory = configurationService.getDeploymentRepositoryDirectory();
if ( deploymentRepositoryDirectory != null )
{
Project project = getProject( context );
ContinuumBuildExecutor buildExecutor = buildExecutorManager.getBuildExecutor( project.getExecutorId() );
// ----------------------------------------------------------------------
// This is really a precondition for this action to execute
// ----------------------------------------------------------------------
if ( project.getState() == ContinuumProjectState.OK )
{
BuildDefinition buildDefinition = getBuildDefinition( context );
String projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() );
List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context );
List<Artifact> artifacts = buildExecutor.getDeployableArtifacts( project,
workingDirectoryService.getWorkingDirectory(
project, projectScmRootUrl,
projectsWithCommonScmRoot ),
buildDefinition );
LocalRepository repository = project.getProjectGroup().getLocalRepository();
ArtifactRepository localRepository = localRepositoryHelper.getLocalRepository( repository );
for ( Artifact artifact : artifacts )
{
ArtifactRepositoryLayout repositoryLayout = new DefaultRepositoryLayout();
if ( !deploymentRepositoryDirectory.exists() )
{
deploymentRepositoryDirectory.mkdirs();
}
String location = deploymentRepositoryDirectory.toURL().toExternalForm();
ArtifactRepository deploymentRepository =
artifactRepositoryFactory.createDeploymentArtifactRepository( "deployment-repository", location,
repositoryLayout, true );
artifactDeployer.deploy( artifact.getFile(), artifact, deploymentRepository, localRepository );
}
}
}
}
}
| 5,084 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/ValidateProject.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.model.project.Project;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "validate-project" )
public class ValidateProject
extends AbstractValidationContinuumAction
{
@Requirement
private BuildExecutorManager buildExecutorManager;
@Requirement
private ProjectDao projectDao;
public void execute( Map context )
throws Exception
{
Project project = getUnvalidatedProject( context );
// ----------------------------------------------------------------------
// Make sure that the builder id is correct before starting to check
// stuff out
// ----------------------------------------------------------------------
if ( !buildExecutorManager.hasBuildExecutor( project.getExecutorId() ) )
{
throw new ContinuumException( "No such executor with id '" + project.getExecutorId() + "'." );
}
List<Project> projects = projectDao.getAllProjectsByName();
for ( Project storedProject : projects )
{
// CONTINUUM-1445
if ( StringUtils.equalsIgnoreCase( project.getName(), storedProject.getName() ) &&
StringUtils.equalsIgnoreCase( project.getVersion(), storedProject.getVersion() ) &&
StringUtils.equalsIgnoreCase( project.getScmUrl(), storedProject.getScmUrl() ) )
{
throw new ContinuumException( "A duplicate project already exist '" + storedProject.getName() + "'." );
}
}
/*
if ( store.getProjectByName( project.getName() ) != null )
{
throw new ContinuumException( "A project with the name '" + project.getName() + "' already exist." );
}
*/
// if ( getProjectByScmUrl( scmUrl ) != null )
// {
// throw new ContinuumStoreException( "A project with the scm url '" + scmUrl + "' already exist." );
// }
// TODO: Enable
// assertStringNotEmpty( project.getPath(), "path" );
// assertStringNotEmpty( project.getGroupId(), "group id" );
// assertStringNotEmpty( project.getArtifactId(), "artifact id" );
// if ( project.getProjectGroup() == null )
// {
// throw new ContinuumException( "A project has to belong to a project group." );
// }
// TODO: validate that the SCM provider id
}
}
| 5,085 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/StoreProjectAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "store-project" )
public class StoreProjectAction
extends AbstractContinuumAction
{
private static final String KEY_SCM_USE_CREDENTIALS_CACHE = "useCredentialsCache";
@Requirement
private ProjectGroupDao projectGroupDao;
public void execute( Map context )
throws ContinuumException, ContinuumStoreException
{
Project project = getUnvalidatedProject( context );
ProjectGroup projectGroup = getUnvalidatedProjectGroup( context );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
boolean useCredentialsCache = isUseScmCredentialsCache( context, false );
// CONTINUUM-1605 don't store username/password
if ( useCredentialsCache )
{
project.setScmUsername( null );
project.setScmPassword( null );
project.setScmUseCache( true );
}
projectGroup.addProject( project );
projectGroupDao.updateProjectGroup( projectGroup );
setProjectId( context, project.getId() );
// ----------------------------------------------------------------------
// Set the working directory
// ----------------------------------------------------------------------
/*
File projectWorkingDirectory = new File( getWorkingDirectory( context ), project.getId() );
if ( !projectWorkingDirectory.exists() && !projectWorkingDirectory.mkdirs() )
{
throw new ContinuumException( "Could not make the working directory for the project " +
"'" + projectWorkingDirectory.getAbsolutePath() + "'." );
}
// The working directory is created based on the project id so we can always
// figure out what it is.
project.setWorkingDirectory( projectWorkingDirectory.getAbsolutePath() );
*/
// store.updateProject( project );
}
public static boolean isUseScmCredentialsCache( Map<String, Object> context, boolean defaultValue )
{
return getBoolean( context, KEY_SCM_USE_CREDENTIALS_CACHE, defaultValue );
}
public static void setUseScmCredentialsCache( Map<String, Object> context, boolean useScmCredentialsCache )
{
context.put( KEY_SCM_USE_CREDENTIALS_CACHE, useScmCredentialsCache );
}
}
| 5,086 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AddBuildDefinitionToProjectGroupAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.List;
import java.util.Map;
/**
* AddBuildDefinitionToProjectAction:
*
* @author Jesse McConnell <jmcconnell@apache.org>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "add-build-definition-to-project-group" )
public class AddBuildDefinitionToProjectGroupAction
extends AbstractBuildDefinitionContinuumAction
{
@Requirement
private ProjectGroupDao projectGroupDao;
public void execute( Map context )
throws Exception
{
int projectGroupId = getProjectGroupId( context );
ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId );
BuildDefinitionTemplate buildDefinitionTemplate = getBuildDefinitionTemplate( context );
if ( buildDefinitionTemplate != null )
{
for ( BuildDefinition buildDefinition : (List<BuildDefinition>) buildDefinitionTemplate.getBuildDefinitions() )
{
resolveDefaultBuildDefinitionsForProjectGroup( buildDefinition, projectGroup );
projectGroup.addBuildDefinition( buildDefinition );
}
}
else
{
BuildDefinition buildDefinition = getBuildDefinition( context );
resolveDefaultBuildDefinitionsForProjectGroup( buildDefinition, projectGroup );
projectGroup.addBuildDefinition( buildDefinition );
}
// Save the project group
projectGroupDao.updateProjectGroup( projectGroup );
//map.put( AbstractContinuumAction.KEY_BUILD_DEFINITION, buildDefinition );
}
}
| 5,087 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AddAssignableRolesAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.redback.role.RoleManager;
import org.codehaus.plexus.redback.role.RoleManagerException;
import java.util.Map;
/**
* AddAssignableRolesAction:
*
* @author: Jesse McConnell <jmcconnell@apache.org>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "add-assignable-roles" )
public class AddAssignableRolesAction
extends AbstractContinuumAction
{
@Requirement
private ProjectGroupDao projectGroupDao;
@Requirement( hint = "default" )
private RoleManager roleManager;
public void execute( Map context )
throws ContinuumException, ContinuumStoreException
{
int projectGroupId = getProjectGroupId( context );
ProjectGroup projectGroup = projectGroupDao.getProjectGroup( projectGroupId );
// TODO: make the resource the name of the project group and hide the id from the user
try
{
if ( !roleManager.templatedRoleExists( "project-administrator", projectGroup.getName() ) )
{
roleManager.createTemplatedRole( "project-administrator", projectGroup.getName() );
}
if ( !roleManager.templatedRoleExists( "project-developer", projectGroup.getName() ) )
{
roleManager.createTemplatedRole( "project-developer", projectGroup.getName() );
}
if ( !roleManager.templatedRoleExists( "project-user", projectGroup.getName() ) )
{
roleManager.createTemplatedRole( "project-user", projectGroup.getName() );
}
}
catch ( RoleManagerException e )
{
e.printStackTrace();
throw new ContinuumException( "error generating templated role for project " + projectGroup.getName(), e );
}
}
}
| 5,088 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/UpdateProjectFromWorkingDirectoryContinuumAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.execution.ContinuumBuildExecutor;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorException;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "update-project-from-working-directory" )
public class UpdateProjectFromWorkingDirectoryContinuumAction
extends AbstractContinuumAction
{
@Requirement
private WorkingDirectoryService workingDirectoryService;
@Requirement
private BuildExecutorManager buildExecutorManager;
@Requirement
private BuildDefinitionDao buildDefinitionDao;
@Requirement
private ProjectDao projectDao;
public void execute( Map context )
throws ContinuumStoreException, ContinuumException, ContinuumBuildExecutorException
{
Project project = getProject( context );
project = projectDao.getProjectWithAllDetails( project.getId() );
getLogger().info( "Updating project '" + project.getName() + "' from checkout." );
BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( getBuildDefinitionId( context ) );
// ----------------------------------------------------------------------
// Make a new descriptor
// ----------------------------------------------------------------------
ContinuumBuildExecutor builder = buildExecutorManager.getBuildExecutor( project.getExecutorId() );
ScmResult scmResult = (ScmResult) context.get( "scmResult" );
List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context );
String projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() );
builder.updateProjectFromCheckOut( workingDirectoryService.getWorkingDirectory( project, projectScmRootUrl,
projectsWithCommonScmRoot ),
project, buildDefinition, scmResult );
// ----------------------------------------------------------------------
// Store the new descriptor
// ----------------------------------------------------------------------
projectDao.updateProject( project );
}
}
| 5,089 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CreateBuildProjectTaskAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.buildmanager.BuildsManager;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.execution.ContinuumBuildExecutor;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "create-build-project-task" )
public class CreateBuildProjectTaskAction
extends AbstractContinuumAction
{
@Requirement
private BuildExecutorManager executorManager;
@Requirement
private ProjectDao projectDao;
@Requirement( hint = "parallel" )
private BuildsManager parallelBuildsManager;
public synchronized void execute( Map context )
throws Exception
{
List<Project> projects = AbstractContinuumAction.getListOfProjects( context );
Map<Integer, BuildDefinition> projectsBuildDefinitionsMap =
AbstractContinuumAction.getProjectsBuildDefinitionsMap( context );
Map<Integer, ScmResult> scmResultMap = AbstractContinuumAction.getScmResultMap( context );
List<Project> projectsToBeBuilt = new ArrayList<Project>();
BuildTrigger buildTrigger = AbstractContinuumAction.getBuildTrigger( context );
int projectGroupId = AbstractContinuumAction.getProjectGroupId( context );
// update state of each project first
for ( Project project : projects )
{
BuildDefinition buildDefinition = projectsBuildDefinitionsMap.get( project.getId() );
if ( parallelBuildsManager.isInAnyBuildQueue( project.getId(), buildDefinition.getId() ) )
{
getLogger().info( "Project '" + project.getName() + "' is already in build queue." );
continue;
}
if ( parallelBuildsManager.isInAnyCheckoutQueue( project.getId() ) )
{
parallelBuildsManager.removeProjectFromCheckoutQueue( project.getId() );
}
try
{
/**
* The following can (and probably should) be simplified to:
*
* If project is building in executor or its state is UPDATING:
* * Skip the project and log it
*
* If project state is not in { NEW, CHECKEDOUT, OK, FAILED, ERROR }:
* * Set the project's state to ERROR
*
* Lastly, record the project's original state and add it to the list of projects to build
*/
if ( project.getState() != ContinuumProjectState.NEW &&
project.getState() != ContinuumProjectState.CHECKEDOUT &&
project.getState() != ContinuumProjectState.OK &&
project.getState() != ContinuumProjectState.FAILED &&
project.getState() != ContinuumProjectState.ERROR )
{
ContinuumBuildExecutor executor = executorManager.getBuildExecutor( project.getExecutorId() );
if ( executor.isBuilding( project ) || project.getState() == ContinuumProjectState.UPDATING )
{
// project is building
getLogger().info( "Project '" + project.getName() + "' already being built." );
continue;
}
else
{
project.setState( ContinuumProjectState.ERROR );
}
}
project.setOldState( project.getState() );
projectDao.updateProject( project );
project = projectDao.getProject( project.getId() );
projectsToBeBuilt.add( project );
}
catch ( ContinuumStoreException e )
{
getLogger().error( "Error while creating build object", e );
}
}
parallelBuildsManager.buildProjects( projectsToBeBuilt, projectsBuildDefinitionsMap, buildTrigger, scmResultMap,
projectGroupId );
}
}
| 5,090 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/StoreProjectGroupAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "store-project-group" )
public class StoreProjectGroupAction
extends AbstractContinuumAction
{
@Requirement
private ProjectGroupDao projectGroupDao;
public void execute( Map context )
throws ContinuumException, ContinuumStoreException
{
ProjectGroup projectGroup = getUnvalidatedProjectGroup( context );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
projectGroup = projectGroupDao.addProjectGroup( projectGroup );
AbstractContinuumAction.setProjectGroupId( context, projectGroup.getId() );
}
}
| 5,091 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/UpdateBuildDefinitionFromProjectAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.Map;
/**
* AddBuildDefinitionToProjectAction:
*
* @author Jesse McConnell <jmcconnell@apache.org>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "update-build-definition-from-project" )
public class UpdateBuildDefinitionFromProjectAction
extends AbstractBuildDefinitionContinuumAction
{
@Requirement
private ProjectDao projectDao;
public void execute( Map context )
throws Exception
{
BuildDefinition buildDefinition = getBuildDefinition( context );
int projectId = getProjectId( context );
Project project = projectDao.getProjectWithAllDetails( projectId );
resolveDefaultBuildDefinitionsForProject( buildDefinition, project );
updateBuildDefinitionInList( project.getBuildDefinitions(), buildDefinition );
AbstractContinuumAction.setBuildDefinition( context, buildDefinition );
}
}
| 5,092 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CheckWorkingDirectoryAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.io.File;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "check-working-directory" )
public class CheckWorkingDirectoryAction
extends AbstractContinuumAction
{
@Requirement
private WorkingDirectoryService workingDirectoryService;
@Requirement
private ProjectDao projectDao;
private static final String KEY_WORKING_DIRECTORY_EXISTS = "working-directory-exists";
public void execute( Map context )
throws Exception
{
Project project = projectDao.getProject( getProjectId( context ) );
List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context );
String projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() );
File workingDirectory = workingDirectoryService.getWorkingDirectory( project, projectScmRootUrl,
projectsWithCommonScmRoot );
if ( !workingDirectory.exists() )
{
setWorkingDirectoryExists( context, false );
return;
}
File[] files = workingDirectory.listFiles();
if ( files == null )
{
//workingDirectory isn't a directory but a file. Not possible in theory.
String msg = workingDirectory.getAbsolutePath() + " isn't a directory but a file.";
getLogger().error( msg );
throw new ContinuumException( msg );
}
setWorkingDirectoryExists( context, files.length > 0 );
}
public static boolean isWorkingDirectoryExists( Map<String, Object> context )
{
return getBoolean( context, KEY_WORKING_DIRECTORY_EXISTS, false );
}
public static void setWorkingDirectoryExists( Map<String, Object> context, boolean isWorkingDirectoryExists )
{
context.put( KEY_WORKING_DIRECTORY_EXISTS, isWorkingDirectoryExists );
}
}
| 5,093 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CreateProjectsFromMetadataAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.execution.SettingsConfigurationException;
import org.apache.maven.continuum.model.project.BuildDefinitionTemplate;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuilderException;
import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult;
import org.apache.maven.continuum.project.builder.manager.ContinuumProjectBuilderManager;
import org.apache.maven.continuum.project.builder.manager.ContinuumProjectBuilderManagerException;
import org.apache.maven.continuum.utils.ContinuumUrlValidator;
import org.apache.maven.continuum.utils.URLUserInfo;
import org.apache.maven.settings.MavenSettingsBuilder;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* Resolve the project url being passed in and gather authentication information
* if the url is so configured, then create the projects
* Supports:
* - standard maven-scm url
* - MungedUrl https://username:password@host
* - maven settings based, server = host and scm info set to username and password
*
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "create-projects-from-metadata" )
public class CreateProjectsFromMetadataAction
extends AbstractContinuumAction
{
/**
* Metadata url for adding projects.
*/
private static final String KEY_URL = "url";
private static final String KEY_PROJECT_BUILDER_ID = "builderId";
private static final String KEY_PROJECT_BUILDING_RESULT = "projectBuildingResult";
private static final String KEY_LOAD_RECURSIVE_PROJECTS = "loadRecursiveProjects";
public static final String KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY = "checkoutProjectsInSingleDirectory";
@Requirement
private ContinuumProjectBuilderManager projectBuilderManager;
@Requirement
private MavenSettingsBuilder mavenSettingsBuilder;
@Requirement( hint = "continuumUrl" )
private ContinuumUrlValidator urlValidator;
public void execute( Map context )
throws ContinuumException, ContinuumProjectBuilderManagerException, ContinuumProjectBuilderException
{
String projectBuilderId = getProjectBuilderId( context );
boolean loadRecursiveProjects = isLoadRecursiveProject( context );
boolean checkoutProjectsInSingleDirectory = getBoolean( context, KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY );
int projectGroupId = getProjectGroupId( context );
String curl = getUrl( context );
URL url;
ContinuumProjectBuilder projectBuilder = projectBuilderManager.getProjectBuilder( projectBuilderId );
ContinuumProjectBuildingResult result;
try
{
BuildDefinitionTemplate buildDefinitionTemplate = getBuildDefinitionTemplate( context );
if ( buildDefinitionTemplate == null )
{
buildDefinitionTemplate = projectBuilder.getDefaultBuildDefinitionTemplate();
}
if ( !curl.startsWith( "http" ) )
{
url = new URL( curl );
result = projectBuilder.buildProjectsFromMetadata( url, null, null, loadRecursiveProjects,
buildDefinitionTemplate,
checkoutProjectsInSingleDirectory, projectGroupId );
}
else
{
url = new URL( curl );
String host = url.getHost();
String username = null;
String password = null;
try
{
getLogger().info( "consulting settings for credentials to " + host );
Settings settings = getSettings();
Server server = settings.getServer( url.getHost() );
if ( server != null )
{
username = server.getUsername();
password = server.getPassword();
getLogger().info( "credentials found in settings, will fetch metadata as " + username );
}
else
{
getLogger().info( "credentials not found for server " + host );
}
}
catch ( SettingsConfigurationException se )
{
getLogger().warn( "problem with settings file, disabling scm resolution of username and password" );
}
if ( username == null )
{
URLUserInfo urlUserInfo = urlValidator.extractURLUserInfo( curl );
username = urlUserInfo.getUsername();
password = urlUserInfo.getPassword();
}
if ( urlValidator.isValid( curl ) )
{
result = projectBuilder.buildProjectsFromMetadata( url, username, password, loadRecursiveProjects,
buildDefinitionTemplate,
checkoutProjectsInSingleDirectory,
projectGroupId );
}
else
{
result = new ContinuumProjectBuildingResult();
getLogger().info( "Malformed URL (MungedHttpsURL is not valid): " + hidePasswordInUrl( curl ) );
result.addError( ContinuumProjectBuildingResult.ERROR_MALFORMED_URL );
}
}
if ( result.getProjects() != null )
{
String scmRootUrl = getScmRootUrl( result.getProjects() );
if ( scmRootUrl == null || scmRootUrl.equals( "" ) )
{
if ( curl.indexOf( "pom.xml" ) > 0 )
{
scmRootUrl = curl.substring( 0, curl.indexOf( "pom.xml" ) - 1 );
}
else
{
scmRootUrl = curl;
}
}
//setUrl( context, scmRootUrl );
setProjectScmRootUrl( context, scmRootUrl );
}
}
catch ( MalformedURLException e )
{
getLogger().info( "Malformed URL: " + hidePasswordInUrl( curl ), e );
result = new ContinuumProjectBuildingResult();
result.addError( ContinuumProjectBuildingResult.ERROR_MALFORMED_URL );
}
catch ( URISyntaxException e )
{
getLogger().info( "Malformed URL: " + hidePasswordInUrl( curl ), e );
result = new ContinuumProjectBuildingResult();
result.addError( ContinuumProjectBuildingResult.ERROR_MALFORMED_URL );
}
setProjectBuildingResult( context, result );
}
private String hidePasswordInUrl( String url )
{
int indexAt = url.indexOf( "@" );
if ( indexAt < 0 )
{
return url;
}
String s = url.substring( 0, indexAt );
int pos = s.lastIndexOf( ":" );
return s.substring( 0, pos + 1 ) + "*****" + url.substring( indexAt );
}
private Settings getSettings()
throws SettingsConfigurationException
{
try
{
return mavenSettingsBuilder.buildSettings();
}
catch ( IOException e )
{
throw new SettingsConfigurationException( "Error reading settings file", e );
}
catch ( XmlPullParserException e )
{
throw new SettingsConfigurationException( e.getMessage(), e.getDetail(), e.getLineNumber(),
e.getColumnNumber() );
}
}
private String getScmRootUrl( List<Project> projects )
{
String scmRootUrl = "";
for ( Project project : projects )
{
String scmUrl = project.getScmUrl();
scmRootUrl = getCommonPath( scmUrl, scmRootUrl );
}
return scmRootUrl;
}
private String getCommonPath( String path1, String path2 )
{
if ( path2 == null || path2.equals( "" ) )
{
return path1;
}
else
{
int indexDiff = StringUtils.differenceAt( path1, path2 );
String commonPath = path1.substring( 0, indexDiff );
if ( commonPath.lastIndexOf( '/' ) != commonPath.length() - 1 && !( path1.contains( new String(
commonPath + "/" ) ) || path2.contains( new String( commonPath + "/" ) ) ) )
{
while ( commonPath.lastIndexOf( '/' ) != commonPath.length() - 1 )
{
commonPath = commonPath.substring( 0, commonPath.length() - 1 );
}
}
return commonPath;
}
}
public ContinuumProjectBuilderManager getProjectBuilderManager()
{
return projectBuilderManager;
}
public void setProjectBuilderManager( ContinuumProjectBuilderManager projectBuilderManager )
{
this.projectBuilderManager = projectBuilderManager;
}
public MavenSettingsBuilder getMavenSettingsBuilder()
{
return mavenSettingsBuilder;
}
public void setMavenSettingsBuilder( MavenSettingsBuilder mavenSettingsBuilder )
{
this.mavenSettingsBuilder = mavenSettingsBuilder;
}
public ContinuumUrlValidator getUrlValidator()
{
return urlValidator;
}
public void setUrlValidator( ContinuumUrlValidator urlValidator )
{
this.urlValidator = urlValidator;
}
public static String getUrl( Map<String, Object> context )
{
return getString( context, KEY_URL );
}
public static void setUrl( Map<String, Object> context, String url )
{
context.put( KEY_URL, url );
}
public static String getProjectBuilderId( Map<String, Object> context )
{
return getString( context, KEY_PROJECT_BUILDER_ID );
}
public static void setProjectBuilderId( Map<String, Object> context, String projectBuilderId )
{
context.put( KEY_PROJECT_BUILDER_ID, projectBuilderId );
}
public static ContinuumProjectBuildingResult getProjectBuildingResult( Map<String, Object> context )
{
return (ContinuumProjectBuildingResult) getObject( context, KEY_PROJECT_BUILDING_RESULT );
}
private static void setProjectBuildingResult( Map<String, Object> context, ContinuumProjectBuildingResult result )
{
context.put( KEY_PROJECT_BUILDING_RESULT, result );
}
public static boolean isLoadRecursiveProject( Map<String, Object> context )
{
return getBoolean( context, KEY_LOAD_RECURSIVE_PROJECTS );
}
public static void setLoadRecursiveProject( Map<String, Object> context, boolean loadRecursiveProject )
{
context.put( KEY_LOAD_RECURSIVE_PROJECTS, loadRecursiveProject );
}
public static boolean isCheckoutProjectsInSingleDirectory( Map<String, Object> context )
{
return getBoolean( context, KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY );
}
public static void setCheckoutProjectsInSingleDirectory( Map<String, Object> context,
boolean checkoutProjectsInSingleDirectory )
{
context.put( KEY_CHECKOUT_PROJECTS_IN_SINGLE_DIRECTORY, checkoutProjectsInSingleDirectory );
}
}
| 5,094 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/RemoveAssignableRolesAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.redback.role.RoleManager;
import org.codehaus.plexus.redback.role.RoleManagerException;
import java.util.Map;
/**
* AddAssignableRolesAction:
*
* @author: Emmanuel Venisse <evenisse@apache.org>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "remove-assignable-roles" )
public class RemoveAssignableRolesAction
extends AbstractContinuumAction
{
@Requirement
private ProjectGroupDao projectGroupDao;
@Requirement( hint = "default" )
private RoleManager roleManager;
public void execute( Map context )
throws ContinuumException, ContinuumStoreException
{
int projectGroupId = getProjectGroupId( context );
ProjectGroup projectGroup = projectGroupDao.getProjectGroup( projectGroupId );
try
{
if ( !roleManager.templatedRoleExists( "project-administrator", projectGroup.getName() ) )
{
roleManager.removeTemplatedRole( "project-administrator", projectGroup.getName() );
}
if ( !roleManager.templatedRoleExists( "project-developer", projectGroup.getName() ) )
{
roleManager.removeTemplatedRole( "project-developer", projectGroup.getName() );
}
if ( !roleManager.templatedRoleExists( "project-user", projectGroup.getName() ) )
{
roleManager.removeTemplatedRole( "project-user", projectGroup.getName() );
}
}
catch ( RoleManagerException e )
{
e.printStackTrace();
throw new ContinuumException( "error removing templated role for project " + projectGroup.getName(), e );
}
}
}
| 5,095 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/RemoveBuildDefinitionFromProjectGroupAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.Map;
/**
* AddBuildDefinitionToProjectAction:
*
* @author: Jesse McConnell <jmcconnell@apache.org>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "remove-build-definition-from-project-group" )
public class RemoveBuildDefinitionFromProjectGroupAction
extends AbstractBuildDefinitionContinuumAction
{
@Requirement
private ProjectGroupDao projectGroupDao;
public void execute( Map context )
throws Exception
{
BuildDefinition buildDefinition = getBuildDefinition( context );
int projectGroupId = getProjectGroupId( context );
ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId );
if ( buildDefinition.isDefaultForProject() )
{
throw new ContinuumException( "can't remove default build definition from project group" );
}
projectGroup.removeBuildDefinition( buildDefinition );
projectGroupDao.updateProjectGroup( projectGroup );
}
}
| 5,096 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CheckoutProjectContinuumAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.scm.ContinuumScm;
import org.apache.continuum.scm.ContinuumScmConfiguration;
import org.apache.continuum.scm.ContinuumScmUtils;
import org.apache.continuum.utils.ContinuumUtils;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.command.checkout.CheckOutScmResult;
import org.apache.maven.scm.manager.NoSuchScmProviderException;
import org.apache.maven.scm.repository.ScmRepositoryException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "checkout-project" )
public class CheckoutProjectContinuumAction
extends AbstractContinuumAction
{
private static final String KEY_SCM_USERNAME = "scmUserName";
private static final String KEY_SCM_PASSWORD = "scmUserPassword";
private static final String KEY_PROJECT_RELATIVE_PATH = "project-relative-path";
private static final String KEY_CHECKOUT_SCM_RESULT = "checkout-result";
@Requirement
private ContinuumNotificationDispatcher notifier;
@Requirement
private ContinuumScm scm;
@Requirement
private BuildDefinitionDao buildDefinitionDao;
@Requirement
private ProjectDao projectDao;
public void execute( Map context )
throws ContinuumStoreException
{
Project project = projectDao.getProject( getProject( context ).getId() );
BuildDefinition buildDefinition = getBuildDefinition( context );
if ( buildDefinition != null )
{
buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinition.getId() );
}
int originalState = project.getState();
project.setState( ContinuumProjectState.CHECKING_OUT );
projectDao.updateProject( project );
File workingDirectory = getWorkingDirectory( context );
// ----------------------------------------------------------------------
// Check out the project
// ----------------------------------------------------------------------
ScmResult result;
List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context );
try
{
String scmUserName = getScmUsername( context, project.getScmUsername() );
String scmPassword = getScmPassword( context, project.getScmPassword() );
String scmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() );
ContinuumScmConfiguration config = createScmConfiguration( project, workingDirectory, scmUserName,
scmPassword, scmRootUrl, isRootDirectory(
context ) );
String tag = config.getTag();
getLogger().info(
"Checking out project: '" + project.getName() + "', id: '" + project.getId() + "' " + "to '" +
workingDirectory + "'" + ( tag != null ? " with branch/tag " + tag + "." : "." ) );
CheckOutScmResult checkoutResult = scm.checkout( config );
if ( StringUtils.isNotEmpty( checkoutResult.getRelativePathProjectDirectory() ) )
{
setProjectRelativePath( context, checkoutResult.getRelativePathProjectDirectory() );
}
if ( !checkoutResult.isSuccess() )
{
// TODO: is it more appropriate to return this in the converted result so that it can be presented to
// the user?
String msg = "Error while checking out the code for project: '" + project.getName() + "', id: '" +
project.getId() + "' to '" + workingDirectory.getAbsolutePath() + "'" +
( tag != null ? " with branch/tag " + tag + "." : "." );
getLogger().warn( msg );
getLogger().warn( "Command output: " + checkoutResult.getCommandOutput() );
getLogger().warn( "Provider message: " + checkoutResult.getProviderMessage() );
}
else
{
getLogger().info( "Checked out " + checkoutResult.getCheckedOutFiles().size() + " files." );
}
result = convertScmResult( checkoutResult );
}
catch ( ScmRepositoryException e )
{
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( e.getMessage() + ": " + getValidationMessages( e ) );
getLogger().error( e.getMessage(), e );
}
catch ( NoSuchScmProviderException e )
{
// TODO: this is not making it back into a result of any kind - log it at least. Same is probably the case for ScmException
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( e.getMessage() );
getLogger().error( e.getMessage(), e );
}
catch ( ScmException e )
{
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( e ) );
getLogger().error( e.getMessage(), e );
}
catch ( Throwable t )
{
// TODO: do we want this here, or should it be to the logs?
// TODO: what throwables do we really get here that we can cope with?
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( t ) );
getLogger().error( t.getMessage(), t );
}
finally
{
String relativePath = getProjectRelativePath( context );
if ( StringUtils.isNotEmpty( relativePath ) )
{
project.setRelativePath( relativePath );
}
project = projectDao.getProject( project.getId() );
if ( originalState == ContinuumProjectState.NEW )
{
project.setState( ContinuumProjectState.CHECKEDOUT );
}
else
{
project.setState( originalState );
}
projectDao.updateProject( project );
// update state of sub-projects
// if multi-module project was checked out in a single directory, these must not be null
for ( Project projectWithCommonScmRoot : projectsWithCommonScmRoot )
{
projectWithCommonScmRoot = projectDao.getProject( projectWithCommonScmRoot.getId() );
if ( projectWithCommonScmRoot != null && projectWithCommonScmRoot.getId() != project.getId() &&
projectWithCommonScmRoot.getState() == ContinuumProjectState.NEW )
{
projectWithCommonScmRoot.setState( ContinuumProjectState.CHECKEDOUT );
projectDao.updateProject( projectWithCommonScmRoot );
}
}
notifier.checkoutComplete( project, buildDefinition );
}
setCheckoutScmResult( context, result );
setProject( context, project );
}
private ContinuumScmConfiguration createScmConfiguration( Project project, File workingDirectory,
String scmUserName, String scmPassword, String scmRootUrl,
boolean isRootDirectory )
{
ContinuumScmConfiguration config = new ContinuumScmConfiguration();
if ( project.isCheckedOutInSingleDirectory() && scmRootUrl != null && !"".equals( scmRootUrl ) &&
isRootDirectory )
{
config.setUrl( scmRootUrl );
}
else
{
config.setUrl( project.getScmUrl() );
}
// CONTINUUM-2628
config = ContinuumScmUtils.setSCMCredentialsforSSH( config, config.getUrl(), scmUserName, scmPassword );
config.setUseCredentialsCache( project.isScmUseCache() );
config.setWorkingDirectory( workingDirectory );
config.setTag( project.getScmTag() );
return config;
}
private ScmResult convertScmResult( CheckOutScmResult scmResult )
{
ScmResult result = new ScmResult();
result.setSuccess( scmResult.isSuccess() );
result.setCommandLine( maskPassword( scmResult.getCommandLine() ) );
result.setCommandOutput( scmResult.getCommandOutput() );
result.setProviderMessage( scmResult.getProviderMessage() );
return result;
}
// TODO: migrate to the SvnCommandLineUtils version (preferably properly encapsulated in the provider)
private String maskPassword( String commandLine )
{
String cmd = commandLine;
if ( cmd != null && cmd.startsWith( "svn" ) )
{
String pwdString = "--password";
if ( cmd.indexOf( pwdString ) > 0 )
{
int index = cmd.indexOf( pwdString ) + pwdString.length() + 1;
int nextSpace = cmd.indexOf( " ", index );
cmd = cmd.substring( 0, index ) + "********" + cmd.substring( nextSpace );
}
}
return cmd;
}
private String getValidationMessages( ScmRepositoryException ex )
{
List<String> messages = ex.getValidationMessages();
StringBuffer message = new StringBuffer();
if ( messages != null && !messages.isEmpty() )
{
for ( Iterator<String> i = messages.iterator(); i.hasNext(); )
{
message.append( i.next() );
if ( i.hasNext() )
{
message.append( System.getProperty( "line.separator" ) );
}
}
}
return message.toString();
}
public static String getScmUsername( Map<String, Object> context, String defaultValue )
{
return getString( context, KEY_SCM_USERNAME, defaultValue );
}
public static void setScmUsername( Map<String, Object> context, String scmUsername )
{
context.put( KEY_SCM_USERNAME, scmUsername );
}
public static String getScmPassword( Map<String, Object> context, String defaultValue )
{
return getString( context, KEY_SCM_PASSWORD, defaultValue );
}
public static void setScmPassword( Map<String, Object> context, String scmPassword )
{
context.put( KEY_SCM_PASSWORD, scmPassword );
}
public static String getProjectRelativePath( Map<String, Object> context )
{
return getString( context, KEY_PROJECT_RELATIVE_PATH, "" );
}
public static void setProjectRelativePath( Map<String, Object> context, String projectRelativePath )
{
context.put( KEY_PROJECT_RELATIVE_PATH, projectRelativePath );
}
public static ScmResult getCheckoutScmResult( Map<String, Object> context, ScmResult defaultValue )
{
return (ScmResult) getObject( context, KEY_CHECKOUT_SCM_RESULT, defaultValue );
}
public static void setCheckoutScmResult( Map<String, Object> context, ScmResult scmResult )
{
context.put( KEY_CHECKOUT_SCM_RESULT, scmResult );
}
}
| 5,097 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/UpdateWorkingDirectoryFromScmContinuumAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.scm.ContinuumScm;
import org.apache.continuum.scm.ContinuumScmConfiguration;
import org.apache.continuum.scm.ContinuumScmUtils;
import org.apache.continuum.utils.ContinuumUtils;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ChangeFile;
import org.apache.maven.continuum.model.scm.ChangeSet;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.store.ContinuumObjectNotFoundException;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.command.update.UpdateScmResult;
import org.apache.maven.scm.manager.NoSuchScmProviderException;
import org.apache.maven.scm.repository.ScmRepositoryException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "update-working-directory-from-scm" )
public class UpdateWorkingDirectoryFromScmContinuumAction
extends AbstractContinuumAction
{
private static final String KEY_UPDATE_SCM_RESULT = "update-result";
@Requirement
private ContinuumNotificationDispatcher notifier;
@Requirement
private ContinuumScm scm;
@Requirement
private WorkingDirectoryService workingDirectoryService;
@Requirement
private BuildResultDao buildResultDao;
@Requirement
private ProjectDao projectDao;
public void execute( Map context )
throws ScmRepositoryException, NoSuchScmProviderException, ScmException, ContinuumObjectNotFoundException,
ContinuumStoreException
{
Project project = projectDao.getProject( getProject( context ).getId() );
BuildDefinition buildDefinition = getBuildDefinition( context );
UpdateScmResult scmResult;
ScmResult result;
Date latestUpdateDate = null;
int originalState = project.getState();
project.setState( ContinuumProjectState.UPDATING );
projectDao.updateProject( project );
try
{
BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( project.getId() );
latestUpdateDate = new Date( buildResult.getStartTime() );
}
catch ( Exception e )
{
}
try
{
notifier.checkoutStarted( project, buildDefinition );
List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context );
String projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() );
// TODO: not sure why this is different to the context, but it all needs to change
File workingDirectory = workingDirectoryService.getWorkingDirectory( project, projectScmRootUrl,
projectsWithCommonScmRoot );
ContinuumScmConfiguration config = createScmConfiguration( project, workingDirectory, projectScmRootUrl );
config.setLatestUpdateDate( latestUpdateDate );
String tag = config.getTag();
String msg =
project.getName() + "', id: '" + project.getId() + "' to '" + workingDirectory.getAbsolutePath() + "'" +
( tag != null ? " with branch/tag " + tag + "." : "." );
getLogger().info( "Updating project: " + msg );
scmResult = scm.update( config );
if ( !scmResult.isSuccess() )
{
getLogger().warn( "Error while updating the code for project: '" + msg );
getLogger().warn( "Command output: " + scmResult.getCommandOutput() );
getLogger().warn( "Provider message: " + scmResult.getProviderMessage() );
}
if ( scmResult.getUpdatedFiles() != null && scmResult.getUpdatedFiles().size() > 0 )
{
getLogger().info( "Updated " + scmResult.getUpdatedFiles().size() + " files." );
}
result = convertScmResult( scmResult );
}
catch ( ScmRepositoryException e )
{
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( e.getMessage() + ": " + getValidationMessages( e ) );
getLogger().error( e.getMessage(), e );
}
catch ( NoSuchScmProviderException e )
{
// TODO: this is not making it back into a result of any kind - log it at least. Same is probably the case for ScmException
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( e.getMessage() );
getLogger().error( e.getMessage(), e );
}
catch ( ScmException e )
{
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( e ) );
getLogger().error( e.getMessage(), e );
}
finally
{
// set back to the original state
try
{
project = projectDao.getProject( project.getId() );
project.setState( originalState );
projectDao.updateProject( project );
}
catch ( Exception e )
{
// nasty nasty, but we're in finally, so just sacrifice the state to keep the original exception
getLogger().error( e.getMessage(), e );
}
notifier.checkoutComplete( project, buildDefinition );
}
setUpdateScmResult( context, result );
AbstractContinuumAction.setProject( context, project );
}
private ContinuumScmConfiguration createScmConfiguration( Project project, File workingDirectory,
String scmRootUrl )
{
ContinuumScmConfiguration config = new ContinuumScmConfiguration();
if ( project.isCheckedOutInSingleDirectory() && scmRootUrl != null && !"".equals( scmRootUrl ) )
{
config.setUrl( scmRootUrl );
}
else
{
config.setUrl( project.getScmUrl() );
}
// CONTINUUM-2628
config = ContinuumScmUtils.setSCMCredentialsforSSH( config, config.getUrl(), project.getScmUsername(),
project.getScmPassword() );
config.setUseCredentialsCache( project.isScmUseCache() );
config.setWorkingDirectory( workingDirectory );
config.setTag( project.getScmTag() );
return config;
}
private ScmResult convertScmResult( UpdateScmResult scmResult )
{
ScmResult result = new ScmResult();
result.setCommandLine( maskPassword( scmResult.getCommandLine() ) );
result.setSuccess( scmResult.isSuccess() );
result.setCommandOutput( scmResult.getCommandOutput() );
result.setProviderMessage( scmResult.getProviderMessage() );
if ( scmResult.getChanges() != null && !scmResult.getChanges().isEmpty() )
{
for ( org.apache.maven.scm.ChangeSet scmChangeSet : (List<org.apache.maven.scm.ChangeSet>) scmResult.getChanges() )
{
ChangeSet change = new ChangeSet();
change.setAuthor( scmChangeSet.getAuthor() );
change.setComment( scmChangeSet.getComment() );
if ( scmChangeSet.getDate() != null )
{
change.setDate( scmChangeSet.getDate().getTime() );
}
if ( scmChangeSet.getFiles() != null )
{
for ( org.apache.maven.scm.ChangeFile f : (List<org.apache.maven.scm.ChangeFile>) scmChangeSet.getFiles() )
{
ChangeFile file = new ChangeFile();
file.setName( f.getName() );
file.setRevision( f.getRevision() );
change.addFile( file );
}
}
result.addChange( change );
}
}
else
{
// We don't have a changes information probably because provider doesn't have a changelog command
// so we use the updated list that contains only the updated files list
ChangeSet changeSet = convertScmFileSetToChangeSet( scmResult.getUpdatedFiles() );
if ( changeSet != null )
{
result.addChange( changeSet );
}
}
return result;
}
private static ChangeSet convertScmFileSetToChangeSet( List<ScmFile> files )
{
ChangeSet changeSet = null;
if ( files != null && !files.isEmpty() )
{
changeSet = new ChangeSet();
// TODO: author, etc.
for ( ScmFile scmFile : files )
{
ChangeFile file = new ChangeFile();
file.setName( scmFile.getPath() );
// TODO: revision?
file.setStatus( scmFile.getStatus().toString() );
changeSet.addFile( file );
}
}
return changeSet;
}
// TODO: migrate to the SvnCommandLineUtils version (preferably properly encapsulated in the provider)
private String maskPassword( String commandLine )
{
String cmd = commandLine;
if ( cmd != null && cmd.startsWith( "svn" ) )
{
String pwdString = "--password";
if ( cmd.indexOf( pwdString ) > 0 )
{
int index = cmd.indexOf( pwdString ) + pwdString.length() + 1;
int nextSpace = cmd.indexOf( " ", index );
cmd = cmd.substring( 0, index ) + "********" + cmd.substring( nextSpace );
}
}
return cmd;
}
private String getValidationMessages( ScmRepositoryException ex )
{
List<String> messages = ex.getValidationMessages();
StringBuffer message = new StringBuffer();
if ( messages != null && !messages.isEmpty() )
{
for ( Iterator<String> i = messages.iterator(); i.hasNext(); )
{
message.append( i.next() );
if ( i.hasNext() )
{
message.append( System.getProperty( "line.separator" ) );
}
}
}
return message.toString();
}
public static ScmResult getUpdateScmResult( Map<String, Object> context, ScmResult defaultValue )
{
return (ScmResult) getObject( context, KEY_UPDATE_SCM_RESULT, defaultValue );
}
public static void setUpdateScmResult( Map<String, Object> context, ScmResult scmResult )
{
context.put( KEY_UPDATE_SCM_RESULT, scmResult );
}
}
| 5,098 |
0 | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core | Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AddProjectToCheckOutQueueAction.java | package org.apache.maven.continuum.core.action;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.lang.StringUtils;
import org.apache.continuum.buildmanager.BuildsManager;
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import java.util.Map;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
@Component( role = org.codehaus.plexus.action.Action.class, hint = "add-project-to-checkout-queue" )
public class AddProjectToCheckOutQueueAction
extends AbstractContinuumAction
{
@Requirement
private WorkingDirectoryService workingDirectoryService;
@Requirement
private ProjectDao projectDao;
@Requirement( hint = "parallel" )
private BuildsManager parallelBuildsManager;
@SuppressWarnings( "unchecked" )
public void execute( Map context )
throws Exception
{
Project project = getProject( context, null );
if ( project == null )
{
project = projectDao.getProject( getProjectId( context ) );
}
String scmUsername = project.getScmUsername();
String scmPassword = project.getScmPassword();
if ( scmUsername == null || StringUtils.isEmpty( scmUsername ) )
{
scmUsername = CheckoutProjectContinuumAction.getScmUsername( context, null );
}
if ( scmPassword == null || StringUtils.isEmpty( scmPassword ) )
{
scmPassword = CheckoutProjectContinuumAction.getScmPassword( context, null );
}
String scmRootUrl = getProjectScmRootUrl( context, null );
BuildDefinition defaultBuildDefinition = getBuildDefinition( context );
parallelBuildsManager.checkoutProject( project.getId(), project.getName(),
workingDirectoryService.getWorkingDirectory( project ), scmRootUrl,
scmUsername, scmPassword, defaultBuildDefinition,
getListOfProjectsInGroupWithCommonScmRoot( context ) );
}
}
| 5,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.