private StorageAsset getAssetByPath( String assetPath )
{
+ log.debug( "Get asset {}", assetPath );
return getStorage( ).getAsset( assetPath );
}
org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository(repositoryId);
+ log.debug( "Finding artifact path for {}, {}, {}, {}", groupId, artifactId, version, packaging );
ItemSelector selector = ArchivaItemSelector.builder( )
.withNamespace( groupId )
.withProjectId( artifactId )
+++ /dev/null
-package org.apache.archiva;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
-import org.apache.archiva.redback.rest.services.AbstractRestServicesTest;
-import org.apache.archiva.remotedownload.DownloadArtifactsTest;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.archiva.web.api.RuntimeInfoService;
-import org.apache.archiva.web.model.ApplicationRuntimeInfo;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Collections;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public class RuntimeInfoServiceTest
- extends AbstractRestServicesTest
-{
-
- private static Path appServerBase;
- private static String previousAppServerBase;
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrvrt_" );
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- @Before
- public void startServer()
- throws Exception
- {
- Path jcrDirectory = appServerBase.resolve( "jcr" );
-
- if ( Files.exists(jcrDirectory) )
- {
- org.apache.archiva.common.utils.FileUtils.deleteDirectory( jcrDirectory );
- }
-
- super.startServer();
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- return "classpath*:META-INF/spring-context.xml,classpath:/spring-context-with-jcr.xml";
- }
-
- @Override
- protected String getRestServicesPath()
- {
- return "restServices";
- }
-
- protected String getBaseUrl()
- {
- String baseUrlSysProps = System.getProperty( "archiva.baseRestUrl" );
- return StringUtils.isBlank( baseUrlSysProps ) ? "http://localhost:" + getServerPort() : baseUrlSysProps;
- }
-
- @Test
- public void runtimeInfoService()
- throws Exception
- {
- RuntimeInfoService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaUiServices/",
- RuntimeInfoService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client(service).header("Referer","http://localhost");
- ApplicationRuntimeInfo applicationRuntimeInfo = service.getApplicationRuntimeInfo( "en" );
-
- assertEquals( System.getProperty( "expectedVersion" ), applicationRuntimeInfo.getVersion() );
- assertFalse( applicationRuntimeInfo.isJavascriptLog() );
- assertTrue( applicationRuntimeInfo.isLogMissingI18n() );
-
- }
-}
+++ /dev/null
-package org.apache.archiva;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.metadata.repository.RepositorySessionFactory;
-import org.apache.archiva.metadata.repository.RepositorySessionFactoryBean;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Properties;
-
-/**
- * @author Olivier Lamy
- */
-public class TestRepositorySessionFactoryBean
- extends RepositorySessionFactoryBean
-{
-
- private Logger logger = LoggerFactory.getLogger( getClass() );
-
- private String beanId;
-
- public TestRepositorySessionFactoryBean( String beanId )
- {
- super( new Properties( ) );
- this.beanId = beanId;
- }
-
- @Override
- public Class<RepositorySessionFactory> getObjectType()
- {
- return RepositorySessionFactory.class;
- }
-
- @Override
- protected RepositorySessionFactory createInstance()
- throws Exception
- {
- RepositorySessionFactory repositorySessionFactory =
- getBeanFactory().getBean( "repositorySessionFactory#" + this.beanId, RepositorySessionFactory.class );
- logger.info( "create RepositorySessionFactory instance of {}", repositorySessionFactory.getClass().getName() );
- if (!repositorySessionFactory.isOpen()) {
- repositorySessionFactory.open();
- }
- return repositorySessionFactory;
- }
-
- @Override
- public String getId()
- {
- return this.beanId;
- }
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
-import junit.framework.TestCase;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.redback.rest.api.services.RoleManagementService;
-import org.apache.archiva.redback.rest.api.services.UserService;
-import org.apache.archiva.redback.rest.services.BaseSetup;
-import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
-import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
-import org.apache.archiva.rest.api.services.ProxyConnectorService;
-import org.apache.archiva.rest.api.services.RemoteRepositoriesService;
-import org.apache.archiva.rest.api.services.RepositoriesService;
-import org.apache.archiva.rest.api.services.RepositoryGroupService;
-import org.apache.archiva.rest.api.services.SearchService;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.archiva.webdav.RepositoryServlet;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.SystemUtils;
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.transport.servlet.CXFServlet;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.session.SessionHandler;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.web.context.ContextLoaderListener;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public abstract class AbstractDownloadTest
- extends TestCase
-{
-
- AtomicReference<Path> projectDir = new AtomicReference<>( );
- AtomicReference<Path> basePath = new AtomicReference<>( );
-
- protected List<Path> createdPaths = new ArrayList<>( );
-
- protected final Logger log = LoggerFactory.getLogger( getClass() );
-
- protected static String previousAppServerBase;
-
- public String authorizationHeader = getAdminAuthzHeader();
-
- public Server server = null;
-
- ServerConnector serverConnector;
-
- public int port;
-
- protected Path getProjectDirectory() {
- if ( projectDir.get()==null) {
- String propVal = System.getProperty("mvn.project.base.dir");
- Path newVal;
- if (StringUtils.isEmpty(propVal)) {
- newVal = Paths.get("").toAbsolutePath();
- } else {
- newVal = Paths.get(propVal).toAbsolutePath();
- }
- projectDir.compareAndSet(null, newVal);
- }
- return projectDir.get();
- }
-
- public Path getBasedir()
- {
- if (basePath.get()==null) {
- String baseDir = System.getProperty( "basedir" );
- final Path baseDirPath;
- if (StringUtils.isNotEmpty( baseDir )) {
- baseDirPath = Paths.get( baseDir );
- } else {
- baseDirPath = getProjectDirectory( );
- }
- basePath.compareAndSet( null, baseDirPath );
- }
- return basePath.get( );
- }
-
-
-
- public static String encode( String uid, String password )
- {
- return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
- }
-
- public static String getAdminAuthzHeader()
- {
- String adminPwdSysProps = System.getProperty( "rest.admin.pwd" );
- if ( StringUtils.isBlank( adminPwdSysProps ) )
- {
- return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, BaseSetup.getAdminPwd() );
- }
- return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminPwdSysProps );
- }
-
-
- protected abstract String getSpringConfigLocation();
-
-
- protected String getRestServicesPath()
- {
- return "restServices";
- }
-
-
- @Before
- public void startServer()
- throws Exception
- {
-
- System.setProperty( "redback.admin.creation.file", "target/auto-admin-creation.properties" );
-
- server = new Server();
- serverConnector = new ServerConnector( server, new HttpConnectionFactory() );
- server.addConnector( serverConnector );
-
- ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
- ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS );
- context.setResourceBase( SystemUtils.JAVA_IO_TMPDIR );
- context.setSessionHandler( new SessionHandler() );
- context.addServlet( servletHolder, "/" + getRestServicesPath() + "/*" );
- context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
- context.addEventListener( new ContextLoaderListener() );
-
- ServletHolder servletHolderRepo = new ServletHolder( new RepositoryServlet() );
- context.addServlet( servletHolderRepo, "/repository/*" );
-
- server.setHandler( context );
- server.start();
- port = serverConnector.getLocalPort();
- log.info( "start server on port {}", this.port );
-
- User user = new User();
- user.setEmail( "toto@toto.fr" );
- user.setFullName( "the root user" );
- user.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
- user.setPassword( BaseSetup.getAdminPwd() );
-
- getUserService( null ).createAdminUser( user );
-
-
- }
-
-
- @After
- @Override
- public void tearDown()
- throws Exception
- {
-
- for(Path dir : createdPaths) {
- if ( Files.exists( dir)) {
- FileUtils.deleteQuietly( dir.toFile( ) );
- }
- }
- createdPaths.clear();
-
- System.clearProperty( "redback.admin.creation.file" );
- super.tearDown();
- if ( this.server != null )
- {
- this.server.stop();
- }
- }
-
-
- protected ProxyConnectorService getProxyConnectorService()
- {
- ProxyConnectorService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
- ProxyConnectorService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
- return service;
- }
-
- protected RemoteRepositoriesService getRemoteRepositoriesService()
- {
- RemoteRepositoriesService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
- RemoteRepositoriesService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
- return service;
- }
-
- protected ManagedRepositoriesService getManagedRepositoriesService()
- {
- ManagedRepositoriesService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
- ManagedRepositoriesService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
- return service;
- }
-
-
- protected RepositoryGroupService getRepositoryGroupService()
- {
- RepositoryGroupService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
- RepositoryGroupService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
- return service;
- }
-
- protected RepositoriesService getRepositoriesService()
- {
- RepositoriesService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
- RepositoriesService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
- return service;
- }
-
- protected SearchService getSearchService()
- {
- SearchService service =
- JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
- SearchService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
- return service;
- }
-
- protected String getBaseUrl()
- {
- String baseUrlSysProps = System.getProperty( "archiva.baseRestUrl" );
- return StringUtils.isBlank( baseUrlSysProps ) ? "http://localhost:" + port : baseUrlSysProps;
- }
-
-
- protected RoleManagementService getRoleManagementService( String authzHeader )
- {
- RoleManagementService service =
- JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
- RoleManagementService.class,
- Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- // for debuging purpose
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 3000000L );
-
- if ( authzHeader != null )
- {
- WebClient.client( service ).header( "Authorization", authzHeader );
- }
- return service;
- }
-
- protected UserService getUserService( String authzHeader )
- {
- UserService service =
- JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
- UserService.class, Collections.singletonList( new JacksonJaxbJsonProvider() ) );
-
- WebClient.client( service ).header( "Referer", "http://localhost:" + port );
-
- // for debuging purpose
- WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 3000000L );
-
- if ( authzHeader != null )
- {
- WebClient.client( service ).header( "Authorization", authzHeader );
- }
- return service;
- }
-
- protected FakeCreateAdminService getFakeCreateAdminService()
- {
- return JAXRSClientFactory.create(
- "http://localhost:" + port + "/" + getRestServicesPath() + "/fakeCreateAdminService/",
- FakeCreateAdminService.class );
- }
-
-
- protected List<String> getZipEntriesNames( ZipFile zipFile )
- {
- try
- {
- List<String> entriesNames = new ArrayList<>();
- Enumeration<? extends ZipEntry> entries = zipFile.entries();
- while ( entries.hasMoreElements() )
- {
- entriesNames.add( entries.nextElement().getName() );
- }
- return entriesNames;
- }
- catch ( Throwable e )
- {
- log.info( "fail to get zipEntries {}", e.getMessage(), e );
- }
- return Collections.emptyList();
- }
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
-import org.apache.archiva.rest.api.services.RepositoriesService;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.commons.io.FileUtils;
-import org.assertj.core.api.Assertions;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import javax.ws.rs.RedirectionException;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.net.URI;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Locale;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public class DownloadArtifactFromQueryTest
- extends AbstractDownloadTest
-{
-
- private static Path appServerBase;
-
- private Path indexDir;
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv1_" ).toAbsolutePath();
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- System.out.println( "Appserver base: " + System.getProperty( "appserver.base" ) );
- return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-merge-index-download.xml";
- }
-
- @Before
- public void init() throws IOException
- {
- indexDir = Files.createTempDirectory( "archiva-web-common-index" );
- }
-
- @After
- public void cleanup()
- throws Exception
- {
- super.tearDown();
- if ( Files.exists( indexDir ) )
- {
- FileUtils.deleteDirectory( indexDir.toFile() );
- }
- }
-
-
- protected String createAndScanRepo()
- throws Exception
- {
-
- String id = Long.toString( System.currentTimeMillis() );
- Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
- Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
- createdPaths.add( testRep );
-
-
- ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
- managedRepository.setId( id );
- managedRepository.setName( "name of " + id );
- managedRepository.setLocation( testRep.toString() );
- managedRepository.setIndexDirectory( indexDir.resolve( "index-"+id ).toString());
- managedRepository.setPackedIndexDirectory( indexDir.resolve( "indexpacked-"+id ).toString());
-
- ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
-
- if ( managedRepositoriesService.getManagedRepository( id ) != null )
- {
- managedRepositoriesService.deleteManagedRepository( id, false );
- }
-
- getManagedRepositoriesService().addManagedRepository( managedRepository );
-
- RepositoriesService repositoriesService = getRepositoriesService();
-
- repositoriesService.scanRepositoryNow( id, true );
-
- // wait a bit to ensure index is finished
- int timeout = 20000;
- while ( timeout > 0 && repositoriesService.getScanStatus( id ).isAlreadyScanning() )
- {
- Thread.sleep( 500 );
- timeout -= 500;
- }
-
- return id;
-
- }
-
- @Test( expected = RedirectionException.class )
- public void downloadFixedVersion()
- throws Exception
- {
-
- String id = createAndScanRepo();
-
- try
- {
- Response response =
- getSearchService().redirectToArtifactFile( null, "org.apache.archiva", "archiva-test", "1.0", null,
- null );
-
- }
- catch ( RedirectionException e )
- {
- Assertions.assertThat( e.getLocation().compareTo( new URI( "http://localhost:" + port + "/repository/" + id
- + "/org/apache/archiva/archiva-test/1.0/archiva-test-1.0.jar" ) ) ).isEqualTo(
- 0 );
- throw e;
- }
- finally
- {
- getManagedRepositoriesService().deleteManagedRepository( id, false );
- }
-
- }
-
-
- @Test( expected = RedirectionException.class )
- public void downloadLatestVersion()
- throws Exception
- {
- String id = createAndScanRepo();
-
- try
- {
- Response response =
- getSearchService().redirectToArtifactFile( null, "org.apache.archiva", "archiva-test", "LATEST", null,
- null );
-
- }
- catch ( RedirectionException e )
- {
- Assertions.assertThat( e.getLocation().compareTo( new URI( "http://localhost:" + port + "/repository/" + id
- + "/org/apache/archiva/archiva-test/2.0/archiva-test-2.0.jar" ) ) ).isEqualTo(
- 0 );
- throw e;
- }
- finally
- {
- getManagedRepositoriesService().deleteManagedRepository( id, false );
- }
-
- }
-
- @Test
- public void download_no_content()
- throws Exception
- {
- String id = createAndScanRepo();
-
- try
- {
- Response response =
- getSearchService().redirectToArtifactFile( null, "org.apache.archiva.beer", "archiva-wine", "LATEST",
- null, null );
-
- Assert.assertEquals( Response.Status.NO_CONTENT.getStatusCode(), response.getStatus() );
-
-
- }
- finally
- {
- getManagedRepositoriesService().deleteManagedRepository( id, false );
- }
-
- }
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.RemoteRepository;
-import org.apache.archiva.redback.rest.api.services.RoleManagementService;
-import org.apache.archiva.security.common.ArchivaRoleConstants;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.maven.wagon.providers.http.HttpWagon;
-import org.apache.maven.wagon.repository.Repository;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public class DownloadArtifactsTest
- extends AbstractDownloadTest
-{
-
- protected Logger log = LoggerFactory.getLogger( DownloadArtifactsTest.class );
-
- public Server redirectServer = null;
-
- public int redirectPort;
-
- public Server repoServer = null;
-
- public int repoServerPort;
-
- private static Path appServerBase;
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- System.out.println( "Setting appserver base" );
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv2_" ).toAbsolutePath( );
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
- return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml";
- }
-
- @Override
-
- @Before
- public void startServer()
- throws Exception
- {
- super.startServer();
-
- // repo handler
-
- this.repoServer = new Server( );
- ServerConnector repoServerConnector = new ServerConnector( this.repoServer, new HttpConnectionFactory());
- this.repoServer.addConnector( repoServerConnector );
-
- ServletHolder shRepo = new ServletHolder( RepoServlet.class );
- ServletContextHandler contextRepo = new ServletContextHandler();
-
- contextRepo.setContextPath( "/" );
- contextRepo.addServlet( shRepo, "/*" );
-
- repoServer.setHandler( contextRepo );
-
- repoServer.start();
- this.repoServerPort = repoServerConnector.getLocalPort();
-
- //redirect handler
-
- this.redirectServer = new Server( );
- ServerConnector redirectServerConnector = new ServerConnector( this.redirectServer, new HttpConnectionFactory());
- this.redirectServer.addConnector( redirectServerConnector );
-
- ServletHolder shRedirect = new ServletHolder( RedirectServlet.class );
- ServletContextHandler contextRedirect = new ServletContextHandler();
- contextRedirect.setAttribute( "redirectToPort", Integer.toString( this.repoServerPort ) );
-
- contextRedirect.setContextPath( "/" );
- contextRedirect.addServlet( shRedirect, "/*" );
-
- redirectServer.setHandler( contextRedirect );
- redirectServer.start();
- this.redirectPort = redirectServerConnector.getLocalPort();
- log.info( "redirect server port {}", redirectPort );
-
- }
-
- @After
- @Override
- public void tearDown()
- throws Exception
- {
- super.tearDown();
- if ( this.redirectServer != null )
- {
- this.redirectServer.stop();
- }
- }
-
- @Test
- public void downloadWithRemoteRedirect()
- throws Exception
- {
- RemoteRepository remoteRepository = getRemoteRepositoriesService().getRemoteRepository( "central" );
- remoteRepository.setUrl( "http://localhost:" + redirectPort );
- getRemoteRepositoriesService().updateRemoteRepository( remoteRepository );
-
- RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader );
-
- if ( !roleManagementService.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
- "internal" ) )
- {
- roleManagementService.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal" );
- }
-
- getUserService( authorizationHeader ).createGuestUser();
- roleManagementService.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, "guest" );
-
- roleManagementService.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal",
- "guest" );
-
- getUserService( authorizationHeader ).removeFromCache( "guest" );
-
- Path file = Paths.get( "target/junit-4.9.jar" );
- Files.deleteIfExists( file );
-
- HttpWagon httpWagon = new HttpWagon();
- httpWagon.connect( new Repository( "foo", "http://localhost:" + port ) );
-
- httpWagon.get( "repository/internal/junit/junit/4.9/junit-4.9.jar", file.toFile() );
-
- ZipFile zipFile = new ZipFile( file.toFile() );
- List<String> entries = getZipEntriesNames( zipFile );
- ZipEntry zipEntry = zipFile.getEntry( "org/junit/runners/JUnit4.class" );
- assertNotNull( "cannot find zipEntry org/junit/runners/JUnit4.class, entries: " + entries + ", content is: "
- + FileUtils.readFileToString( file.toFile(), Charset.forName( "UTF-8") ), zipEntry );
- zipFile.close();
- file.toFile().deleteOnExit();
- }
-
-
- public static class RedirectServlet
- extends HttpServlet
- {
- @Override
- protected void doGet( HttpServletRequest req, HttpServletResponse resp )
- throws ServletException, IOException
- {
-
- LoggerFactory.getLogger( getClass() ).info( "redirect servlet receive: {}", req.getRequestURI() );
- resp.setStatus( 302 );
- resp.getWriter().write( "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n"
- + "<title>302 Found</title>\n" + "</head><body>\n" + "<h1>Found</h1>\n"
- + "<p>The document has moved <a href=\"https://repo.maven.apache.org/maven2/junit/junit/4.9/junit-4.9.jar\">here</a>.</p>\n"
- + "</body></html>\n" + "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
- + "<html><head>\n" );
- resp.sendRedirect( "http://localhost:" + getServletContext().getAttribute( "redirectToPort" ) + "/maven2/"
- + req.getRequestURI() );
- }
- }
-
- public static class RepoServlet
- extends HttpServlet
- {
-
- private AtomicReference<Path> projectDir = new AtomicReference<>( );
-
- protected Path getProjectDirectory() {
- if ( projectDir.get()==null) {
- String propVal = System.getProperty("mvn.project.base.dir");
- Path newVal;
- if ( StringUtils.isEmpty(propVal)) {
- newVal = Paths.get("").toAbsolutePath();
- } else {
- newVal = Paths.get(propVal).toAbsolutePath();
- }
- projectDir.compareAndSet(null, newVal);
- }
- return projectDir.get();
- }
-
- @Override
- protected void doGet( HttpServletRequest req, HttpServletResponse resp )
- throws ServletException, IOException
- {
- Path jar = getProjectDirectory().resolve( "src/test/junit-4.9.jar" );
- Files.copy( jar, resp.getOutputStream() );
-
- }
- }
-
-
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.admin.model.beans.ProxyConnector;
-import org.apache.archiva.admin.model.beans.RemoteRepository;
-import org.apache.archiva.admin.model.beans.RepositoryGroup;
-import org.apache.archiva.maven.model.Artifact;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.rest.services.BaseSetup;
-import org.apache.archiva.rest.api.model.SearchRequest;
-import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
-import org.apache.archiva.rest.api.services.ProxyConnectorService;
-import org.apache.archiva.rest.api.services.RepositoriesService;
-import org.apache.archiva.rest.api.services.RepositoryGroupService;
-import org.apache.archiva.rest.api.services.SearchService;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public class DownloadMergedIndexNonDefaultPathTest
- extends AbstractDownloadTest
-{
-
- private static Path appServerBase;
- private Path indexDir;
-
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv3_" ).toAbsolutePath();
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- org.apache.commons.io.FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
- return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-merge-index-download.xml";
- }
-
- @Before
- public void init() throws IOException
- {
- indexDir = Files.createTempDirectory( "archiva-web-common-index" );
- }
-
- @After
- public void cleanup()
- throws Exception
- {
- super.tearDown();
- if ( Files.exists( indexDir ) )
- {
- org.apache.commons.io.FileUtils.deleteDirectory( indexDir.toFile() );
- }
- }
-
- @Test
- public void downloadMergedIndexWithNonDefaultPath()
- throws Exception
- {
-
- Path indexBaseDir = indexDir.resolve("remotedownloadtest");
- if (!Files.exists(indexBaseDir)) {
- Files.createDirectories( indexBaseDir );
- }
- String id = Long.toString( System.currentTimeMillis() );
- Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
- Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
- createdPaths.add( testRep );
-
- ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
- managedRepository.setId( id );
- managedRepository.setName( "name of " + id );
- managedRepository.setLocation( testRep.toString() );
- managedRepository.setIndexDirectory( indexBaseDir.resolve( "index-" + id ).toString() );
- managedRepository.setPackedIndexDirectory( indexBaseDir.resolve( "indexPacked-" + id ).toString() );
-
-
- ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
-
- if ( managedRepositoriesService.getManagedRepository( id ) != null )
- {
- managedRepositoriesService.deleteManagedRepository( id, false );
- }
-
- getManagedRepositoriesService().addManagedRepository( managedRepository );
-
- RepositoriesService repositoriesService = getRepositoriesService();
-
- repositoriesService.scanRepositoryNow( id, true );
-
- // wait a bit to ensure index is finished
- int timeout = 20000;
- while ( timeout > 0 && repositoriesService.getScanStatus( id ).isAlreadyScanning() )
- {
- Thread.sleep( 500 );
- timeout -= 500;
- }
-
- RepositoryGroupService repositoryGroupService = getRepositoryGroupService();
-
- String repoGroupId = "test-group";
-
- if ( repositoryGroupService.getRepositoryGroup( repoGroupId ) != null )
- {
- repositoryGroupService.deleteRepositoryGroup( repoGroupId );
- }
-
- RepositoryGroup repositoryGroup = new RepositoryGroup();
- repositoryGroup.setId( repoGroupId );
- String path = ".fooooo";
- repositoryGroup.setRepositories( Arrays.asList( id ) );
- repositoryGroup.setMergedIndexPath( path );
-
- repositoryGroupService.addRepositoryGroup( repositoryGroup );
-
-
-
- // create a repo with a remote on the one with index
- id = Long.toString( System.currentTimeMillis() );
- Path srcRep2 = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
- Path testRep2 = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep2.toFile( ), testRep2.toFile( ) );
- createdPaths.add( testRep2 );
-
- managedRepository = new ManagedRepository(Locale.getDefault());
- managedRepository.setId( id );
- managedRepository.setName( "name of " + id );
- managedRepository.setLocation( testRep2.toString() );
- managedRepository.setIndexDirectory( indexBaseDir.resolve( "index-" + id ).toString() );
- managedRepository.setPackedIndexDirectory( indexBaseDir.resolve( "indexpacked-" + id ).toString() );
-
- if ( managedRepositoriesService.getManagedRepository( id ) != null )
- {
- managedRepositoriesService.deleteManagedRepository( id, false );
- }
-
- getManagedRepositoriesService().addManagedRepository( managedRepository );
-
- String remoteId = Long.toString( System.currentTimeMillis() );
-
- RemoteRepository remoteRepository = new RemoteRepository(Locale.getDefault());
- remoteRepository.setId( remoteId );
- remoteRepository.setName( remoteId );
- remoteRepository.setDownloadRemoteIndex( true );
- remoteRepository.setUrl( "http://localhost:" + port + "/repository/test-group" );
- remoteRepository.setRemoteIndexUrl( "http://localhost:" + port + "/repository/test-group/" + path );
- remoteRepository.setUserName( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
- remoteRepository.setPassword( BaseSetup.getAdminPwd() );
-
- getRemoteRepositoriesService().addRemoteRepository( remoteRepository );
-
- ProxyConnectorService proxyConnectorService = getProxyConnectorService();
- ProxyConnector proxyConnector = new ProxyConnector();
- proxyConnector.setProxyId( "foo-bar2" );
- proxyConnector.setSourceRepoId( id );
- proxyConnector.setTargetRepoId( remoteId );
- proxyConnectorService.addProxyConnector( proxyConnector );
-
- repositoriesService.scheduleDownloadRemoteIndex( remoteId, true, true );
-
- // wait a bit
- /*
- timeout = 20000;
- while ( timeout > 0 )
- {
- Thread.sleep( 500 );
- timeout -= 500;
- }*/
- // wait the end
- while ( !repositoriesService.getRunningRemoteDownloadIds().getStrings().isEmpty() )
- {
- Thread.sleep( 500 );
- log.debug( "still running remote download" );
- }
-
- SearchService searchService = getSearchService();
-
- SearchRequest request = new SearchRequest();
- request.setRepositories( Arrays.asList( id ) );
- request.setGroupId( "org.apache.felix" );
-
- List<Artifact> artifacts = searchService.searchArtifacts( request );
- assertThat( artifacts ).isNotNull().isNotEmpty().hasSize( 1 );
-
- }
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.admin.model.beans.ProxyConnector;
-import org.apache.archiva.admin.model.beans.RemoteRepository;
-import org.apache.archiva.admin.model.beans.RepositoryGroup;
-import org.apache.archiva.maven.model.Artifact;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.rest.services.BaseSetup;
-import org.apache.archiva.rest.api.model.SearchRequest;
-import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
-import org.apache.archiva.rest.api.services.ProxyConnectorService;
-import org.apache.archiva.rest.api.services.RepositoriesService;
-import org.apache.archiva.rest.api.services.RepositoryGroupService;
-import org.apache.archiva.rest.api.services.SearchService;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public class DownloadMergedIndexTest
- extends AbstractDownloadTest
-{
-
- private static Path appServerBase;
- private Path indexDir;
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv4_" ).toAbsolutePath();
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
- return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-merge-index-download.xml";
- }
-
- @Before
- public void init() throws IOException
- {
- indexDir = Files.createTempDirectory( "archiva-web-common-index" );
- }
-
- @After
- public void cleanup()
- throws Exception
- {
- super.tearDown();
- if ( Files.exists( indexDir ) )
- {
- FileUtils.deleteDirectory( indexDir.toFile() );
- }
- }
-
-
- @Test
- public void downloadMergedIndex()
- throws Exception
- {
- String id = Long.toString( System.currentTimeMillis() );
- Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
- Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
- createdPaths.add( testRep );
-
-
- ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
- managedRepository.setId( id );
- managedRepository.setName( "name of " + id );
- managedRepository.setLocation( testRep.toString() );
- managedRepository.setIndexDirectory( indexDir.resolve( "index-" + id ).toString() );
-
- ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
-
- if ( managedRepositoriesService.getManagedRepository( id ) != null )
- {
- managedRepositoriesService.deleteManagedRepository( id, false );
- }
-
- getManagedRepositoriesService().addManagedRepository( managedRepository );
-
- RepositoriesService repositoriesService = getRepositoriesService();
-
- repositoriesService.scanRepositoryNow( id, true );
-
- // wait a bit to ensure index is finished
- int timeout = 20000;
- while ( timeout > 0 && repositoriesService.getScanStatus( id ).isAlreadyScanning() )
- {
- Thread.sleep( 500 );
- timeout -= 500;
- }
-
- RepositoryGroupService repositoryGroupService = getRepositoryGroupService();
-
- String repoGroupId = "test-group";
-
- if ( repositoryGroupService.getRepositoryGroup( repoGroupId ) != null )
- {
- repositoryGroupService.deleteRepositoryGroup( repoGroupId );
- }
-
- RepositoryGroup repositoryGroup = new RepositoryGroup();
- repositoryGroup.setId( repoGroupId );
- repositoryGroup.setRepositories( Arrays.asList( id ) );
-
- repositoryGroupService.addRepositoryGroup( repositoryGroup );
-
- // create a repo with a remote on the one with index
- id = Long.toString( System.currentTimeMillis() );
-
- Path srcRep2 = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
- Path testRep2 = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep2.toFile( ), testRep2.toFile( ) );
- createdPaths.add( testRep2 );
-
- managedRepository = new ManagedRepository(Locale.getDefault());
- managedRepository.setId( id );
- managedRepository.setName( "name of " + id );
- managedRepository.setLocation( testRep2.toString() );
- managedRepository.setIndexDirectory( indexDir.resolve( "index-" + id ).toString() );
-
- if ( managedRepositoriesService.getManagedRepository( id ) != null )
- {
- managedRepositoriesService.deleteManagedRepository( id, false );
- }
-
- getManagedRepositoriesService().addManagedRepository( managedRepository );
-
- RemoteRepository remoteRepository = new RemoteRepository(Locale.getDefault());
- remoteRepository.setId( "all-merged" );
- remoteRepository.setName( "all-merged" );
- remoteRepository.setDownloadRemoteIndex( true );
- remoteRepository.setUrl( "http://localhost:" + port + "/repository/test-group" );
- remoteRepository.setRemoteIndexUrl( "http://localhost:" + port + "/repository/test-group/.index" );
- remoteRepository.setUserName( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
- remoteRepository.setPassword( BaseSetup.getAdminPwd() );
-
- if ( getRemoteRepositoriesService().getRemoteRepository( remoteRepository.getId() ) != null )
- {
- getRemoteRepositoriesService().deleteRemoteRepository( remoteRepository.getId() );
- }
-
- getRemoteRepositoriesService().addRemoteRepository( remoteRepository );
-
- ProxyConnectorService proxyConnectorService = getProxyConnectorService();
- ProxyConnector proxyConnector = new ProxyConnector();
- proxyConnector.setProxyId( "foo-bar1" );
- proxyConnector.setSourceRepoId( id );
- proxyConnector.setTargetRepoId( "all-merged" );
- proxyConnectorService.addProxyConnector( proxyConnector );
-
- repositoriesService.scheduleDownloadRemoteIndex( "all-merged", true, true );
-
- // wait a bit
- timeout = 20000;
- while ( timeout > 0 )
- {
- Thread.sleep( 500 );
- timeout -= 500;
- }
-
- SearchService searchService = getSearchService();
-
- SearchRequest request = new SearchRequest();
- request.setRepositories( Arrays.asList( id ) );
- request.setGroupId( "org.apache.felix" );
-
- List<Artifact> artifacts = searchService.searchArtifacts( request );
- assertThat( artifacts ).isNotNull().isNotEmpty().hasSize( 1 );
-
- }
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.redback.rest.api.services.RoleManagementService;
-import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
-import org.apache.archiva.security.common.ArchivaRoleConstants;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.commons.io.FileUtils;
-import org.apache.maven.wagon.providers.http.HttpWagon;
-import org.apache.maven.wagon.repository.Repository;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Locale;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith( ArchivaBlockJUnit4ClassRunner.class )
-public class DownloadSnapshotTest
- extends AbstractDownloadTest
-{
- protected Logger log = LoggerFactory.getLogger( getClass() );
-
- private static Path appServerBase;
- private Path indexDir;
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv5_" ).toAbsolutePath();
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
- return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml";
- }
-
- @Before
- public void init() throws IOException
- {
- indexDir = Files.createTempDirectory( "archiva-web-common-index" );
- }
-
- @After
- public void cleanup()
- throws Exception
- {
- super.tearDown();
- if ( Files.exists( indexDir ) )
- {
- FileUtils.deleteDirectory( indexDir.toFile() );
- }
- }
-
-
- @Test
- public void downloadSNAPSHOT()
- throws Exception
- {
-
- String id = Long.toString( System.currentTimeMillis() );
- Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/snapshot-repo" );
- Path testRep = getBasedir( ).resolve( "target" ).resolve( "snapshot-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
- createdPaths.add( testRep );
-
- ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
- managedRepository.setId( id );
- managedRepository.setName( "name of " + id );
- managedRepository.setLocation( testRep.toString() );
- managedRepository.setIndexDirectory( indexDir.resolve( "index-" + id ).toString() );
- managedRepository.setPackedIndexDirectory( indexDir.resolve( "indexpacked-" + id ).toString() );
-
- ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
-
- if ( managedRepositoriesService.getManagedRepository( id ) != null )
- {
- managedRepositoriesService.deleteManagedRepository( id, false );
- }
-
- getManagedRepositoriesService().addManagedRepository( managedRepository );
-
- RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader );
-
- if ( !roleManagementService.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
- id ) )
- {
- roleManagementService.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id );
- }
-
- getUserService( authorizationHeader ).createGuestUser();
- roleManagementService.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, "guest" );
-
- roleManagementService.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id,
- "guest" );
-
- getUserService( authorizationHeader ).removeFromCache( "guest" );
-
- Path file = Paths.get( "target/archiva-model-1.4-M4-SNAPSHOT.jar" );
- Files.deleteIfExists(file);
-
- HttpWagon httpWagon = new HttpWagon();
- httpWagon.connect( new Repository( "foo", "http://localhost:" + port ) );
-
- httpWagon.get( "/repository/"+ id +"/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-SNAPSHOT.jar", file.toFile() );
-
- ZipFile zipFile = new ZipFile( file.toFile() );
- List<String> entries = getZipEntriesNames( zipFile );
- ZipEntry zipEntry = zipFile.getEntry( "org/apache/archiva/model/ArchivaArtifact.class" );
- assertNotNull( "cannot find zipEntry org/apache/archiva/model/ArchivaArtifact.class, entries: " + entries + ", content is: "
- + FileUtils.readFileToString( file.toFile(), Charset.forName( "UTF-8") ), zipEntry );
- zipFile.close();
- file.toFile().deleteOnExit();
-
-
-
- }
-
-}
+++ /dev/null
-package org.apache.archiva.remotedownload;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.RemoteRepository;
-import org.apache.archiva.rest.api.services.RemoteRepositoriesService;
-import org.apache.commons.io.FileUtils;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.eclipse.jetty.server.Handler;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.handler.DefaultHandler;
-import org.eclipse.jetty.server.handler.HandlerList;
-import org.eclipse.jetty.server.handler.ResourceHandler;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Locale;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author Olivier Lamy
- */
-public class RemoteRepositoryConnectivityCheckTest
- extends AbstractDownloadTest
-{
-
- private static Path appServerBase;
-
- @BeforeClass
- public static void setAppServerBase()
- throws IOException
- {
- previousAppServerBase = System.getProperty( "appserver.base" );
- appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv6_" ).toAbsolutePath( );
- System.setProperty( "appserver.base", appServerBase.toString( ) );
- }
-
- @AfterClass
- public static void resetAppServerBase()
- {
- if (Files.exists(appServerBase)) {
- FileUtils.deleteQuietly( appServerBase.toFile() );
- }
- System.setProperty( "appserver.base", previousAppServerBase );
- }
-
- @Override
- protected String getSpringConfigLocation()
- {
- System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
- return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml";
- }
-
- @Test
- public void checkRemoteConnectivity()
- throws Exception
- {
- String id = Long.toString( System.currentTimeMillis() );
-
- Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
- Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
- FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
- createdPaths.add( testRep );
-
-
- Server repoServer =
- buildStaticServer( testRep );
-
- ServerConnector serverConnector = new ServerConnector( repoServer, new HttpConnectionFactory());
- repoServer.addConnector( serverConnector );
- repoServer.start();
-
- RemoteRepositoriesService service = getRemoteRepositoriesService();
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
-
- try
- {
-
- int repoServerPort = serverConnector.getLocalPort();
-
- RemoteRepository repo = getRemoteRepository();
-
- repo.setUrl( "http://localhost:" + repoServerPort );
-
- service.addRemoteRepository( repo );
-
- assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isTrue();
- }
- finally
- {
- service.deleteRemoteRepository( "id-new" );
- repoServer.stop();
- }
- }
-
- @Test
- public void checkRemoteConnectivityEmptyRemote()
- throws Exception
- {
-
- Path tmpDir = Files.createTempDirectory( "test" );
- Server repoServer = buildStaticServer( tmpDir );
- ServerConnector serverConnector = new ServerConnector( repoServer, new HttpConnectionFactory());
- repoServer.addConnector( serverConnector );
- repoServer.start();
-
- RemoteRepositoriesService service = getRemoteRepositoriesService();
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
-
- try
- {
-
- int repoServerPort = serverConnector.getLocalPort();
-
- RemoteRepository repo = getRemoteRepository();
-
- repo.setUrl( "http://localhost:" + repoServerPort );
-
- service.addRemoteRepository( repo );
-
- assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isTrue();
- }
- finally
- {
- service.deleteRemoteRepository( "id-new" );
- org.apache.archiva.common.utils.FileUtils.deleteQuietly( tmpDir );
- repoServer.stop();
- }
- }
-
- @Test
- public void checkRemoteConnectivityFail()
- throws Exception
- {
-
- RemoteRepositoriesService service = getRemoteRepositoriesService();
-
- WebClient.client( service ).header( "Authorization", authorizationHeader );
-
- try
- {
-
- RemoteRepository repo = getRemoteRepository();
-
- repo.setUrl( "http://localhost:8956" );
-
- service.addRemoteRepository( repo );
-
- assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isFalse();
- }
- finally
- {
- service.deleteRemoteRepository( "id-new" );
-
- }
- }
-
- protected Server buildStaticServer( Path path )
- {
- Server repoServer = new Server( );
-
- ResourceHandler resourceHandler = new ResourceHandler();
- resourceHandler.setDirectoriesListed( true );
- resourceHandler.setWelcomeFiles( new String[]{ "index.html" } );
- resourceHandler.setResourceBase( path.toAbsolutePath().toString() );
-
- HandlerList handlers = new HandlerList();
- handlers.setHandlers( new Handler[]{ resourceHandler, new DefaultHandler() } );
- repoServer.setHandler( handlers );
-
- return repoServer;
- }
-
-
- RemoteRepository getRemoteRepository()
- {
- return new RemoteRepository( Locale.getDefault( ), "id-new", "new one", "http://foo.com", "default", "foo", "foopassword", 120,
- "cool repo" );
- }
-
-}
+++ /dev/null
-package org.apache.archiva.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- * UserRepositories stub used for testing.
- *
- *
- */
-public class UserRepositoriesStub
- implements UserRepositories
-{
- private List<String> repoIds = Collections.singletonList( "test-repo" );
-
- @Override
- public void createMissingRepositoryRoles( String repoId )
- throws ArchivaSecurityException
- {
- }
-
- @Override
- public List<String> getObservableRepositoryIds( String principal )
- throws ArchivaSecurityException
- {
- return repoIds;
- }
-
- public void setObservableRepositoryIds( List<String> repoIds )
- {
- this.repoIds = repoIds;
- }
-
- @Override
- public boolean isAuthorizedToUploadArtifacts( String principal, String repoId )
- throws ArchivaSecurityException
- {
- return true;
- }
-
- @Override
- public boolean isAuthorizedToDeleteArtifacts( String principal, String repoId )
- {
- return true;
- }
-
- @Override
- public List<String> getManagableRepositoryIds( String principal )
- throws ArchivaSecurityException
- {
- return null;
- }
-
- public List<String> getRepoIds()
- {
- return repoIds;
- }
-
- public void setRepoIds( List<String> repoIds )
- {
- this.repoIds = repoIds;
- }
-
- @Override
- public List<ManagedRepository> getAccessibleRepositories( String principal )
- throws ArchivaSecurityException, AccessDeniedException, PrincipalNotFoundException
- {
- return Collections.emptyList();
- }
-
- @Override
- public List<ManagedRepository> getManagableRepositories(String principal) throws ArchivaSecurityException, AccessDeniedException, PrincipalNotFoundException {
- return Collections.emptyList();
- }
-}
+++ /dev/null
-package org.apache.archiva.upload;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
-import org.apache.archiva.configuration.ArchivaConfiguration;
-import org.apache.archiva.redback.rest.services.AbstractRestServicesTest;
-import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
-import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
-import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
-import org.apache.archiva.web.api.FileUploadService;
-import org.apache.archiva.web.model.FileMetadata;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.SystemUtils;
-import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.jaxrs.ext.multipart.Attachment;
-import org.apache.cxf.jaxrs.ext.multipart.AttachmentBuilder;
-import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
-import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
-import org.apache.cxf.message.Message;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import javax.ws.rs.ClientErrorException;
-import java.io.IOException;
-import java.net.URLEncoder;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Collections;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith(ArchivaBlockJUnit4ClassRunner.class)
-public class UploadArtifactsTest
- extends AbstractRestServicesTest {
-
- private static String PREVIOUS_ARCHIVA_PATH;
- private AtomicReference<Path> projectDir = new AtomicReference<>( );
-
- @BeforeClass
- public static void initConfigurationPath()
- throws Exception
- {
- PREVIOUS_ARCHIVA_PATH = System.getProperty(ArchivaConfiguration.USER_CONFIG_PROPERTY);
- System.setProperty( ArchivaConfiguration.USER_CONFIG_PROPERTY,
- System.getProperty( "test.resources.path" ) + "/archiva.xml" );
- }
-
-
- @AfterClass
- public static void restoreConfigurationPath()
- throws Exception
- {
- System.setProperty( ArchivaConfiguration.USER_CONFIG_PROPERTY, PREVIOUS_ARCHIVA_PATH );
- }
- @Override
- protected String getSpringConfigLocation() {
- return "classpath*:META-INF/spring-context.xml,classpath:/spring-context-test-upload.xml";
- }
-
- protected Path getProjectDirectory() {
- if ( projectDir.get()==null) {
- String propVal = System.getProperty("mvn.project.base.dir");
- Path newVal;
- if (StringUtils.isEmpty(propVal)) {
- newVal = Paths.get("").toAbsolutePath();
- } else {
- newVal = Paths.get(propVal).toAbsolutePath();
- }
- projectDir.compareAndSet(null, newVal);
- }
- return projectDir.get();
- }
-
- @Override
- protected String getRestServicesPath() {
- return "restServices";
- }
-
- protected String getBaseUrl() {
- String baseUrlSysProps = System.getProperty("archiva.baseRestUrl");
- return StringUtils.isBlank(baseUrlSysProps) ? "http://localhost:" + getServerPort() : baseUrlSysProps;
- }
-
- private FileUploadService getUploadService() {
- FileUploadService service =
- JAXRSClientFactory.create(getBaseUrl() + "/" + getRestServicesPath() + "/archivaUiServices/",
- FileUploadService.class,
- Collections.singletonList(new JacksonJaxbJsonProvider()));
- log.debug("Service class {}", service.getClass().getName());
- WebClient.client(service).header("Authorization", authorizationHeader);
- WebClient.client(service).header("Referer", "http://localhost:" + getServerPort());
-
- WebClient.client(service).header("Referer", "http://localhost");
- WebClient.getConfig(service).getRequestContext().put(Message.MAINTAIN_SESSION, true);
- WebClient.getConfig(service).getRequestContext().put(Message.EXCEPTION_MESSAGE_CAUSE_ENABLED, true);
- WebClient.getConfig(service).getRequestContext().put(Message.FAULT_STACKTRACE_ENABLED, true);
- WebClient.getConfig(service).getRequestContext().put(Message.PROPOGATE_EXCEPTION, true);
- WebClient.getConfig(service).getRequestContext().put("org.apache.cxf.transport.no_io_exceptions", true);
-
- // WebClient.client( service ).
- return service;
- }
-
- @Test
- public void clearUploadedFiles()
- throws Exception {
- FileUploadService service = getUploadService();
- service.clearUploadedFiles();
- }
-
- @Test
- public void uploadFile() throws IOException, ArchivaRestServiceException {
- FileUploadService service = getUploadService();
- try {
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- } finally {
- service.clearUploadedFiles();
- }
- }
-
- @Test
- public void failUploadFileWithBadFileName() throws IOException, ArchivaRestServiceException {
- FileUploadService service = getUploadService();
- try {
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"/../TestFile.testext\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- try {
- service.post(body);
- fail("FileNames with path contents should not be allowed.");
- } catch (ClientErrorException e) {
- assertEquals(422, e.getResponse().getStatus());
- }
- } finally {
- service.clearUploadedFiles();
- }
- }
-
- @Test
- public void uploadAndDeleteFile() throws IOException, ArchivaRestServiceException {
- FileUploadService service = getUploadService();
- try {
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- service.deleteFile(file.getFileName().toString());
- } finally {
- service.clearUploadedFiles();
- }
- }
-
- @Test
- public void failUploadAndDeleteWrongFile() throws IOException, ArchivaRestServiceException {
- FileUploadService service = getUploadService();
- try {
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- assertFalse(service.deleteFile("file123" + file.getFileName().toString()));
- } finally {
- service.clearUploadedFiles();
- }
- }
-
- @Test
- public void failUploadAndDeleteFileInOtherDir() throws IOException, ArchivaRestServiceException {
- Path testFile = null;
- try {
- FileUploadService service = getUploadService();
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- Path targetDir = Paths.get("target/testDelete").toAbsolutePath();
- if (!Files.exists(targetDir)) Files.createDirectories(targetDir);
- Path tempDir = SystemUtils.getJavaIoTmpDir().toPath();
- testFile = Files.createTempFile(targetDir, "TestFile", ".txt");
- log.debug("Test file {}", testFile.toAbsolutePath());
- log.debug("Tmp dir {}", tempDir.toAbsolutePath());
- assertTrue(Files.exists(testFile));
- Path relativePath = tempDir.relativize(testFile.toAbsolutePath());
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- String relativePathEncoded = URLEncoder.encode("../target/" + relativePath.toString(), "UTF-8");
- log.debug("Trying to delete with path traversal: {}, {}", relativePath, relativePathEncoded);
- try {
- service.deleteFile(relativePathEncoded);
- } catch (ArchivaRestServiceException ex) {
- // Expected exception
- }
- assertTrue("File in another directory may not be deleted", Files.exists(testFile));
- } finally {
- if (testFile != null) {
- Files.deleteIfExists(testFile);
- }
- }
- }
-
- @Test
- public void failSaveFileWithBadParams() throws IOException, ArchivaRestServiceException {
- Path path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.jar");
- Files.deleteIfExists(path);
- FileUploadService service = getUploadService();
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
-
- Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.jar\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- assertTrue(service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "jar", true));
-
- fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"TestFile.FileExt\"; name=\"files[]\"")).build();
- body = new MultipartBody(fileAttachment);
- FileMetadata meta = service.post(body);
- log.debug("Metadata {}", meta.toString());
- try {
- service.save("internal", "org", URLEncoder.encode("../../../test", "UTF-8"), URLEncoder.encode("testSave", "UTF-8"), "4", true);
- fail("Error expected, if the content contains bad characters.");
- } catch (ClientErrorException e) {
- assertEquals(422, e.getResponse().getStatus());
- }
- assertFalse(Files.exists(Paths.get("target/test-testSave.4")));
- }
-
- @Test
- public void saveFile() throws IOException, ArchivaRestServiceException {
- log.debug("Starting saveFile()");
-
- Path path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.jar");
- log.debug("Jar exists: {}",Files.exists(path));
- Files.deleteIfExists(path);
- path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.pom");
- Files.deleteIfExists(path);
- FileUploadService service = getUploadService();
- service.clearUploadedFiles();
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- log.debug("Upload file exists: {}", Files.exists(file));
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.jar\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "jar", true);
- }
-
- @Test
- public void saveFileWithOtherExtension() throws IOException, ArchivaRestServiceException {
- log.debug("Starting saveFileWithOtherExtension()");
-
- Path path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.bin");
- log.debug("Jar exists: {}",Files.exists(path));
- Files.deleteIfExists(path);
- Path pomPath = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.pom");
- Files.deleteIfExists(pomPath);
- FileUploadService service = getUploadService();
- service.clearUploadedFiles();
- Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
- log.debug("Upload file exists: {}", Files.exists(file));
- final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.bin\"; name=\"files[]\"")).build();
- MultipartBody body = new MultipartBody(fileAttachment);
- service.post(body);
- assertTrue(service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "bin", false));
- assertTrue(Files.exists(path));
- }
-
-
-}
--- /dev/null
+package org.apache.archiva.web;/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import junit.framework.TestCase;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.LdapGroupMappingService;
+import org.apache.archiva.redback.rest.api.services.LoginService;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.apache.archiva.redback.rest.api.services.UserService;
+import org.apache.archiva.redback.rest.api.services.v2.AuthenticationService;
+import org.apache.archiva.redback.rest.services.BaseSetup;
+import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
+import org.apache.commons.lang3.SystemUtils;
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.transport.servlet.CXFServlet;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.server.session.SessionHandler;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.context.ContextLoaderListener;
+
+import javax.ws.rs.core.MediaType;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith(JUnit4.class)
+public abstract class AbstractRestServicesTest
+ extends TestCase
+{
+ protected Logger log = LoggerFactory.getLogger( getClass() );
+
+ private static AtomicReference<Server> server = new AtomicReference<>();
+ private static AtomicReference<ServerConnector> serverConnector = new AtomicReference<>();
+
+ public String authorizationHeader = getAdminAuthzHeader();
+
+ /**
+ * Returns the server that was started, or null if not initialized before.
+ * @return
+ */
+ public Server getServer() {
+ return this.server.get();
+ }
+
+ public int getServerPort() {
+ ServerConnector connector = serverConnector.get();
+ if (connector!=null) {
+ return connector.getLocalPort();
+ } else {
+ return 0;
+ }
+ }
+
+ JacksonJaxbJsonProvider getJsonProvider() {
+ JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider( );
+ ObjectMapper mapper = new ObjectMapper( );
+ mapper.registerModule( new JavaTimeModule( ) );
+ provider.setMapper( mapper );
+ return provider;
+ }
+
+ /**
+ * Returns true, if the server does exist and is running.
+ * @return true, if server does exist and is running.
+ */
+ public boolean isServerRunning() {
+ return this.server.get() != null && this.server.get().isRunning();
+ }
+
+ /**
+ * Returns the timeout in ms for rest requests. The timeout can be set by
+ * the system property <code>rest.test.timeout</code>.
+ * @return The timeout value in ms.
+ */
+ public long getTimeout()
+ {
+ return Long.getLong( "rest.test.timeout", 1000000 );
+ }
+
+ public static String encode( String uid, String password )
+ {
+ return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
+ }
+
+ public static String getAdminAuthzHeader()
+ {
+ return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, BaseSetup.getAdminPwd() );
+ }
+
+ protected String getSpringConfigLocation()
+ {
+ return "classpath*:spring-context.xml,classpath*:META-INF/spring-context.xml";
+ }
+
+
+ protected String getRestServicesPath()
+ {
+ return "restServices";
+ }
+
+ @Before
+ public void startServer()
+ throws Exception
+ {
+ log.info("Starting server");
+ log.info( "User config {}", System.getProperty( "archiva.user.configFileName" ) );
+ log.info( "Appserver base {}", System.getProperty( "appserver.base" ) );
+ Server myServer = new Server();
+ this.server.set(myServer);
+ this.serverConnector.set(new ServerConnector( myServer, new HttpConnectionFactory()));
+ myServer.addConnector(serverConnector.get());
+
+ ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
+ ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
+ context.setResourceBase( SystemUtils.JAVA_IO_TMPDIR );
+ context.setSessionHandler( new SessionHandler( ) );
+ context.addServlet( servletHolder, "/" + getRestServicesPath() + "/*" );
+ context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
+ context.addEventListener(new ContextLoaderListener());
+
+ getServer().setHandler( context );
+ getServer().start();
+
+ if (log.isDebugEnabled())
+ {
+ log.debug( "Jetty dump: {}", getServer().dump() );
+ }
+
+ log.info( "Started server on port {}", getServerPort() );
+
+ UserService userService = getUserService();
+
+ User adminUser = new User();
+ adminUser.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
+ adminUser.setPassword( BaseSetup.getAdminPwd() );
+ adminUser.setFullName( "the admin user" );
+ adminUser.setEmail( "toto@toto.fr" );
+ if( !userService.createAdminUser( adminUser ) ) {
+ log.info( "Could not create admin user." );
+ }
+
+ FakeCreateAdminService fakeCreateAdminService = getFakeCreateAdminService();
+ //assertTrue( res.booleanValue() );
+
+ }
+
+ protected FakeCreateAdminService getFakeCreateAdminService()
+ {
+ return JAXRSClientFactory.create(
+ "http://localhost:" + getServerPort()+ "/" + getRestServicesPath() + "/fakeCreateAdminService/",
+ FakeCreateAdminService.class, Collections.singletonList( getJsonProvider() ) );
+ }
+
+ @After
+ public void stopServer()
+ throws Exception
+ {
+ if ( getServer() != null )
+ {
+ log.info("Stopping server");
+ getServer().stop();
+ }
+ }
+
+ protected UserService getUserService()
+ {
+
+ return getUserService( null );
+ }
+
+ // START SNIPPET: get-user-service
+ protected UserService getUserService( String authzHeader )
+ {
+ UserService service =
+ JAXRSClientFactory.create( "http://localhost:" + getServerPort() + "/" + getRestServicesPath() + "/redbackServices/",
+ UserService.class, Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ // time out for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( getTimeout() );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ WebClient.client(service).header("Referer","http://localhost:"+getServerPort());
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+ // END SNIPPET: get-user-service
+
+ protected RoleManagementService getRoleManagementService( String authzHeader )
+ {
+ RoleManagementService service =
+ JAXRSClientFactory.create( "http://localhost:" + getServerPort() + "/" + getRestServicesPath() + "/redbackServices/",
+ RoleManagementService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( getTimeout() );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ WebClient.client(service).header("Referer","http://localhost:"+getServerPort());
+
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+ protected LoginService getLoginService( String authzHeader )
+ {
+ LoginService service =
+ JAXRSClientFactory.create( "http://localhost:" + getServerPort() + "/" + getRestServicesPath() + "/redbackServices/",
+ LoginService.class, Collections.singletonList( getJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( getTimeout() );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ WebClient.client(service).header("Referer","http://localhost:"+getServerPort());
+
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+ protected AuthenticationService getLoginServiceV2( String authzHeader )
+ {
+ AuthenticationService service =
+ JAXRSClientFactory.create( "http://localhost:" + getServerPort() + "/" + getRestServicesPath() + "/v2/redback/",
+ AuthenticationService.class, Collections.singletonList( getJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( getTimeout() );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ WebClient.client(service).header("Referer","http://localhost:"+getServerPort());
+
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+
+ protected LdapGroupMappingService getLdapGroupMappingService( String authzHeader )
+ {
+ LdapGroupMappingService service =
+ JAXRSClientFactory.create( "http://localhost:" + getServerPort() + "/" + getRestServicesPath() + "/redbackServices/",
+ LdapGroupMappingService.class,
+ Collections.singletonList( getJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( getTimeout() );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ WebClient.client(service).header("Referer","http://localhost:"+getServerPort());
+
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.web;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import org.apache.archiva.redback.rest.services.AbstractRestServicesTest;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.archiva.web.api.RuntimeInfoService;
+import org.apache.archiva.web.model.ApplicationRuntimeInfo;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public class RuntimeInfoServiceTest
+ extends AbstractRestServicesTest
+{
+
+ private static Path appServerBase;
+ private static String previousAppServerBase;
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrvrt_" );
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ @Before
+ public void startServer()
+ throws Exception
+ {
+ Path jcrDirectory = appServerBase.resolve( "jcr" );
+
+ if ( Files.exists(jcrDirectory) )
+ {
+ org.apache.archiva.common.utils.FileUtils.deleteDirectory( jcrDirectory );
+ }
+
+ super.startServer();
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ return "classpath*:META-INF/spring-context.xml,classpath:/spring-context-with-jcr.xml";
+ }
+
+ @Override
+ protected String getRestServicesPath()
+ {
+ return "restServices";
+ }
+
+ protected String getBaseUrl()
+ {
+ String baseUrlSysProps = System.getProperty( "archiva.baseRestUrl" );
+ return StringUtils.isBlank( baseUrlSysProps ) ? "http://localhost:" + getServerPort() : baseUrlSysProps;
+ }
+
+ @Test
+ public void runtimeInfoService()
+ throws Exception
+ {
+ RuntimeInfoService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaUiServices/",
+ RuntimeInfoService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client(service).header("Referer","http://localhost");
+ ApplicationRuntimeInfo applicationRuntimeInfo = service.getApplicationRuntimeInfo( "en" );
+
+ assertEquals( System.getProperty( "expectedVersion" ), applicationRuntimeInfo.getVersion() );
+ assertFalse( applicationRuntimeInfo.isJavascriptLog() );
+ assertTrue( applicationRuntimeInfo.isLogMissingI18n() );
+
+ }
+}
--- /dev/null
+package org.apache.archiva.web;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.metadata.repository.RepositorySessionFactory;
+import org.apache.archiva.metadata.repository.RepositorySessionFactoryBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Properties;
+
+/**
+ * @author Olivier Lamy
+ */
+public class TestRepositorySessionFactoryBean
+ extends RepositorySessionFactoryBean
+{
+
+ private Logger logger = LoggerFactory.getLogger( getClass() );
+
+ private String beanId;
+
+ public TestRepositorySessionFactoryBean( String beanId )
+ {
+ super( new Properties( ) );
+ this.beanId = beanId;
+ }
+
+ @Override
+ public Class<RepositorySessionFactory> getObjectType()
+ {
+ return RepositorySessionFactory.class;
+ }
+
+ @Override
+ protected RepositorySessionFactory createInstance()
+ throws Exception
+ {
+ RepositorySessionFactory repositorySessionFactory =
+ getBeanFactory().getBean( "repositorySessionFactory#" + this.beanId, RepositorySessionFactory.class );
+ logger.info( "create RepositorySessionFactory instance of {}", repositorySessionFactory.getClass().getName() );
+ if (!repositorySessionFactory.isOpen()) {
+ repositorySessionFactory.open();
+ }
+ return repositorySessionFactory;
+ }
+
+ @Override
+ public String getId()
+ {
+ return this.beanId;
+ }
+}
--- /dev/null
+package org.apache.archiva.web.mock.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.security.AccessDeniedException;
+import org.apache.archiva.security.ArchivaSecurityException;
+import org.apache.archiva.security.PrincipalNotFoundException;
+import org.apache.archiva.security.UserRepositories;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * UserRepositories stub used for testing.
+ *
+ *
+ */
+public class UserRepositoriesStub
+ implements UserRepositories
+{
+ private List<String> repoIds = Collections.singletonList( "test-repo" );
+
+ @Override
+ public void createMissingRepositoryRoles( String repoId )
+ throws ArchivaSecurityException
+ {
+ }
+
+ @Override
+ public List<String> getObservableRepositoryIds( String principal )
+ throws ArchivaSecurityException
+ {
+ return repoIds;
+ }
+
+ public void setObservableRepositoryIds( List<String> repoIds )
+ {
+ this.repoIds = repoIds;
+ }
+
+ @Override
+ public boolean isAuthorizedToUploadArtifacts( String principal, String repoId )
+ throws ArchivaSecurityException
+ {
+ return true;
+ }
+
+ @Override
+ public boolean isAuthorizedToDeleteArtifacts( String principal, String repoId )
+ {
+ return true;
+ }
+
+ @Override
+ public List<String> getManagableRepositoryIds( String principal )
+ throws ArchivaSecurityException
+ {
+ return null;
+ }
+
+ public List<String> getRepoIds()
+ {
+ return repoIds;
+ }
+
+ public void setRepoIds( List<String> repoIds )
+ {
+ this.repoIds = repoIds;
+ }
+
+ @Override
+ public List<ManagedRepository> getAccessibleRepositories( String principal )
+ throws ArchivaSecurityException, AccessDeniedException, PrincipalNotFoundException
+ {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<ManagedRepository> getManagableRepositories(String principal) throws ArchivaSecurityException, AccessDeniedException, PrincipalNotFoundException {
+ return Collections.emptyList();
+ }
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import junit.framework.TestCase;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.apache.archiva.redback.rest.api.services.UserService;
+import org.apache.archiva.redback.rest.services.BaseSetup;
+import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
+import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
+import org.apache.archiva.rest.api.services.ProxyConnectorService;
+import org.apache.archiva.rest.api.services.RemoteRepositoriesService;
+import org.apache.archiva.rest.api.services.RepositoriesService;
+import org.apache.archiva.rest.api.services.RepositoryGroupService;
+import org.apache.archiva.rest.api.services.SearchService;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.archiva.webdav.RepositoryServlet;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.SystemUtils;
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.transport.servlet.CXFServlet;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.server.session.SessionHandler;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.context.ContextLoaderListener;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public abstract class AbstractDownloadTest
+ extends TestCase
+{
+
+ AtomicReference<Path> projectDir = new AtomicReference<>( );
+ AtomicReference<Path> basePath = new AtomicReference<>( );
+
+ protected List<Path> createdPaths = new ArrayList<>( );
+
+ protected final Logger log = LoggerFactory.getLogger( getClass() );
+
+ protected static String previousAppServerBase;
+
+ public String authorizationHeader = getAdminAuthzHeader();
+
+ public Server server = null;
+
+ ServerConnector serverConnector;
+
+ public int port;
+
+ protected Path getProjectDirectory() {
+ if ( projectDir.get()==null) {
+ String propVal = System.getProperty("mvn.project.base.dir");
+ Path newVal;
+ if (StringUtils.isEmpty(propVal)) {
+ newVal = Paths.get("").toAbsolutePath();
+ } else {
+ newVal = Paths.get(propVal).toAbsolutePath();
+ }
+ projectDir.compareAndSet(null, newVal);
+ }
+ return projectDir.get();
+ }
+
+ public Path getBasedir()
+ {
+ if (basePath.get()==null) {
+ String baseDir = System.getProperty( "basedir" );
+ final Path baseDirPath;
+ if (StringUtils.isNotEmpty( baseDir )) {
+ baseDirPath = Paths.get( baseDir );
+ } else {
+ baseDirPath = getProjectDirectory( );
+ }
+ basePath.compareAndSet( null, baseDirPath );
+ }
+ return basePath.get( );
+ }
+
+
+
+ public static String encode( String uid, String password )
+ {
+ return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
+ }
+
+ public static String getAdminAuthzHeader()
+ {
+ String adminPwdSysProps = System.getProperty( "rest.admin.pwd" );
+ if ( StringUtils.isBlank( adminPwdSysProps ) )
+ {
+ return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, BaseSetup.getAdminPwd() );
+ }
+ return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminPwdSysProps );
+ }
+
+
+ protected abstract String getSpringConfigLocation();
+
+
+ protected String getRestServicesPath()
+ {
+ return "restServices";
+ }
+
+
+ @Before
+ public void startServer()
+ throws Exception
+ {
+
+ System.setProperty( "redback.admin.creation.file", "target/auto-admin-creation.properties" );
+
+ server = new Server();
+ serverConnector = new ServerConnector( server, new HttpConnectionFactory() );
+ server.addConnector( serverConnector );
+
+ ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
+ ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS );
+ context.setResourceBase( SystemUtils.JAVA_IO_TMPDIR );
+ context.setSessionHandler( new SessionHandler() );
+ context.addServlet( servletHolder, "/" + getRestServicesPath() + "/*" );
+ context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
+ context.addEventListener( new ContextLoaderListener() );
+
+ ServletHolder servletHolderRepo = new ServletHolder( new RepositoryServlet() );
+ context.addServlet( servletHolderRepo, "/repository/*" );
+
+ server.setHandler( context );
+ server.start();
+ port = serverConnector.getLocalPort();
+ log.info( "start server on port {}", this.port );
+
+ User user = new User();
+ user.setEmail( "toto@toto.fr" );
+ user.setFullName( "the root user" );
+ user.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
+ user.setPassword( BaseSetup.getAdminPwd() );
+
+ getUserService( null ).createAdminUser( user );
+
+
+ }
+
+
+ @After
+ @Override
+ public void tearDown()
+ throws Exception
+ {
+
+ for(Path dir : createdPaths) {
+ if ( Files.exists( dir)) {
+ FileUtils.deleteQuietly( dir.toFile( ) );
+ }
+ }
+ createdPaths.clear();
+
+ System.clearProperty( "redback.admin.creation.file" );
+ super.tearDown();
+ if ( this.server != null )
+ {
+ this.server.stop();
+ }
+ }
+
+
+ protected ProxyConnectorService getProxyConnectorService()
+ {
+ ProxyConnectorService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
+ ProxyConnectorService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
+ return service;
+ }
+
+ protected RemoteRepositoriesService getRemoteRepositoriesService()
+ {
+ RemoteRepositoriesService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
+ RemoteRepositoriesService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
+ return service;
+ }
+
+ protected ManagedRepositoriesService getManagedRepositoriesService()
+ {
+ ManagedRepositoriesService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
+ ManagedRepositoriesService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
+ return service;
+ }
+
+
+ protected RepositoryGroupService getRepositoryGroupService()
+ {
+ RepositoryGroupService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
+ RepositoryGroupService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
+ return service;
+ }
+
+ protected RepositoriesService getRepositoriesService()
+ {
+ RepositoriesService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
+ RepositoriesService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
+ return service;
+ }
+
+ protected SearchService getSearchService()
+ {
+ SearchService service =
+ JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
+ SearchService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
+ return service;
+ }
+
+ protected String getBaseUrl()
+ {
+ String baseUrlSysProps = System.getProperty( "archiva.baseRestUrl" );
+ return StringUtils.isBlank( baseUrlSysProps ) ? "http://localhost:" + port : baseUrlSysProps;
+ }
+
+
+ protected RoleManagementService getRoleManagementService( String authzHeader )
+ {
+ RoleManagementService service =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
+ RoleManagementService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 3000000L );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ return service;
+ }
+
+ protected UserService getUserService( String authzHeader )
+ {
+ UserService service =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
+ UserService.class, Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( service ).header( "Referer", "http://localhost:" + port );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 3000000L );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ return service;
+ }
+
+ protected FakeCreateAdminService getFakeCreateAdminService()
+ {
+ return JAXRSClientFactory.create(
+ "http://localhost:" + port + "/" + getRestServicesPath() + "/fakeCreateAdminService/",
+ FakeCreateAdminService.class );
+ }
+
+
+ protected List<String> getZipEntriesNames( ZipFile zipFile )
+ {
+ try
+ {
+ List<String> entriesNames = new ArrayList<>();
+ Enumeration<? extends ZipEntry> entries = zipFile.entries();
+ while ( entries.hasMoreElements() )
+ {
+ entriesNames.add( entries.nextElement().getName() );
+ }
+ return entriesNames;
+ }
+ catch ( Throwable e )
+ {
+ log.info( "fail to get zipEntries {}", e.getMessage(), e );
+ }
+ return Collections.emptyList();
+ }
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
+import org.apache.archiva.rest.api.services.RepositoriesService;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.commons.io.FileUtils;
+import org.assertj.core.api.Assertions;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.ws.rs.RedirectionException;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Locale;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public class DownloadArtifactFromQueryTest
+ extends AbstractDownloadTest
+{
+
+ private static Path appServerBase;
+
+ private Path indexDir;
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv1_" ).toAbsolutePath();
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ System.out.println( "Appserver base: " + System.getProperty( "appserver.base" ) );
+ return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-merge-index-download.xml";
+ }
+
+ @Before
+ public void init() throws IOException
+ {
+ indexDir = Files.createTempDirectory( "archiva-web-common-index" );
+ }
+
+ @After
+ public void cleanup()
+ throws Exception
+ {
+ super.tearDown();
+ if ( Files.exists( indexDir ) )
+ {
+ FileUtils.deleteDirectory( indexDir.toFile() );
+ }
+ }
+
+
+ protected String createAndScanRepo()
+ throws Exception
+ {
+
+ String id = Long.toString( System.currentTimeMillis() );
+ Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
+ Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
+ createdPaths.add( testRep );
+
+
+ ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
+ managedRepository.setId( id );
+ managedRepository.setName( "name of " + id );
+ managedRepository.setLocation( testRep.toString() );
+ managedRepository.setIndexDirectory( indexDir.resolve( "index-"+id ).toString());
+ managedRepository.setPackedIndexDirectory( indexDir.resolve( "indexpacked-"+id ).toString());
+
+ ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
+
+ if ( managedRepositoriesService.getManagedRepository( id ) != null )
+ {
+ managedRepositoriesService.deleteManagedRepository( id, false );
+ }
+
+ getManagedRepositoriesService().addManagedRepository( managedRepository );
+
+ RepositoriesService repositoriesService = getRepositoriesService();
+
+ repositoriesService.scanRepositoryNow( id, true );
+
+ // wait a bit to ensure index is finished
+ int timeout = 20000;
+ while ( timeout > 0 && repositoriesService.getScanStatus( id ).isAlreadyScanning() )
+ {
+ Thread.sleep( 500 );
+ timeout -= 500;
+ }
+
+ return id;
+
+ }
+
+ @Test( expected = RedirectionException.class )
+ public void downloadFixedVersion()
+ throws Exception
+ {
+
+ String id = createAndScanRepo();
+
+ try
+ {
+ Response response =
+ getSearchService().redirectToArtifactFile( null, "org.apache.archiva", "archiva-test", "1.0", null,
+ null );
+
+ }
+ catch ( RedirectionException e )
+ {
+ Assertions.assertThat( e.getLocation().compareTo( new URI( "http://localhost:" + port + "/repository/" + id
+ + "/org/apache/archiva/archiva-test/1.0/archiva-test-1.0.jar" ) ) ).isEqualTo(
+ 0 );
+ throw e;
+ }
+ finally
+ {
+ getManagedRepositoriesService().deleteManagedRepository( id, false );
+ }
+
+ }
+
+
+ @Test( expected = RedirectionException.class )
+ public void downloadLatestVersion()
+ throws Exception
+ {
+ String id = createAndScanRepo();
+
+ try
+ {
+ Response response =
+ getSearchService().redirectToArtifactFile( null, "org.apache.archiva", "archiva-test", "LATEST", null,
+ null );
+
+ }
+ catch ( RedirectionException e )
+ {
+ Assertions.assertThat( e.getLocation().compareTo( new URI( "http://localhost:" + port + "/repository/" + id
+ + "/org/apache/archiva/archiva-test/2.0/archiva-test-2.0.jar" ) ) ).isEqualTo(
+ 0 );
+ throw e;
+ }
+ finally
+ {
+ getManagedRepositoriesService().deleteManagedRepository( id, false );
+ }
+
+ }
+
+ @Test
+ public void download_no_content()
+ throws Exception
+ {
+ String id = createAndScanRepo();
+
+ try
+ {
+ Response response =
+ getSearchService().redirectToArtifactFile( null, "org.apache.archiva.beer", "archiva-wine", "LATEST",
+ null, null );
+
+ Assert.assertEquals( Response.Status.NO_CONTENT.getStatusCode(), response.getStatus() );
+
+
+ }
+ finally
+ {
+ getManagedRepositoriesService().deleteManagedRepository( id, false );
+ }
+
+ }
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.RemoteRepository;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.apache.archiva.security.common.ArchivaRoleConstants;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.maven.wagon.providers.http.HttpWagon;
+import org.apache.maven.wagon.repository.Repository;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public class DownloadArtifactsTest
+ extends AbstractDownloadTest
+{
+
+ protected Logger log = LoggerFactory.getLogger( DownloadArtifactsTest.class );
+
+ public Server redirectServer = null;
+
+ public int redirectPort;
+
+ public Server repoServer = null;
+
+ public int repoServerPort;
+
+ private static Path appServerBase;
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ System.out.println( "Setting appserver base" );
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv2_" ).toAbsolutePath( );
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
+ return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml";
+ }
+
+ @Override
+
+ @Before
+ public void startServer()
+ throws Exception
+ {
+ super.startServer();
+
+ // repo handler
+
+ this.repoServer = new Server( );
+ ServerConnector repoServerConnector = new ServerConnector( this.repoServer, new HttpConnectionFactory());
+ this.repoServer.addConnector( repoServerConnector );
+
+ ServletHolder shRepo = new ServletHolder( RepoServlet.class );
+ ServletContextHandler contextRepo = new ServletContextHandler();
+
+ contextRepo.setContextPath( "/" );
+ contextRepo.addServlet( shRepo, "/*" );
+
+ repoServer.setHandler( contextRepo );
+
+ repoServer.start();
+ this.repoServerPort = repoServerConnector.getLocalPort();
+
+ //redirect handler
+
+ this.redirectServer = new Server( );
+ ServerConnector redirectServerConnector = new ServerConnector( this.redirectServer, new HttpConnectionFactory());
+ this.redirectServer.addConnector( redirectServerConnector );
+
+ ServletHolder shRedirect = new ServletHolder( RedirectServlet.class );
+ ServletContextHandler contextRedirect = new ServletContextHandler();
+ contextRedirect.setAttribute( "redirectToPort", Integer.toString( this.repoServerPort ) );
+
+ contextRedirect.setContextPath( "/" );
+ contextRedirect.addServlet( shRedirect, "/*" );
+
+ redirectServer.setHandler( contextRedirect );
+ redirectServer.start();
+ this.redirectPort = redirectServerConnector.getLocalPort();
+ log.info( "redirect server port {}", redirectPort );
+
+ }
+
+ @After
+ @Override
+ public void tearDown()
+ throws Exception
+ {
+ super.tearDown();
+ if ( this.redirectServer != null )
+ {
+ this.redirectServer.stop();
+ }
+ }
+
+ @Test
+ public void downloadWithRemoteRedirect()
+ throws Exception
+ {
+ RemoteRepository remoteRepository = getRemoteRepositoriesService().getRemoteRepository( "central" );
+ remoteRepository.setUrl( "http://localhost:" + redirectPort );
+ getRemoteRepositoriesService().updateRemoteRepository( remoteRepository );
+
+ RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader );
+
+ if ( !roleManagementService.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
+ "internal" ) )
+ {
+ roleManagementService.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal" );
+ }
+
+ getUserService( authorizationHeader ).createGuestUser();
+ roleManagementService.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, "guest" );
+
+ roleManagementService.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal",
+ "guest" );
+
+ getUserService( authorizationHeader ).removeFromCache( "guest" );
+
+ Path file = Paths.get( "target/junit-4.9.jar" );
+ Files.deleteIfExists( file );
+
+ HttpWagon httpWagon = new HttpWagon();
+ httpWagon.connect( new Repository( "foo", "http://localhost:" + port ) );
+
+ httpWagon.get( "repository/internal/junit/junit/4.9/junit-4.9.jar", file.toFile() );
+
+ ZipFile zipFile = new ZipFile( file.toFile() );
+ List<String> entries = getZipEntriesNames( zipFile );
+ ZipEntry zipEntry = zipFile.getEntry( "org/junit/runners/JUnit4.class" );
+ assertNotNull( "cannot find zipEntry org/junit/runners/JUnit4.class, entries: " + entries + ", content is: "
+ + FileUtils.readFileToString( file.toFile(), Charset.forName( "UTF-8") ), zipEntry );
+ zipFile.close();
+ file.toFile().deleteOnExit();
+ }
+
+
+ public static class RedirectServlet
+ extends HttpServlet
+ {
+ @Override
+ protected void doGet( HttpServletRequest req, HttpServletResponse resp )
+ throws ServletException, IOException
+ {
+
+ LoggerFactory.getLogger( getClass() ).info( "redirect servlet receive: {}", req.getRequestURI() );
+ resp.setStatus( 302 );
+ resp.getWriter().write( "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n"
+ + "<title>302 Found</title>\n" + "</head><body>\n" + "<h1>Found</h1>\n"
+ + "<p>The document has moved <a href=\"https://repo.maven.apache.org/maven2/junit/junit/4.9/junit-4.9.jar\">here</a>.</p>\n"
+ + "</body></html>\n" + "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
+ + "<html><head>\n" );
+ resp.sendRedirect( "http://localhost:" + getServletContext().getAttribute( "redirectToPort" ) + "/maven2/"
+ + req.getRequestURI() );
+ }
+ }
+
+ public static class RepoServlet
+ extends HttpServlet
+ {
+
+ private AtomicReference<Path> projectDir = new AtomicReference<>( );
+
+ protected Path getProjectDirectory() {
+ if ( projectDir.get()==null) {
+ String propVal = System.getProperty("mvn.project.base.dir");
+ Path newVal;
+ if ( StringUtils.isEmpty(propVal)) {
+ newVal = Paths.get("").toAbsolutePath();
+ } else {
+ newVal = Paths.get(propVal).toAbsolutePath();
+ }
+ projectDir.compareAndSet(null, newVal);
+ }
+ return projectDir.get();
+ }
+
+ @Override
+ protected void doGet( HttpServletRequest req, HttpServletResponse resp )
+ throws ServletException, IOException
+ {
+ Path jar = getProjectDirectory().resolve( "src/test/junit-4.9.jar" );
+ Files.copy( jar, resp.getOutputStream() );
+
+ }
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.admin.model.beans.ProxyConnector;
+import org.apache.archiva.admin.model.beans.RemoteRepository;
+import org.apache.archiva.admin.model.beans.RepositoryGroup;
+import org.apache.archiva.maven.model.Artifact;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.services.BaseSetup;
+import org.apache.archiva.rest.api.model.SearchRequest;
+import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
+import org.apache.archiva.rest.api.services.ProxyConnectorService;
+import org.apache.archiva.rest.api.services.RepositoriesService;
+import org.apache.archiva.rest.api.services.RepositoryGroupService;
+import org.apache.archiva.rest.api.services.SearchService;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.commons.io.FileUtils;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public class DownloadMergedIndexNonDefaultPathTest
+ extends AbstractDownloadTest
+{
+
+ private static Path appServerBase;
+ private Path indexDir;
+
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv3_" ).toAbsolutePath();
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ org.apache.commons.io.FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
+ return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-merge-index-download.xml";
+ }
+
+ @Before
+ public void init() throws IOException
+ {
+ indexDir = Files.createTempDirectory( "archiva-web-common-index" );
+ }
+
+ @After
+ public void cleanup()
+ throws Exception
+ {
+ super.tearDown();
+ if ( Files.exists( indexDir ) )
+ {
+ org.apache.commons.io.FileUtils.deleteDirectory( indexDir.toFile() );
+ }
+ }
+
+ @Test
+ public void downloadMergedIndexWithNonDefaultPath()
+ throws Exception
+ {
+
+ Path indexBaseDir = indexDir.resolve("remotedownloadtest");
+ if (!Files.exists(indexBaseDir)) {
+ Files.createDirectories( indexBaseDir );
+ }
+ String id = Long.toString( System.currentTimeMillis() );
+ Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
+ Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
+ createdPaths.add( testRep );
+
+ ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
+ managedRepository.setId( id );
+ managedRepository.setName( "name of " + id );
+ managedRepository.setLocation( testRep.toString() );
+ managedRepository.setIndexDirectory( indexBaseDir.resolve( "index-" + id ).toString() );
+ managedRepository.setPackedIndexDirectory( indexBaseDir.resolve( "indexPacked-" + id ).toString() );
+
+
+ ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
+
+ if ( managedRepositoriesService.getManagedRepository( id ) != null )
+ {
+ managedRepositoriesService.deleteManagedRepository( id, false );
+ }
+
+ getManagedRepositoriesService().addManagedRepository( managedRepository );
+
+ RepositoriesService repositoriesService = getRepositoriesService();
+
+ repositoriesService.scanRepositoryNow( id, true );
+
+ // wait a bit to ensure index is finished
+ int timeout = 20000;
+ while ( timeout > 0 && repositoriesService.getScanStatus( id ).isAlreadyScanning() )
+ {
+ Thread.sleep( 500 );
+ timeout -= 500;
+ }
+
+ RepositoryGroupService repositoryGroupService = getRepositoryGroupService();
+
+ String repoGroupId = "test-group";
+
+ if ( repositoryGroupService.getRepositoryGroup( repoGroupId ) != null )
+ {
+ repositoryGroupService.deleteRepositoryGroup( repoGroupId );
+ }
+
+ RepositoryGroup repositoryGroup = new RepositoryGroup();
+ repositoryGroup.setId( repoGroupId );
+ String path = ".fooooo";
+ repositoryGroup.setRepositories( Arrays.asList( id ) );
+ repositoryGroup.setMergedIndexPath( path );
+
+ repositoryGroupService.addRepositoryGroup( repositoryGroup );
+
+
+
+ // create a repo with a remote on the one with index
+ id = Long.toString( System.currentTimeMillis() );
+ Path srcRep2 = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
+ Path testRep2 = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep2.toFile( ), testRep2.toFile( ) );
+ createdPaths.add( testRep2 );
+
+ managedRepository = new ManagedRepository(Locale.getDefault());
+ managedRepository.setId( id );
+ managedRepository.setName( "name of " + id );
+ managedRepository.setLocation( testRep2.toString() );
+ managedRepository.setIndexDirectory( indexBaseDir.resolve( "index-" + id ).toString() );
+ managedRepository.setPackedIndexDirectory( indexBaseDir.resolve( "indexpacked-" + id ).toString() );
+
+ if ( managedRepositoriesService.getManagedRepository( id ) != null )
+ {
+ managedRepositoriesService.deleteManagedRepository( id, false );
+ }
+
+ getManagedRepositoriesService().addManagedRepository( managedRepository );
+
+ String remoteId = Long.toString( System.currentTimeMillis() );
+
+ RemoteRepository remoteRepository = new RemoteRepository(Locale.getDefault());
+ remoteRepository.setId( remoteId );
+ remoteRepository.setName( remoteId );
+ remoteRepository.setDownloadRemoteIndex( true );
+ remoteRepository.setUrl( "http://localhost:" + port + "/repository/test-group" );
+ remoteRepository.setRemoteIndexUrl( "http://localhost:" + port + "/repository/test-group/" + path );
+ remoteRepository.setUserName( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
+ remoteRepository.setPassword( BaseSetup.getAdminPwd() );
+
+ getRemoteRepositoriesService().addRemoteRepository( remoteRepository );
+
+ ProxyConnectorService proxyConnectorService = getProxyConnectorService();
+ ProxyConnector proxyConnector = new ProxyConnector();
+ proxyConnector.setProxyId( "foo-bar2" );
+ proxyConnector.setSourceRepoId( id );
+ proxyConnector.setTargetRepoId( remoteId );
+ proxyConnectorService.addProxyConnector( proxyConnector );
+
+ repositoriesService.scheduleDownloadRemoteIndex( remoteId, true, true );
+
+ // wait a bit
+ /*
+ timeout = 20000;
+ while ( timeout > 0 )
+ {
+ Thread.sleep( 500 );
+ timeout -= 500;
+ }*/
+ // wait the end
+ while ( !repositoriesService.getRunningRemoteDownloadIds().getStrings().isEmpty() )
+ {
+ Thread.sleep( 500 );
+ log.debug( "still running remote download" );
+ }
+
+ SearchService searchService = getSearchService();
+
+ SearchRequest request = new SearchRequest();
+ request.setRepositories( Arrays.asList( id ) );
+ request.setGroupId( "org.apache.felix" );
+
+ List<Artifact> artifacts = searchService.searchArtifacts( request );
+ assertThat( artifacts ).isNotNull().isNotEmpty().hasSize( 1 );
+
+ }
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.admin.model.beans.ProxyConnector;
+import org.apache.archiva.admin.model.beans.RemoteRepository;
+import org.apache.archiva.admin.model.beans.RepositoryGroup;
+import org.apache.archiva.maven.model.Artifact;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.services.BaseSetup;
+import org.apache.archiva.rest.api.model.SearchRequest;
+import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
+import org.apache.archiva.rest.api.services.ProxyConnectorService;
+import org.apache.archiva.rest.api.services.RepositoriesService;
+import org.apache.archiva.rest.api.services.RepositoryGroupService;
+import org.apache.archiva.rest.api.services.SearchService;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.commons.io.FileUtils;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public class DownloadMergedIndexTest
+ extends AbstractDownloadTest
+{
+
+ private static Path appServerBase;
+ private Path indexDir;
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv4_" ).toAbsolutePath();
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
+ return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-merge-index-download.xml";
+ }
+
+ @Before
+ public void init() throws IOException
+ {
+ indexDir = Files.createTempDirectory( "archiva-web-common-index" );
+ }
+
+ @After
+ public void cleanup()
+ throws Exception
+ {
+ super.tearDown();
+ if ( Files.exists( indexDir ) )
+ {
+ FileUtils.deleteDirectory( indexDir.toFile() );
+ }
+ }
+
+
+ @Test
+ public void downloadMergedIndex()
+ throws Exception
+ {
+ String id = Long.toString( System.currentTimeMillis() );
+ Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
+ Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
+ createdPaths.add( testRep );
+
+
+ ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
+ managedRepository.setId( id );
+ managedRepository.setName( "name of " + id );
+ managedRepository.setLocation( testRep.toString() );
+ managedRepository.setIndexDirectory( indexDir.resolve( "index-" + id ).toString() );
+
+ ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
+
+ if ( managedRepositoriesService.getManagedRepository( id ) != null )
+ {
+ managedRepositoriesService.deleteManagedRepository( id, false );
+ }
+
+ getManagedRepositoriesService().addManagedRepository( managedRepository );
+
+ RepositoriesService repositoriesService = getRepositoriesService();
+
+ repositoriesService.scanRepositoryNow( id, true );
+
+ // wait a bit to ensure index is finished
+ int timeout = 20000;
+ while ( timeout > 0 && repositoriesService.getScanStatus( id ).isAlreadyScanning() )
+ {
+ Thread.sleep( 500 );
+ timeout -= 500;
+ }
+
+ RepositoryGroupService repositoryGroupService = getRepositoryGroupService();
+
+ String repoGroupId = "test-group";
+
+ if ( repositoryGroupService.getRepositoryGroup( repoGroupId ) != null )
+ {
+ repositoryGroupService.deleteRepositoryGroup( repoGroupId );
+ }
+
+ RepositoryGroup repositoryGroup = new RepositoryGroup();
+ repositoryGroup.setId( repoGroupId );
+ repositoryGroup.setRepositories( Arrays.asList( id ) );
+
+ repositoryGroupService.addRepositoryGroup( repositoryGroup );
+
+ // create a repo with a remote on the one with index
+ id = Long.toString( System.currentTimeMillis() );
+
+ Path srcRep2 = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
+ Path testRep2 = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep2.toFile( ), testRep2.toFile( ) );
+ createdPaths.add( testRep2 );
+
+ managedRepository = new ManagedRepository(Locale.getDefault());
+ managedRepository.setId( id );
+ managedRepository.setName( "name of " + id );
+ managedRepository.setLocation( testRep2.toString() );
+ managedRepository.setIndexDirectory( indexDir.resolve( "index-" + id ).toString() );
+
+ if ( managedRepositoriesService.getManagedRepository( id ) != null )
+ {
+ managedRepositoriesService.deleteManagedRepository( id, false );
+ }
+
+ getManagedRepositoriesService().addManagedRepository( managedRepository );
+
+ RemoteRepository remoteRepository = new RemoteRepository(Locale.getDefault());
+ remoteRepository.setId( "all-merged" );
+ remoteRepository.setName( "all-merged" );
+ remoteRepository.setDownloadRemoteIndex( true );
+ remoteRepository.setUrl( "http://localhost:" + port + "/repository/test-group" );
+ remoteRepository.setRemoteIndexUrl( "http://localhost:" + port + "/repository/test-group/.index" );
+ remoteRepository.setUserName( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
+ remoteRepository.setPassword( BaseSetup.getAdminPwd() );
+
+ if ( getRemoteRepositoriesService().getRemoteRepository( remoteRepository.getId() ) != null )
+ {
+ getRemoteRepositoriesService().deleteRemoteRepository( remoteRepository.getId() );
+ }
+
+ getRemoteRepositoriesService().addRemoteRepository( remoteRepository );
+
+ ProxyConnectorService proxyConnectorService = getProxyConnectorService();
+ ProxyConnector proxyConnector = new ProxyConnector();
+ proxyConnector.setProxyId( "foo-bar1" );
+ proxyConnector.setSourceRepoId( id );
+ proxyConnector.setTargetRepoId( "all-merged" );
+ proxyConnectorService.addProxyConnector( proxyConnector );
+
+ repositoriesService.scheduleDownloadRemoteIndex( "all-merged", true, true );
+
+ // wait a bit
+ timeout = 20000;
+ while ( timeout > 0 )
+ {
+ Thread.sleep( 500 );
+ timeout -= 500;
+ }
+
+ SearchService searchService = getSearchService();
+
+ SearchRequest request = new SearchRequest();
+ request.setRepositories( Arrays.asList( id ) );
+ request.setGroupId( "org.apache.felix" );
+
+ List<Artifact> artifacts = searchService.searchArtifacts( request );
+ assertThat( artifacts ).isNotNull().isNotEmpty().hasSize( 1 );
+
+ }
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
+import org.apache.archiva.security.common.ArchivaRoleConstants;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.wagon.providers.http.HttpWagon;
+import org.apache.maven.wagon.repository.Repository;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Locale;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( ArchivaBlockJUnit4ClassRunner.class )
+public class DownloadSnapshotTest
+ extends AbstractDownloadTest
+{
+ protected Logger log = LoggerFactory.getLogger( getClass() );
+
+ private static Path appServerBase;
+ private Path indexDir;
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv5_" ).toAbsolutePath();
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
+ return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml";
+ }
+
+ @Before
+ public void init() throws IOException
+ {
+ indexDir = Files.createTempDirectory( "archiva-web-common-index" );
+ }
+
+ @After
+ public void cleanup()
+ throws Exception
+ {
+ super.tearDown();
+ if ( Files.exists( indexDir ) )
+ {
+ FileUtils.deleteDirectory( indexDir.toFile() );
+ }
+ }
+
+
+ @Test
+ public void downloadSNAPSHOT()
+ throws Exception
+ {
+
+ String id = Long.toString( System.currentTimeMillis() );
+ Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/snapshot-repo" );
+ Path testRep = getBasedir( ).resolve( "target" ).resolve( "snapshot-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
+ createdPaths.add( testRep );
+
+ ManagedRepository managedRepository = new ManagedRepository( Locale.getDefault());
+ managedRepository.setId( id );
+ managedRepository.setName( "name of " + id );
+ managedRepository.setLocation( testRep.toString() );
+ managedRepository.setIndexDirectory( indexDir.resolve( "index-" + id ).toString() );
+ managedRepository.setPackedIndexDirectory( indexDir.resolve( "indexpacked-" + id ).toString() );
+
+ ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
+
+ if ( managedRepositoriesService.getManagedRepository( id ) != null )
+ {
+ managedRepositoriesService.deleteManagedRepository( id, false );
+ }
+
+ getManagedRepositoriesService().addManagedRepository( managedRepository );
+
+ RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader );
+
+ if ( !roleManagementService.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
+ id ) )
+ {
+ roleManagementService.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id );
+ }
+
+ getUserService( authorizationHeader ).createGuestUser();
+ roleManagementService.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, "guest" );
+
+ roleManagementService.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id,
+ "guest" );
+
+ getUserService( authorizationHeader ).removeFromCache( "guest" );
+
+ Path file = Paths.get( "target/archiva-model-1.4-M4-SNAPSHOT.jar" );
+ Files.deleteIfExists(file);
+
+ HttpWagon httpWagon = new HttpWagon();
+ httpWagon.connect( new Repository( "foo", "http://localhost:" + port ) );
+
+ httpWagon.get( "/repository/"+ id +"/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-SNAPSHOT.jar", file.toFile() );
+
+ ZipFile zipFile = new ZipFile( file.toFile() );
+ List<String> entries = getZipEntriesNames( zipFile );
+ ZipEntry zipEntry = zipFile.getEntry( "org/apache/archiva/model/ArchivaArtifact.class" );
+ assertNotNull( "cannot find zipEntry org/apache/archiva/model/ArchivaArtifact.class, entries: " + entries + ", content is: "
+ + FileUtils.readFileToString( file.toFile(), Charset.forName( "UTF-8") ), zipEntry );
+ zipFile.close();
+ file.toFile().deleteOnExit();
+
+
+
+ }
+
+}
--- /dev/null
+package org.apache.archiva.web.remotedownload;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.admin.model.beans.RemoteRepository;
+import org.apache.archiva.rest.api.services.RemoteRepositoriesService;
+import org.apache.commons.io.FileUtils;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.eclipse.jetty.server.Handler;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.server.handler.DefaultHandler;
+import org.eclipse.jetty.server.handler.HandlerList;
+import org.eclipse.jetty.server.handler.ResourceHandler;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Locale;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author Olivier Lamy
+ */
+public class RemoteRepositoryConnectivityCheckTest
+ extends AbstractDownloadTest
+{
+
+ private static Path appServerBase;
+
+ @BeforeClass
+ public static void setAppServerBase()
+ throws IOException
+ {
+ previousAppServerBase = System.getProperty( "appserver.base" );
+ appServerBase = Files.createTempDirectory( "archiva-common-web_appsrv6_" ).toAbsolutePath( );
+ System.setProperty( "appserver.base", appServerBase.toString( ) );
+ }
+
+ @AfterClass
+ public static void resetAppServerBase()
+ {
+ if (Files.exists(appServerBase)) {
+ FileUtils.deleteQuietly( appServerBase.toFile() );
+ }
+ System.setProperty( "appserver.base", previousAppServerBase );
+ }
+
+ @Override
+ protected String getSpringConfigLocation()
+ {
+ System.out.println( "AppserverBase: " + System.getProperty( "appserver.base" ) );
+ return "classpath*:META-INF/spring-context.xml classpath*:spring-context-test-common.xml classpath*:spring-context-artifacts-download.xml";
+ }
+
+ @Test
+ public void checkRemoteConnectivity()
+ throws Exception
+ {
+ String id = Long.toString( System.currentTimeMillis() );
+
+ Path srcRep = getProjectDirectory( ).resolve( "src/test/repositories/test-repo" );
+ Path testRep = getBasedir( ).resolve( "target" ).resolve( "test-repo-" + id ).toAbsolutePath();
+ FileUtils.copyDirectory( srcRep.toFile( ), testRep.toFile( ) );
+ createdPaths.add( testRep );
+
+
+ Server repoServer =
+ buildStaticServer( testRep );
+
+ ServerConnector serverConnector = new ServerConnector( repoServer, new HttpConnectionFactory());
+ repoServer.addConnector( serverConnector );
+ repoServer.start();
+
+ RemoteRepositoriesService service = getRemoteRepositoriesService();
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+
+ try
+ {
+
+ int repoServerPort = serverConnector.getLocalPort();
+
+ RemoteRepository repo = getRemoteRepository();
+
+ repo.setUrl( "http://localhost:" + repoServerPort );
+
+ service.addRemoteRepository( repo );
+
+ assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isTrue();
+ }
+ finally
+ {
+ service.deleteRemoteRepository( "id-new" );
+ repoServer.stop();
+ }
+ }
+
+ @Test
+ public void checkRemoteConnectivityEmptyRemote()
+ throws Exception
+ {
+
+ Path tmpDir = Files.createTempDirectory( "test" );
+ Server repoServer = buildStaticServer( tmpDir );
+ ServerConnector serverConnector = new ServerConnector( repoServer, new HttpConnectionFactory());
+ repoServer.addConnector( serverConnector );
+ repoServer.start();
+
+ RemoteRepositoriesService service = getRemoteRepositoriesService();
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+
+ try
+ {
+
+ int repoServerPort = serverConnector.getLocalPort();
+
+ RemoteRepository repo = getRemoteRepository();
+
+ repo.setUrl( "http://localhost:" + repoServerPort );
+
+ service.addRemoteRepository( repo );
+
+ assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isTrue();
+ }
+ finally
+ {
+ service.deleteRemoteRepository( "id-new" );
+ org.apache.archiva.common.utils.FileUtils.deleteQuietly( tmpDir );
+ repoServer.stop();
+ }
+ }
+
+ @Test
+ public void checkRemoteConnectivityFail()
+ throws Exception
+ {
+
+ RemoteRepositoriesService service = getRemoteRepositoriesService();
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+
+ try
+ {
+
+ RemoteRepository repo = getRemoteRepository();
+
+ repo.setUrl( "http://localhost:8956" );
+
+ service.addRemoteRepository( repo );
+
+ assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isFalse();
+ }
+ finally
+ {
+ service.deleteRemoteRepository( "id-new" );
+
+ }
+ }
+
+ protected Server buildStaticServer( Path path )
+ {
+ Server repoServer = new Server( );
+
+ ResourceHandler resourceHandler = new ResourceHandler();
+ resourceHandler.setDirectoriesListed( true );
+ resourceHandler.setWelcomeFiles( new String[]{ "index.html" } );
+ resourceHandler.setResourceBase( path.toAbsolutePath().toString() );
+
+ HandlerList handlers = new HandlerList();
+ handlers.setHandlers( new Handler[]{ resourceHandler, new DefaultHandler() } );
+ repoServer.setHandler( handlers );
+
+ return repoServer;
+ }
+
+
+ RemoteRepository getRemoteRepository()
+ {
+ return new RemoteRepository( Locale.getDefault( ), "id-new", "new one", "http://foo.com", "default", "foo", "foopassword", 120,
+ "cool repo" );
+ }
+
+}
--- /dev/null
+package org.apache.archiva.web.upload;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import org.apache.archiva.configuration.ArchivaConfiguration;
+import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
+import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
+import org.apache.archiva.web.AbstractRestServicesTest;
+import org.apache.archiva.web.api.FileUploadService;
+import org.apache.archiva.web.model.FileMetadata;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.SystemUtils;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.jaxrs.ext.multipart.Attachment;
+import org.apache.cxf.jaxrs.ext.multipart.AttachmentBuilder;
+import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
+import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
+import org.apache.cxf.message.Message;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.ws.rs.ClientErrorException;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith(ArchivaBlockJUnit4ClassRunner.class)
+public class UploadArtifactsTest
+ extends AbstractRestServicesTest
+{
+
+ private static String PREVIOUS_ARCHIVA_PATH;
+ private AtomicReference<Path> projectDir = new AtomicReference<>( );
+
+ @BeforeClass
+ public static void initConfigurationPath()
+ throws Exception
+ {
+ PREVIOUS_ARCHIVA_PATH = System.getProperty(ArchivaConfiguration.USER_CONFIG_PROPERTY);
+ if (System.getProperties().containsKey( "test.resources.path" ))
+ {
+ System.setProperty( ArchivaConfiguration.USER_CONFIG_PROPERTY,
+ System.getProperty( "test.resources.path" ) + "/archiva.xml" );
+ } else {
+ Path path = Paths.get( "src/test/resources/archiva.xml" ).toAbsolutePath();
+ System.setProperty( ArchivaConfiguration.USER_CONFIG_PROPERTY,
+ path.toString() );
+
+ }
+ System.err.println( "USER_CONFIG_DIR " + System.getProperty( ArchivaConfiguration.USER_CONFIG_PROPERTY ) );
+ }
+
+
+ @AfterClass
+ public static void restoreConfigurationPath()
+ throws Exception
+ {
+ System.setProperty( ArchivaConfiguration.USER_CONFIG_PROPERTY, PREVIOUS_ARCHIVA_PATH );
+ }
+ @Override
+ protected String getSpringConfigLocation() {
+ return "classpath*:META-INF/spring-context.xml,classpath:/spring-context-test-upload.xml";
+ }
+
+ protected Path getProjectDirectory() {
+ if ( projectDir.get()==null) {
+ String propVal = System.getProperty("mvn.project.base.dir");
+ Path newVal;
+ if (StringUtils.isEmpty(propVal)) {
+ newVal = Paths.get("").toAbsolutePath();
+ } else {
+ newVal = Paths.get(propVal).toAbsolutePath();
+ }
+ projectDir.compareAndSet(null, newVal);
+ }
+ System.err.println( "project dir: " + projectDir.get( ).toString( ) );
+ return projectDir.get();
+ }
+
+ @Override
+ protected String getRestServicesPath() {
+ return "restServices";
+ }
+
+ protected String getBaseUrl() {
+ String baseUrlSysProps = System.getProperty("archiva.baseRestUrl");
+ return StringUtils.isBlank(baseUrlSysProps) ? "http://localhost:" + getServerPort() : baseUrlSysProps;
+ }
+
+ private FileUploadService getUploadService() {
+ FileUploadService service =
+ JAXRSClientFactory.create(getBaseUrl() + "/" + getRestServicesPath() + "/archivaUiServices/",
+ FileUploadService.class,
+ Collections.singletonList(new JacksonJaxbJsonProvider()));
+ log.debug("Service class {}", service.getClass().getName());
+ WebClient.client(service).header("Authorization", authorizationHeader);
+ WebClient.client(service).header("Referer", "http://localhost:" + getServerPort());
+
+ WebClient.client(service).header("Referer", "http://localhost");
+ WebClient.getConfig(service).getRequestContext().put(Message.MAINTAIN_SESSION, true);
+ WebClient.getConfig(service).getRequestContext().put(Message.EXCEPTION_MESSAGE_CAUSE_ENABLED, true);
+ WebClient.getConfig(service).getRequestContext().put(Message.FAULT_STACKTRACE_ENABLED, true);
+ WebClient.getConfig(service).getRequestContext().put(Message.PROPOGATE_EXCEPTION, true);
+ WebClient.getConfig(service).getRequestContext().put("org.apache.cxf.transport.no_io_exceptions", true);
+
+ // WebClient.client( service ).
+ return service;
+ }
+
+ @Test
+ public void clearUploadedFiles()
+ throws Exception {
+ FileUploadService service = getUploadService();
+ service.clearUploadedFiles();
+ }
+
+ @Test
+ public void uploadFile() throws IOException, ArchivaRestServiceException {
+ FileUploadService service = getUploadService();
+ try {
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ } finally {
+ service.clearUploadedFiles();
+ }
+ }
+
+ @Test
+ public void failUploadFileWithBadFileName() throws IOException, ArchivaRestServiceException {
+ FileUploadService service = getUploadService();
+ try {
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"/../TestFile.testext\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ try {
+ service.post(body);
+ fail("FileNames with path contents should not be allowed.");
+ } catch (ClientErrorException e) {
+ assertEquals(422, e.getResponse().getStatus());
+ }
+ } finally {
+ service.clearUploadedFiles();
+ }
+ }
+
+ @Test
+ public void uploadAndDeleteFile() throws IOException, ArchivaRestServiceException {
+ FileUploadService service = getUploadService();
+ try {
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ service.deleteFile(file.getFileName().toString());
+ } finally {
+ service.clearUploadedFiles();
+ }
+ }
+
+ @Test
+ public void failUploadAndDeleteWrongFile() throws IOException, ArchivaRestServiceException {
+ FileUploadService service = getUploadService();
+ try {
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ assertFalse(service.deleteFile("file123" + file.getFileName().toString()));
+ } finally {
+ service.clearUploadedFiles();
+ }
+ }
+
+ @Test
+ public void failUploadAndDeleteFileInOtherDir() throws IOException, ArchivaRestServiceException {
+ Path testFile = null;
+ try {
+ FileUploadService service = getUploadService();
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ Path targetDir = getProjectDirectory().resolve("target/testDelete").toAbsolutePath();
+ if (!Files.exists(targetDir)) Files.createDirectories(targetDir);
+ Path tempDir = SystemUtils.getJavaIoTmpDir().toPath();
+ testFile = Files.createTempFile(targetDir, "TestFile", ".txt");
+ log.debug("Test file {}", testFile.toAbsolutePath());
+ log.debug("Tmp dir {}", tempDir.toAbsolutePath());
+ assertTrue(Files.exists(testFile));
+ Path relativePath = tempDir.relativize(testFile.toAbsolutePath());
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ String relativePathEncoded = URLEncoder.encode("../target/" + relativePath.toString(), "UTF-8");
+ log.debug("Trying to delete with path traversal: {}, {}", relativePath, relativePathEncoded);
+ try {
+ service.deleteFile(relativePathEncoded);
+ } catch (ArchivaRestServiceException ex) {
+ // Expected exception
+ }
+ assertTrue("File in another directory may not be deleted", Files.exists(testFile));
+ } finally {
+ if (testFile != null) {
+ Files.deleteIfExists(testFile);
+ }
+ }
+ }
+
+ @Test
+ public void failSaveFileWithBadParams() throws IOException, ArchivaRestServiceException {
+ Path path = getProjectDirectory().resolve("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.jar");
+ Files.deleteIfExists(path);
+ FileUploadService service = getUploadService();
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+
+ Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.jar\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ assertTrue(service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "jar", true));
+
+ fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"TestFile.FileExt\"; name=\"files[]\"")).build();
+ body = new MultipartBody(fileAttachment);
+ FileMetadata meta = service.post(body);
+ log.debug("Metadata {}", meta.toString());
+ try {
+ service.save("internal", "org", URLEncoder.encode("../../../test", "UTF-8"), URLEncoder.encode("testSave", "UTF-8"), "4", true);
+ fail("Error expected, if the content contains bad characters.");
+ } catch (ClientErrorException e) {
+ assertEquals(422, e.getResponse().getStatus());
+ }
+ assertFalse(Files.exists(getProjectDirectory().resolve("target/test-testSave.4")));
+ }
+
+ @Test
+ public void saveFile() throws IOException, ArchivaRestServiceException {
+ log.debug("Starting saveFile()");
+
+ Path path = getProjectDirectory().resolve("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.jar");
+ log.debug("Jar exists: {}",Files.exists(path));
+ Files.deleteIfExists(path);
+ path = getProjectDirectory().resolve("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.pom");
+ Files.deleteIfExists(path);
+ FileUploadService service = getUploadService();
+ service.clearUploadedFiles();
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ log.debug("Upload file exists: {}", Files.exists(file));
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.jar\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "jar", true);
+ }
+
+ @Test
+ public void saveFileWithOtherExtension() throws IOException, ArchivaRestServiceException {
+ log.debug("Starting saveFileWithOtherExtension()");
+
+ Path path = getProjectDirectory().resolve("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.bin");
+ log.debug("Jar exists: {}",Files.exists(path));
+ Files.deleteIfExists(path);
+ Path pomPath = getProjectDirectory().resolve("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.pom");
+ Files.deleteIfExists(pomPath);
+ FileUploadService service = getUploadService();
+ service.clearUploadedFiles();
+ Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
+ log.debug("Upload file exists: {}", Files.exists(file));
+ final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.bin\"; name=\"files[]\"")).build();
+ MultipartBody body = new MultipartBody(fileAttachment);
+ service.post(body);
+ assertTrue(service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "bin", false));
+ assertTrue(Files.exists(path));
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.web.webtest.memory;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.metadata.model.ArtifactMetadata;
+import org.apache.archiva.metadata.repository.AbstractMetadataRepository;
+import org.apache.archiva.metadata.repository.RepositorySession;
+
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+public class TestMetadataRepository
+ extends AbstractMetadataRepository
+{
+ private static final String TEST_REPO = "test-repo";
+
+ private static final String TEST_NAMESPACE = "org.apache.archiva";
+
+ private List<ArtifactMetadata> artifacts = new ArrayList<>();
+
+ private List<String> versions = new ArrayList<>();
+
+ public TestMetadataRepository()
+ {
+ Date whenGatheredDate = new Date( 123456789 );
+ ZonedDateTime whenGathered = ZonedDateTime.ofInstant(whenGatheredDate.toInstant(), ZoneId.systemDefault());
+
+ addArtifact( "artifact-one", "1.0", whenGathered );
+ addArtifact( "artifact-one", "1.1", whenGathered );
+ addArtifact( "artifact-one", "2.0", whenGathered );
+ addArtifact( "artifact-two", "1.0.1", whenGathered );
+ addArtifact( "artifact-two", "1.0.2", whenGathered );
+ addArtifact( "artifact-two", "1.0.3-SNAPSHOT", whenGathered );
+ addArtifact( "artifact-three", "2.0-SNAPSHOT", whenGathered );
+ addArtifact( "artifact-four", "1.1-beta-2", whenGathered );
+ }
+
+ private void addArtifact( String projectId, String projectVersion, ZonedDateTime whenGathered )
+ {
+ ArtifactMetadata artifact = new ArtifactMetadata();
+ artifact.setFileLastModified( System.currentTimeMillis() );
+ artifact.setNamespace( TEST_NAMESPACE );
+ artifact.setProjectVersion( projectVersion );
+ artifact.setVersion( projectVersion );
+ artifact.setId( projectId + "-" + projectVersion + ".jar" );
+ artifact.setProject( projectId );
+ artifact.setRepositoryId( TEST_REPO );
+ artifact.setWhenGathered( whenGathered );
+ artifacts.add( artifact );
+
+ versions.add( projectVersion );
+ }
+
+ @Override
+ public List<String> getProjectVersions( RepositorySession session, String repoId, String namespace, String projectId )
+ {
+ return versions;
+ }
+
+ @Override
+ public List<String> getMetadataFacets( RepositorySession session, String repodId, String facetId )
+ {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void removeMetadataFacet( RepositorySession session, String repoId, String facetId, String name )
+ {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ @Override
+ public List<ArtifactMetadata> getArtifactsByDateRange(RepositorySession session, String repoId, ZonedDateTime startTime, ZonedDateTime endTime )
+ {
+ return artifacts;
+ }
+
+
+ @Override
+ public List<ArtifactMetadata> getArtifacts( RepositorySession session, String repoId, String namespace, String projectId,
+ String projectVersion )
+ {
+ return artifacts;
+ }
+
+ @Override
+ public List<ArtifactMetadata> getArtifacts( RepositorySession session, String repositoryId )
+ {
+ return artifacts;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package org.apache.archiva.web.webtest.memory;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.metadata.model.ArtifactMetadata;
+import org.apache.archiva.metadata.model.ProjectVersionMetadata;
+import org.apache.archiva.metadata.model.ProjectVersionReference;
+import org.apache.archiva.metadata.repository.MetadataResolver;
+import org.apache.archiva.metadata.repository.RepositorySession;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class TestMetadataResolver
+ implements MetadataResolver
+{
+ private Map<String, ProjectVersionMetadata> projectVersions = new HashMap<>();
+
+ private Map<String, List<ArtifactMetadata>> artifacts = new HashMap<>();
+
+ private Map<String, List<ProjectVersionReference>> references =
+ new HashMap<String, List<ProjectVersionReference>>();
+
+ private Map<String, List<String>> namespaces = new HashMap<>();
+
+ private Map<String, Collection<String>> projectsInNamespace = new HashMap<>();
+
+ private Map<String, Collection<String>> versionsInProject = new HashMap<>();
+
+ @Override
+ public ProjectVersionMetadata resolveProjectVersion( RepositorySession repositorySession, String repoId,
+ String namespace, String projectId, String projectVersion )
+ {
+ return projectVersions.get( createMapKey( repoId, namespace, projectId, projectVersion ) );
+ }
+
+ @Override
+ public Collection<ProjectVersionReference> resolveProjectReferences( RepositorySession repositorySession,
+ String repoId, String namespace,
+ String projectId, String projectVersion )
+ {
+ Collection<ProjectVersionReference> projectVersionReferences =
+ references.get( createMapKey( repoId, namespace, projectId, projectVersion ) );
+ return projectVersionReferences;
+ }
+
+ @Override
+ public Collection<String> resolveRootNamespaces( RepositorySession repositorySession, String repoId )
+ {
+ return resolveNamespaces( repositorySession, repoId, null );
+ }
+
+ @Override
+ public Collection<String> resolveNamespaces( RepositorySession repositorySession, String repoId,
+ String baseNamespace )
+ {
+ Set<String> namespaces = new LinkedHashSet<String>();
+ int fromIndex = baseNamespace != null ? baseNamespace.length() + 1 : 0;
+ for ( String namespace : this.namespaces.get( repoId ) )
+ {
+ if ( baseNamespace == null || namespace.startsWith( baseNamespace + "." ) )
+ {
+ int i = namespace.indexOf( '.', fromIndex );
+ if ( i >= 0 )
+ {
+ namespaces.add( namespace.substring( fromIndex, i ) );
+ }
+ else
+ {
+ namespaces.add( namespace.substring( fromIndex ) );
+ }
+ }
+ }
+ return namespaces;
+ }
+
+ @Override
+ public Collection<String> resolveProjects( RepositorySession repositorySession, String repoId, String namespace )
+ {
+ Collection<String> list = projectsInNamespace.get( namespace );
+ return list != null ? list : Collections.<String>emptyList();
+ }
+
+ @Override
+ public Collection<String> resolveProjectVersions( RepositorySession repositorySession, String repoId,
+ String namespace, String projectId )
+ {
+ Collection<String> list = versionsInProject.get( namespace + ":" + projectId );
+ return list != null ? list : Collections.<String>emptyList();
+ }
+
+ @Override
+ public Collection<ArtifactMetadata> resolveArtifacts( RepositorySession repositorySession, String repoId,
+ String namespace, String projectId, String projectVersion )
+ {
+ List<ArtifactMetadata> artifacts =
+ this.artifacts.get( createMapKey( repoId, namespace, projectId, projectVersion ) );
+ return ( artifacts != null ? artifacts : Collections.<ArtifactMetadata>emptyList() );
+ }
+
+ public void setProjectVersion( String repoId, String namespace, String projectId,
+ ProjectVersionMetadata versionMetadata )
+ {
+ projectVersions.put( createMapKey( repoId, namespace, projectId, versionMetadata.getId() ), versionMetadata );
+
+ Collection<String> projects = projectsInNamespace.get( namespace );
+ if ( projects == null )
+ {
+ projects = new LinkedHashSet<String>();
+ projectsInNamespace.put( namespace, projects );
+ }
+ projects.add( projectId );
+
+ String key = namespace + ":" + projectId;
+ Collection<String> versions = versionsInProject.get( key );
+ if ( versions == null )
+ {
+ versions = new LinkedHashSet<String>();
+ versionsInProject.put( key, versions );
+ }
+ versions.add( versionMetadata.getId() );
+ }
+
+ public void setArtifacts( String repoId, String namespace, String projectId, String projectVersion,
+ List<ArtifactMetadata> artifacts )
+ {
+ this.artifacts.put( createMapKey( repoId, namespace, projectId, projectVersion ), artifacts );
+ }
+
+ private String createMapKey( String repoId, String namespace, String projectId, String projectVersion )
+ {
+ return repoId + ":" + namespace + ":" + projectId + ":" + projectVersion;
+ }
+
+ public void setProjectReferences( String repoId, String namespace, String projectId, String projectVersion,
+ List<ProjectVersionReference> references )
+ {
+ this.references.put( createMapKey( repoId, namespace, projectId, projectVersion ), references );
+ }
+
+ public void setNamespaces( String repoId, List<String> namespaces )
+ {
+ this.namespaces.put( repoId, namespaces );
+ }
+}
--- /dev/null
+package org.apache.archiva.web.webtest.memory;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.metadata.repository.MetadataRepositoryException;
+import org.apache.archiva.metadata.repository.RepositorySession;
+import org.apache.archiva.metadata.repository.RepositorySessionFactory;
+import org.springframework.beans.factory.config.AbstractFactoryBean;
+import org.springframework.stereotype.Service;
+
+@Service("repositorySessionFactory#test")
+public class TestRepositorySessionFactory
+ extends AbstractFactoryBean<RepositorySessionFactory>
+ implements RepositorySessionFactory
+{
+ private RepositorySession repositorySession;
+
+ public void setRepositorySession( RepositorySession repositorySession )
+ {
+ this.repositorySession = repositorySession;
+ }
+
+ @Override
+ public void open() {
+
+ }
+
+ @Override
+ public boolean isOpen() {
+ return false;
+ }
+
+ @Override
+ public RepositorySession createSession() throws MetadataRepositoryException
+ {
+ return repositorySession != null ? repositorySession : new RepositorySession( new TestMetadataRepository(),
+ new TestMetadataResolver() );
+ }
+
+ @Override
+ public Class<RepositorySessionFactory> getObjectType()
+ {
+ return RepositorySessionFactory.class;
+ }
+
+ @Override
+ protected RepositorySessionFactory createInstance()
+ throws Exception
+ {
+ return this;
+ }
+
+ @Override
+ public void close()
+ {
+ // no op
+ }
+}
+++ /dev/null
-package org.apache.archiva.webtest.memory;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.metadata.model.ArtifactMetadata;
-import org.apache.archiva.metadata.repository.AbstractMetadataRepository;
-import org.apache.archiva.metadata.repository.RepositorySession;
-
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-public class TestMetadataRepository
- extends AbstractMetadataRepository
-{
- private static final String TEST_REPO = "test-repo";
-
- private static final String TEST_NAMESPACE = "org.apache.archiva";
-
- private List<ArtifactMetadata> artifacts = new ArrayList<>();
-
- private List<String> versions = new ArrayList<>();
-
- public TestMetadataRepository()
- {
- Date whenGatheredDate = new Date( 123456789 );
- ZonedDateTime whenGathered = ZonedDateTime.ofInstant(whenGatheredDate.toInstant(), ZoneId.systemDefault());
-
- addArtifact( "artifact-one", "1.0", whenGathered );
- addArtifact( "artifact-one", "1.1", whenGathered );
- addArtifact( "artifact-one", "2.0", whenGathered );
- addArtifact( "artifact-two", "1.0.1", whenGathered );
- addArtifact( "artifact-two", "1.0.2", whenGathered );
- addArtifact( "artifact-two", "1.0.3-SNAPSHOT", whenGathered );
- addArtifact( "artifact-three", "2.0-SNAPSHOT", whenGathered );
- addArtifact( "artifact-four", "1.1-beta-2", whenGathered );
- }
-
- private void addArtifact( String projectId, String projectVersion, ZonedDateTime whenGathered )
- {
- ArtifactMetadata artifact = new ArtifactMetadata();
- artifact.setFileLastModified( System.currentTimeMillis() );
- artifact.setNamespace( TEST_NAMESPACE );
- artifact.setProjectVersion( projectVersion );
- artifact.setVersion( projectVersion );
- artifact.setId( projectId + "-" + projectVersion + ".jar" );
- artifact.setProject( projectId );
- artifact.setRepositoryId( TEST_REPO );
- artifact.setWhenGathered( whenGathered );
- artifacts.add( artifact );
-
- versions.add( projectVersion );
- }
-
- @Override
- public List<String> getProjectVersions( RepositorySession session, String repoId, String namespace, String projectId )
- {
- return versions;
- }
-
- @Override
- public List<String> getMetadataFacets( RepositorySession session, String repodId, String facetId )
- {
- return Collections.emptyList();
- }
-
- @Override
- public void removeMetadataFacet( RepositorySession session, String repoId, String facetId, String name )
- {
- //To change body of implemented methods use File | Settings | File Templates.
- }
-
- @Override
- public List<ArtifactMetadata> getArtifactsByDateRange(RepositorySession session, String repoId, ZonedDateTime startTime, ZonedDateTime endTime )
- {
- return artifacts;
- }
-
-
- @Override
- public List<ArtifactMetadata> getArtifacts( RepositorySession session, String repoId, String namespace, String projectId,
- String projectVersion )
- {
- return artifacts;
- }
-
- @Override
- public List<ArtifactMetadata> getArtifacts( RepositorySession session, String repositoryId )
- {
- return artifacts;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.apache.archiva.webtest.memory;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.metadata.model.ArtifactMetadata;
-import org.apache.archiva.metadata.model.ProjectVersionMetadata;
-import org.apache.archiva.metadata.model.ProjectVersionReference;
-import org.apache.archiva.metadata.repository.MetadataResolver;
-import org.apache.archiva.metadata.repository.RepositorySession;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-public class TestMetadataResolver
- implements MetadataResolver
-{
- private Map<String, ProjectVersionMetadata> projectVersions = new HashMap<>();
-
- private Map<String, List<ArtifactMetadata>> artifacts = new HashMap<>();
-
- private Map<String, List<ProjectVersionReference>> references =
- new HashMap<String, List<ProjectVersionReference>>();
-
- private Map<String, List<String>> namespaces = new HashMap<>();
-
- private Map<String, Collection<String>> projectsInNamespace = new HashMap<>();
-
- private Map<String, Collection<String>> versionsInProject = new HashMap<>();
-
- @Override
- public ProjectVersionMetadata resolveProjectVersion( RepositorySession repositorySession, String repoId,
- String namespace, String projectId, String projectVersion )
- {
- return projectVersions.get( createMapKey( repoId, namespace, projectId, projectVersion ) );
- }
-
- @Override
- public Collection<ProjectVersionReference> resolveProjectReferences( RepositorySession repositorySession,
- String repoId, String namespace,
- String projectId, String projectVersion )
- {
- Collection<ProjectVersionReference> projectVersionReferences =
- references.get( createMapKey( repoId, namespace, projectId, projectVersion ) );
- return projectVersionReferences;
- }
-
- @Override
- public Collection<String> resolveRootNamespaces( RepositorySession repositorySession, String repoId )
- {
- return resolveNamespaces( repositorySession, repoId, null );
- }
-
- @Override
- public Collection<String> resolveNamespaces( RepositorySession repositorySession, String repoId,
- String baseNamespace )
- {
- Set<String> namespaces = new LinkedHashSet<String>();
- int fromIndex = baseNamespace != null ? baseNamespace.length() + 1 : 0;
- for ( String namespace : this.namespaces.get( repoId ) )
- {
- if ( baseNamespace == null || namespace.startsWith( baseNamespace + "." ) )
- {
- int i = namespace.indexOf( '.', fromIndex );
- if ( i >= 0 )
- {
- namespaces.add( namespace.substring( fromIndex, i ) );
- }
- else
- {
- namespaces.add( namespace.substring( fromIndex ) );
- }
- }
- }
- return namespaces;
- }
-
- @Override
- public Collection<String> resolveProjects( RepositorySession repositorySession, String repoId, String namespace )
- {
- Collection<String> list = projectsInNamespace.get( namespace );
- return list != null ? list : Collections.<String>emptyList();
- }
-
- @Override
- public Collection<String> resolveProjectVersions( RepositorySession repositorySession, String repoId,
- String namespace, String projectId )
- {
- Collection<String> list = versionsInProject.get( namespace + ":" + projectId );
- return list != null ? list : Collections.<String>emptyList();
- }
-
- @Override
- public Collection<ArtifactMetadata> resolveArtifacts( RepositorySession repositorySession, String repoId,
- String namespace, String projectId, String projectVersion )
- {
- List<ArtifactMetadata> artifacts =
- this.artifacts.get( createMapKey( repoId, namespace, projectId, projectVersion ) );
- return ( artifacts != null ? artifacts : Collections.<ArtifactMetadata>emptyList() );
- }
-
- public void setProjectVersion( String repoId, String namespace, String projectId,
- ProjectVersionMetadata versionMetadata )
- {
- projectVersions.put( createMapKey( repoId, namespace, projectId, versionMetadata.getId() ), versionMetadata );
-
- Collection<String> projects = projectsInNamespace.get( namespace );
- if ( projects == null )
- {
- projects = new LinkedHashSet<String>();
- projectsInNamespace.put( namespace, projects );
- }
- projects.add( projectId );
-
- String key = namespace + ":" + projectId;
- Collection<String> versions = versionsInProject.get( key );
- if ( versions == null )
- {
- versions = new LinkedHashSet<String>();
- versionsInProject.put( key, versions );
- }
- versions.add( versionMetadata.getId() );
- }
-
- public void setArtifacts( String repoId, String namespace, String projectId, String projectVersion,
- List<ArtifactMetadata> artifacts )
- {
- this.artifacts.put( createMapKey( repoId, namespace, projectId, projectVersion ), artifacts );
- }
-
- private String createMapKey( String repoId, String namespace, String projectId, String projectVersion )
- {
- return repoId + ":" + namespace + ":" + projectId + ":" + projectVersion;
- }
-
- public void setProjectReferences( String repoId, String namespace, String projectId, String projectVersion,
- List<ProjectVersionReference> references )
- {
- this.references.put( createMapKey( repoId, namespace, projectId, projectVersion ), references );
- }
-
- public void setNamespaces( String repoId, List<String> namespaces )
- {
- this.namespaces.put( repoId, namespaces );
- }
-}
+++ /dev/null
-package org.apache.archiva.webtest.memory;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.metadata.repository.MetadataRepositoryException;
-import org.apache.archiva.metadata.repository.RepositorySession;
-import org.apache.archiva.metadata.repository.RepositorySessionFactory;
-import org.springframework.beans.factory.config.AbstractFactoryBean;
-import org.springframework.stereotype.Service;
-
-@Service("repositorySessionFactory#test")
-public class TestRepositorySessionFactory
- extends AbstractFactoryBean<RepositorySessionFactory>
- implements RepositorySessionFactory
-{
- private RepositorySession repositorySession;
-
- public void setRepositorySession( RepositorySession repositorySession )
- {
- this.repositorySession = repositorySession;
- }
-
- @Override
- public void open() {
-
- }
-
- @Override
- public boolean isOpen() {
- return false;
- }
-
- @Override
- public RepositorySession createSession() throws MetadataRepositoryException
- {
- return repositorySession != null ? repositorySession : new RepositorySession( new TestMetadataRepository(),
- new TestMetadataResolver() );
- }
-
- @Override
- public Class<RepositorySessionFactory> getObjectType()
- {
- return RepositorySessionFactory.class;
- }
-
- @Override
- protected RepositorySessionFactory createInstance()
- throws Exception
- {
- return this;
- }
-
- @Override
- public void close()
- {
- // no op
- }
-}
<logger name="org.springframework" level="error"/>
<logger name="org.apache.archiva" level="error"/>
- <logger name="org.apache.archiva.web" level="info"/>
+ <logger name="org.apache.archiva.web" level="debug"/>
+ <logger name="org.apache.archiva.repository" level="debug"/>
<logger name="org.apache.commons.configuration" level="error"/>
<logger name="org.apache.archiva.scheduler.indexing" level="info"/>
<logger name="org.apache.archiva.remotedownload" level="info"/>
</property>
</bean>
- <bean name="repositorySessionFactory" class="org.apache.archiva.webtest.memory.TestRepositorySessionFactory"/>
+ <bean name="repositorySessionFactory" class="org.apache.archiva.web.webtest.memory.TestRepositorySessionFactory"/>
<alias name="userManager#configurable" alias="userManager#default"/>
- <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.TestRepositorySessionFactoryBean">
+ <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.web.TestRepositorySessionFactoryBean">
<constructor-arg>
<value>jcr</value>
</constructor-arg>
</property>
</bean>
- <bean name="repositorySessionFactory" class="org.apache.archiva.webtest.memory.TestRepositorySessionFactory"/>
+ <bean name="repositorySessionFactory" class="org.apache.archiva.web.webtest.memory.TestRepositorySessionFactory"/>
<alias name="userConfiguration#archiva" alias="userConfiguration#default"/>
<alias name="authorizer#rbac" alias="authorizer#default"/>
<alias name="userManager#configurable" alias="userManager#default"/>
- <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.TestRepositorySessionFactoryBean">
+ <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.web.TestRepositorySessionFactoryBean">
<constructor-arg>
<value>jcr</value>
</constructor-arg>
<context:property-placeholder system-properties-mode="OVERRIDE"/>
<context:annotation-config/>
- <context:component-scan base-package="org.apache.archiva.webtest.memory"/>
+ <context:component-scan base-package="org.apache.archiva.web.webtest.memory"/>
<alias name="repositorySessionFactory#test" alias="repositorySessionFactory"/>
- <bean name="userRepositories#test" class="org.apache.archiva.security.UserRepositoriesStub"/>
+ <bean name="userRepositories#test" class="org.apache.archiva.web.mock.security.UserRepositoriesStub"/>
<alias name="userRepositories#test" alias="userRepositories"/>
<alias name="archivaConfiguration#default" alias="archivaConfiguration"/>
- <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.TestRepositorySessionFactoryBean">
+ <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.web.TestRepositorySessionFactoryBean">
<constructor-arg>
<value>jcr</value>
</constructor-arg>
<context:annotation-config/>
<context:component-scan
- base-package="org.apache.archiva.repository.content.maven2,org.apache.archiva.redback.keys,org.apache.archiva.rest.services.utils"/>
+ base-package="org.apache.archiva.maven.repository.content,org.apache.archiva.redback.keys,org.apache.archiva.rest.services.utils"/>
<bean name="scheduler" class="org.apache.archiva.components.scheduler.DefaultScheduler">
<property name="properties">
</bean>
- <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.TestRepositorySessionFactoryBean">
+ <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.web.TestRepositorySessionFactoryBean">
<constructor-arg>
<value>jcr</value>
</constructor-arg>
<alias name="repositorySessionFactory#jcr" alias="repositorySessionFactory"/>
- <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.TestRepositorySessionFactoryBean">
+ <bean name="TestRepositorySessionFactoryBean" class="org.apache.archiva.web.TestRepositorySessionFactoryBean">
<constructor-arg>
<value>jcr</value>
</constructor-arg>