import org.apache.archiva.indexer.IndexUpdateFailedException;
import org.apache.archiva.indexer.UnsupportedBaseContextException;
import org.apache.archiva.proxy.ProxyRegistry;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryException;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryException;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.ManagedRepository;
--- /dev/null
+package org.apache.archiva.maven.common.proxy;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.maven.wagon.events.TransferEvent;
+import org.apache.maven.wagon.events.TransferListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4-M1
+ */
+public class DebugTransferListener
+ implements TransferListener
+{
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ @Override
+ public void transferInitiated( TransferEvent transferEvent )
+ {
+ log.debug( "transferInitiated for resource {} on repository url {}", transferEvent.getResource().getName(),
+ transferEvent.getWagon().getRepository().getUrl() );
+ }
+
+ @Override
+ public void transferStarted( TransferEvent transferEvent )
+ {
+ log.debug( "transferStarted for resource {} on repository url {}", transferEvent.getResource().getName(),
+ transferEvent.getWagon().getRepository().getUrl() );
+ }
+
+ @Override
+ public void transferProgress( TransferEvent transferEvent, byte[] bytes, int i )
+ {
+ log.debug( "transferProgress for resource {} on repository url {}", transferEvent.getResource().getName(),
+ transferEvent.getWagon().getRepository().getUrl() );
+ }
+
+ @Override
+ public void transferCompleted( TransferEvent transferEvent )
+ {
+ log.debug( "transferCompleted for resource {} on repository url {}", transferEvent.getResource().getName(),
+ transferEvent.getWagon().getRepository().getUrl() );
+ }
+
+ @Override
+ public void transferError( TransferEvent transferEvent )
+ {
+ log.debug( "transferError for resource {} on repository url {}", transferEvent.getResource().getName(),
+ transferEvent.getWagon().getRepository().getUrl(), transferEvent.getException() );
+ }
+
+ @Override
+ public void debug( String s )
+ {
+ log.debug( "wagon debug {}", s );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.common.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.maven.wagon.Wagon;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4-M1
+ */
+@Service ("wagonFactory")
+public class DefaultWagonFactory
+ implements WagonFactory
+{
+
+ private ApplicationContext applicationContext;
+
+ private Logger logger = LoggerFactory.getLogger( getClass() );
+
+ private DebugTransferListener debugTransferListener = new DebugTransferListener();
+
+ @Inject
+ public DefaultWagonFactory( ApplicationContext applicationContext )
+ {
+ this.applicationContext = applicationContext;
+ }
+
+ @Override
+ public Wagon getWagon( WagonFactoryRequest wagonFactoryRequest )
+ throws WagonFactoryException
+ {
+ try
+ {
+ String protocol = StringUtils.startsWith( wagonFactoryRequest.getProtocol(), "wagon#" )
+ ? wagonFactoryRequest.getProtocol()
+ : "wagon#" + wagonFactoryRequest.getProtocol();
+
+ // if it's a ntlm proxy we have to lookup the wagon light which support thats
+ // wagon http client doesn't support that
+ if ( wagonFactoryRequest.getNetworkProxy() != null && wagonFactoryRequest.getNetworkProxy().isUseNtlm() )
+ {
+ protocol = protocol + "-ntlm";
+ }
+
+ Wagon wagon = applicationContext.getBean( protocol, Wagon.class );
+ wagon.addTransferListener( debugTransferListener );
+ configureUserAgent( wagon, wagonFactoryRequest );
+ return wagon;
+ }
+ catch ( BeansException e )
+ {
+ throw new WagonFactoryException( e.getMessage(), e );
+ }
+ }
+
+ protected void configureUserAgent( Wagon wagon, WagonFactoryRequest wagonFactoryRequest )
+ {
+ try
+ {
+ Class<? extends Wagon> clazz = wagon.getClass();
+ Method getHttpHeaders = clazz.getMethod( "getHttpHeaders" );
+
+ Properties headers = (Properties) getHttpHeaders.invoke( wagon );
+ if ( headers == null )
+ {
+ headers = new Properties();
+ }
+
+ headers.put( "User-Agent", wagonFactoryRequest.getUserAgent() );
+
+ if ( !wagonFactoryRequest.getHeaders().isEmpty() )
+ {
+ for ( Map.Entry<String, String> entry : wagonFactoryRequest.getHeaders().entrySet() )
+ {
+ headers.put( entry.getKey(), entry.getValue() );
+ }
+ }
+
+ Method setHttpHeaders = clazz.getMethod( "setHttpHeaders", new Class[]{ Properties.class } );
+ setHttpHeaders.invoke( wagon, headers );
+
+ logger.debug( "http headers set to: {}", headers );
+ }
+ catch ( Exception e )
+ {
+ logger.warn( "fail to configure User-Agent: {}", e.getMessage(), e );
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.common.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.maven.wagon.Wagon;
+
+/**
+ * Create a Wagon instance for the given protocol.
+ */
+public interface WagonFactory
+{
+ /**
+ * Create a new Wagon instance for the given protocol.
+ *
+ * @param wagonFactoryRequest
+ *
+ * @return the Wagon instance
+ */
+ Wagon getWagon( WagonFactoryRequest wagonFactoryRequest )
+ throws WagonFactoryException;
+}
--- /dev/null
+package org.apache.archiva.maven.common.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4-M1
+ */
+public class WagonFactoryException
+ extends Exception
+{
+ public WagonFactoryException( String message, Throwable e )
+ {
+ super( message, e );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.common.proxy;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.proxy.model.NetworkProxy;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4-M4
+ */
+public class WagonFactoryRequest
+{
+
+ public static final String USER_AGENT_SYSTEM_PROPERTY = "archiva.userAgent";
+
+ private static String DEFAULT_USER_AGENT = "Java-Archiva";
+
+ /**
+ * the protocol to find the Wagon for, which must be prefixed with <code>wagon#</code>, for example
+ * <code>wagon#http</code>. <b>to have a wagon supporting ntlm add -ntlm</b>
+ */
+ private String protocol;
+
+ private Map<String, String> headers = new HashMap<>();
+
+ private String userAgent = DEFAULT_USER_AGENT;
+
+ static {
+ if ( StringUtils.isNotBlank( System.getProperty( USER_AGENT_SYSTEM_PROPERTY))) {
+ DEFAULT_USER_AGENT=System.getProperty(USER_AGENT_SYSTEM_PROPERTY);
+ }
+ }
+
+ private NetworkProxy networkProxy;
+
+ public WagonFactoryRequest()
+ {
+ // no op
+ }
+
+ public WagonFactoryRequest( String protocol, Map<String, String> headers )
+ {
+ this.protocol = protocol;
+ this.headers = headers;
+ }
+
+ public String getProtocol()
+ {
+ return protocol;
+ }
+
+ public void setProtocol( String protocol )
+ {
+ this.protocol = protocol;
+ }
+
+ public WagonFactoryRequest protocol( String protocol )
+ {
+ this.protocol = protocol;
+ return this;
+ }
+
+ public Map<String, String> getHeaders()
+ {
+ if ( this.headers == null )
+ {
+ this.headers = new HashMap<>();
+ }
+ return headers;
+ }
+
+ public void setHeaders( Map<String, String> headers )
+ {
+ this.headers = headers;
+ }
+
+ public WagonFactoryRequest headers( Map<String, String> headers )
+ {
+ this.headers = headers;
+ return this;
+ }
+
+ public String getUserAgent()
+ {
+ return userAgent;
+ }
+
+ public void setUserAgent( String userAgent )
+ {
+ this.userAgent = userAgent;
+ }
+
+ public WagonFactoryRequest userAgent( String userAgent )
+ {
+ this.userAgent = userAgent;
+ return this;
+ }
+
+ public NetworkProxy getNetworkProxy()
+ {
+ return networkProxy;
+ }
+
+ public void setNetworkProxy( NetworkProxy networkProxy )
+ {
+ this.networkProxy = networkProxy;
+ }
+
+ public WagonFactoryRequest networkProxy( NetworkProxy networkProxy )
+ {
+ this.networkProxy = networkProxy;
+ return this;
+ }
+
+ @Override
+ public boolean equals( Object o )
+ {
+ if ( this == o )
+ {
+ return true;
+ }
+ if ( !( o instanceof WagonFactoryRequest ) )
+ {
+ return false;
+ }
+
+ WagonFactoryRequest that = (WagonFactoryRequest) o;
+
+ if ( protocol != null ? !protocol.equals( that.protocol ) : that.protocol != null )
+ {
+ return false;
+ }
+ if ( userAgent != null ? !userAgent.equals( that.userAgent ) : that.userAgent != null )
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ int result = protocol != null ? protocol.hashCode() : 0;
+ result = 31 * result + ( userAgent != null ? userAgent.hashCode() : 0 );
+ return result;
+ }
+
+ @Override
+ public String toString()
+ {
+ return "WagonFactoryRequest{" +
+ "protocol='" + protocol + '\'' +
+ ", headers=" + headers +
+ ", userAgent='" + userAgent + '\'' +
+ ", networkProxy=" + networkProxy +
+ '}';
+ }
+}
+++ /dev/null
-package org.apache.archiva.maven.proxy;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.maven.wagon.events.TransferEvent;
-import org.apache.maven.wagon.events.TransferListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author Olivier Lamy
- * @since 1.4-M1
- */
-public class DebugTransferListener
- implements TransferListener
-{
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- @Override
- public void transferInitiated( TransferEvent transferEvent )
- {
- log.debug( "transferInitiated for resource {} on repository url {}", transferEvent.getResource().getName(),
- transferEvent.getWagon().getRepository().getUrl() );
- }
-
- @Override
- public void transferStarted( TransferEvent transferEvent )
- {
- log.debug( "transferStarted for resource {} on repository url {}", transferEvent.getResource().getName(),
- transferEvent.getWagon().getRepository().getUrl() );
- }
-
- @Override
- public void transferProgress( TransferEvent transferEvent, byte[] bytes, int i )
- {
- log.debug( "transferProgress for resource {} on repository url {}", transferEvent.getResource().getName(),
- transferEvent.getWagon().getRepository().getUrl() );
- }
-
- @Override
- public void transferCompleted( TransferEvent transferEvent )
- {
- log.debug( "transferCompleted for resource {} on repository url {}", transferEvent.getResource().getName(),
- transferEvent.getWagon().getRepository().getUrl() );
- }
-
- @Override
- public void transferError( TransferEvent transferEvent )
- {
- log.debug( "transferError for resource {} on repository url {}", transferEvent.getResource().getName(),
- transferEvent.getWagon().getRepository().getUrl(), transferEvent.getException() );
- }
-
- @Override
- public void debug( String s )
- {
- log.debug( "wagon debug {}", s );
- }
-}
+++ /dev/null
-package org.apache.archiva.maven.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.maven.wagon.Wagon;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.BeansException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.stereotype.Service;
-
-import javax.inject.Inject;
-import java.lang.reflect.Method;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * @author Olivier Lamy
- * @since 1.4-M1
- */
-@Service ("wagonFactory")
-public class DefaultWagonFactory
- implements WagonFactory
-{
-
- private ApplicationContext applicationContext;
-
- private Logger logger = LoggerFactory.getLogger( getClass() );
-
- private DebugTransferListener debugTransferListener = new DebugTransferListener();
-
- @Inject
- public DefaultWagonFactory( ApplicationContext applicationContext )
- {
- this.applicationContext = applicationContext;
- }
-
- @Override
- public Wagon getWagon( WagonFactoryRequest wagonFactoryRequest )
- throws WagonFactoryException
- {
- try
- {
- String protocol = StringUtils.startsWith( wagonFactoryRequest.getProtocol(), "wagon#" )
- ? wagonFactoryRequest.getProtocol()
- : "wagon#" + wagonFactoryRequest.getProtocol();
-
- // if it's a ntlm proxy we have to lookup the wagon light which support thats
- // wagon http client doesn't support that
- if ( wagonFactoryRequest.getNetworkProxy() != null && wagonFactoryRequest.getNetworkProxy().isUseNtlm() )
- {
- protocol = protocol + "-ntlm";
- }
-
- Wagon wagon = applicationContext.getBean( protocol, Wagon.class );
- wagon.addTransferListener( debugTransferListener );
- configureUserAgent( wagon, wagonFactoryRequest );
- return wagon;
- }
- catch ( BeansException e )
- {
- throw new WagonFactoryException( e.getMessage(), e );
- }
- }
-
- protected void configureUserAgent( Wagon wagon, WagonFactoryRequest wagonFactoryRequest )
- {
- try
- {
- Class<? extends Wagon> clazz = wagon.getClass();
- Method getHttpHeaders = clazz.getMethod( "getHttpHeaders" );
-
- Properties headers = (Properties) getHttpHeaders.invoke( wagon );
- if ( headers == null )
- {
- headers = new Properties();
- }
-
- headers.put( "User-Agent", wagonFactoryRequest.getUserAgent() );
-
- if ( !wagonFactoryRequest.getHeaders().isEmpty() )
- {
- for ( Map.Entry<String, String> entry : wagonFactoryRequest.getHeaders().entrySet() )
- {
- headers.put( entry.getKey(), entry.getValue() );
- }
- }
-
- Method setHttpHeaders = clazz.getMethod( "setHttpHeaders", new Class[]{ Properties.class } );
- setHttpHeaders.invoke( wagon, headers );
-
- logger.debug( "http headers set to: {}", headers );
- }
- catch ( Exception e )
- {
- logger.warn( "fail to configure User-Agent: {}", e.getMessage(), e );
- }
- }
-}
+++ /dev/null
-package org.apache.archiva.maven.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.maven.wagon.Wagon;
-
-/**
- * Create a Wagon instance for the given protocol.
- */
-public interface WagonFactory
-{
- /**
- * Create a new Wagon instance for the given protocol.
- *
- * @param wagonFactoryRequest
- *
- * @return the Wagon instance
- */
- Wagon getWagon( WagonFactoryRequest wagonFactoryRequest )
- throws WagonFactoryException;
-}
+++ /dev/null
-package org.apache.archiva.maven.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/**
- * @author Olivier Lamy
- * @since 1.4-M1
- */
-public class WagonFactoryException
- extends Exception
-{
- public WagonFactoryException( String message, Throwable e )
- {
- super( message, e );
- }
-}
+++ /dev/null
-package org.apache.archiva.maven.proxy;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.proxy.model.NetworkProxy;
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Olivier Lamy
- * @since 1.4-M4
- */
-public class WagonFactoryRequest
-{
-
- public static final String USER_AGENT_SYSTEM_PROPERTY = "archiva.userAgent";
-
- private static String DEFAULT_USER_AGENT = "Java-Archiva";
-
- /**
- * the protocol to find the Wagon for, which must be prefixed with <code>wagon#</code>, for example
- * <code>wagon#http</code>. <b>to have a wagon supporting ntlm add -ntlm</b>
- */
- private String protocol;
-
- private Map<String, String> headers = new HashMap<>();
-
- private String userAgent = DEFAULT_USER_AGENT;
-
- static {
- if ( StringUtils.isNotBlank( System.getProperty( USER_AGENT_SYSTEM_PROPERTY))) {
- DEFAULT_USER_AGENT=System.getProperty(USER_AGENT_SYSTEM_PROPERTY);
- }
- }
-
- private NetworkProxy networkProxy;
-
- public WagonFactoryRequest()
- {
- // no op
- }
-
- public WagonFactoryRequest( String protocol, Map<String, String> headers )
- {
- this.protocol = protocol;
- this.headers = headers;
- }
-
- public String getProtocol()
- {
- return protocol;
- }
-
- public void setProtocol( String protocol )
- {
- this.protocol = protocol;
- }
-
- public WagonFactoryRequest protocol( String protocol )
- {
- this.protocol = protocol;
- return this;
- }
-
- public Map<String, String> getHeaders()
- {
- if ( this.headers == null )
- {
- this.headers = new HashMap<>();
- }
- return headers;
- }
-
- public void setHeaders( Map<String, String> headers )
- {
- this.headers = headers;
- }
-
- public WagonFactoryRequest headers( Map<String, String> headers )
- {
- this.headers = headers;
- return this;
- }
-
- public String getUserAgent()
- {
- return userAgent;
- }
-
- public void setUserAgent( String userAgent )
- {
- this.userAgent = userAgent;
- }
-
- public WagonFactoryRequest userAgent( String userAgent )
- {
- this.userAgent = userAgent;
- return this;
- }
-
- public NetworkProxy getNetworkProxy()
- {
- return networkProxy;
- }
-
- public void setNetworkProxy( NetworkProxy networkProxy )
- {
- this.networkProxy = networkProxy;
- }
-
- public WagonFactoryRequest networkProxy( NetworkProxy networkProxy )
- {
- this.networkProxy = networkProxy;
- return this;
- }
-
- @Override
- public boolean equals( Object o )
- {
- if ( this == o )
- {
- return true;
- }
- if ( !( o instanceof WagonFactoryRequest ) )
- {
- return false;
- }
-
- WagonFactoryRequest that = (WagonFactoryRequest) o;
-
- if ( protocol != null ? !protocol.equals( that.protocol ) : that.protocol != null )
- {
- return false;
- }
- if ( userAgent != null ? !userAgent.equals( that.userAgent ) : that.userAgent != null )
- {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int result = protocol != null ? protocol.hashCode() : 0;
- result = 31 * result + ( userAgent != null ? userAgent.hashCode() : 0 );
- return result;
- }
-
- @Override
- public String toString()
- {
- return "WagonFactoryRequest{" +
- "protocol='" + protocol + '\'' +
- ", headers=" + headers +
- ", userAgent='" + userAgent + '\'' +
- ", networkProxy=" + networkProxy +
- '}';
- }
-}
default-lazy-init="true">
<context:annotation-config/>
- <context:component-scan base-package="org.apache.archiva.maven.proxy"/>
+ <context:component-scan base-package="org.apache.archiva.maven.common.proxy"/>
</beans>
\ No newline at end of file
import org.apache.archiva.indexer.IndexUpdateFailedException;
import org.apache.archiva.indexer.UnsupportedBaseContextException;
import org.apache.archiva.proxy.ProxyRegistry;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryException;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryException;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.ManagedRepository;
default-lazy-init="false">
<context:annotation-config/>
- <context:component-scan base-package="org.apache.archiva.indexer.maven,org.apache.archiva.repository,org.apache.archiva.repository.content.maven2" />
+ <context:component-scan base-package="org.apache.archiva.maven.indexer,org.apache.archiva.repository" />
<bean name="wagon#file" scope="prototype" class="org.apache.maven.wagon.providers.file.FileWagon"/>
--- /dev/null
+package org.apache.archiva.maven.model;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.xml.bind.annotation.XmlRootElement;
+import java.io.Serializable;
+import java.util.List;
+
+@XmlRootElement( name = "artifact" )
+public class Artifact
+ implements Serializable
+{
+ // The (optional) context for this result.
+ private String context;
+
+ // Basic hit, direct to non-artifact resource.
+ private String url;
+
+ // Advanced hit, reference to groupId.
+ private String groupId;
+
+ // Advanced hit, reference to artifactId.
+ private String artifactId;
+
+ private String repositoryId;
+
+ private String version;
+
+ /**
+ * Plugin goal prefix (only if packaging is "maven-plugin")
+ */
+ private String prefix;
+
+ /**
+ * Plugin goals (only if packaging is "maven-plugin")
+ */
+ private List<String> goals;
+
+ /**
+ * contains osgi metadata Bundle-Version if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleVersion;
+
+ /**
+ * contains osgi metadata Bundle-SymbolicName if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleSymbolicName;
+
+ /**
+ * contains osgi metadata Export-Package if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleExportPackage;
+
+ /**
+ * contains osgi metadata Export-Service if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleExportService;
+
+ /**
+ * contains osgi metadata Bundle-Description if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleDescription;
+
+ /**
+ * contains osgi metadata Bundle-Name if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleName;
+
+ /**
+ * contains osgi metadata Bundle-License if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleLicense;
+
+ /**
+ * contains osgi metadata Bundle-DocURL if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleDocUrl;
+
+ /**
+ * contains osgi metadata Import-Package if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleImportPackage;
+
+ /**
+ * contains osgi metadata Require-Bundle if available
+ *
+ * @since 1.4-M1
+ */
+ private String bundleRequireBundle;
+
+ private String classifier;
+
+ private String packaging;
+
+ /**
+ * file extension of the artifact
+ *
+ * @since 1.4-M2
+ */
+ private String fileExtension;
+
+ /**
+ * human readable size : not available for all services
+ *
+ * @since 1.4-M3
+ */
+ private String size;
+
+ /**
+ * @since 1.4-M3
+ */
+ private String type;
+
+
+ /**
+ * @since 1.4-M3
+ */
+ private String path;
+
+ /**
+ * concat of artifactId+'-'+version+'.'+type
+ *
+ * @since 1.4-M3
+ */
+ private String id;
+
+ /**
+ * @since 1.4-M3
+ */
+ private String scope;
+
+
+ public Artifact()
+ {
+ // no op
+ }
+
+ public Artifact( String groupId, String artifactId, String version )
+ {
+ this.artifactId = artifactId;
+ this.groupId = groupId;
+ this.version = version;
+ }
+
+ /**
+ * @since 1.4-M3
+ */
+ public Artifact( String groupId, String artifactId, String version, String scope )
+ {
+ this( groupId, artifactId, version );
+ this.scope = scope;
+ }
+
+ /**
+ * @since 1.4-M3
+ */
+ public Artifact( String groupId, String artifactId, String version, String scope, String classifier )
+ {
+ this( groupId, artifactId, version );
+ this.scope = scope;
+ this.classifier = classifier;
+ }
+
+ public String getGroupId()
+ {
+ return groupId;
+ }
+
+ public String getArtifactId()
+ {
+ return artifactId;
+ }
+
+ public String getVersion()
+ {
+ return version;
+ }
+
+ public String getRepositoryId()
+ {
+ return repositoryId;
+ }
+
+ public void setGroupId( String groupId )
+ {
+ this.groupId = groupId;
+ }
+
+ public void setArtifactId( String artifactId )
+ {
+ this.artifactId = artifactId;
+ }
+
+ public void setVersion( String version )
+ {
+ this.version = version;
+ }
+
+ public void setRepositoryId( String repositoryId )
+ {
+ this.repositoryId = repositoryId;
+ }
+
+ public String getContext()
+ {
+ return context;
+ }
+
+ public void setContext( String context )
+ {
+ this.context = context;
+ }
+
+ public String getUrl()
+ {
+ return url;
+ }
+
+ public void setUrl( String url )
+ {
+ this.url = url;
+ }
+
+ public String getPrefix()
+ {
+ return prefix;
+ }
+
+ public void setPrefix( String prefix )
+ {
+ this.prefix = prefix;
+ }
+
+ public List<String> getGoals()
+ {
+ return goals;
+ }
+
+ public void setGoals( List<String> goals )
+ {
+ this.goals = goals;
+ }
+
+ public String getBundleVersion()
+ {
+ return bundleVersion;
+ }
+
+ public void setBundleVersion( String bundleVersion )
+ {
+ this.bundleVersion = bundleVersion;
+ }
+
+ public String getBundleSymbolicName()
+ {
+ return bundleSymbolicName;
+ }
+
+ public void setBundleSymbolicName( String bundleSymbolicName )
+ {
+ this.bundleSymbolicName = bundleSymbolicName;
+ }
+
+ public String getBundleExportPackage()
+ {
+ return bundleExportPackage;
+ }
+
+ public void setBundleExportPackage( String bundleExportPackage )
+ {
+ this.bundleExportPackage = bundleExportPackage;
+ }
+
+ public String getBundleExportService()
+ {
+ return bundleExportService;
+ }
+
+ public void setBundleExportService( String bundleExportService )
+ {
+ this.bundleExportService = bundleExportService;
+ }
+
+ public String getBundleDescription()
+ {
+ return bundleDescription;
+ }
+
+ public void setBundleDescription( String bundleDescription )
+ {
+ this.bundleDescription = bundleDescription;
+ }
+
+ public String getBundleName()
+ {
+ return bundleName;
+ }
+
+ public void setBundleName( String bundleName )
+ {
+ this.bundleName = bundleName;
+ }
+
+ public String getBundleLicense()
+ {
+ return bundleLicense;
+ }
+
+ public void setBundleLicense( String bundleLicense )
+ {
+ this.bundleLicense = bundleLicense;
+ }
+
+ public String getBundleDocUrl()
+ {
+ return bundleDocUrl;
+ }
+
+ public void setBundleDocUrl( String bundleDocUrl )
+ {
+ this.bundleDocUrl = bundleDocUrl;
+ }
+
+ public String getBundleImportPackage()
+ {
+ return bundleImportPackage;
+ }
+
+ public void setBundleImportPackage( String bundleImportPackage )
+ {
+ this.bundleImportPackage = bundleImportPackage;
+ }
+
+ public String getBundleRequireBundle()
+ {
+ return bundleRequireBundle;
+ }
+
+ public void setBundleRequireBundle( String bundleRequireBundle )
+ {
+ this.bundleRequireBundle = bundleRequireBundle;
+ }
+
+ public String getClassifier()
+ {
+ return classifier;
+ }
+
+ public void setClassifier( String classifier )
+ {
+ this.classifier = classifier;
+ }
+
+
+ public String getPackaging()
+ {
+ return packaging;
+ }
+
+ public void setPackaging( String packaging )
+ {
+ this.packaging = packaging;
+ }
+
+ public String getFileExtension()
+ {
+ return fileExtension;
+ }
+
+ public void setFileExtension( String fileExtension )
+ {
+ this.fileExtension = fileExtension;
+ }
+
+ public String getSize()
+ {
+ return size;
+ }
+
+ public void setSize( String size )
+ {
+ this.size = size;
+ }
+
+ public String getType()
+ {
+ return type;
+ }
+
+ public void setType( String type )
+ {
+ this.type = type;
+ }
+
+ public String getPath()
+ {
+ return path;
+ }
+
+ public void setPath( String path )
+ {
+ this.path = path;
+ }
+
+ public String getId()
+ {
+ return id;
+ }
+
+ public void setId( String id )
+ {
+ this.id = id;
+ }
+
+ public String getScope()
+ {
+ return scope;
+ }
+
+ public void setScope( String scope )
+ {
+ this.scope = scope;
+ }
+
+ @Override
+ public String toString()
+ {
+ final StringBuilder sb = new StringBuilder();
+ sb.append( "Artifact" );
+ sb.append( "{context='" ).append( context ).append( '\'' );
+ sb.append( ", url='" ).append( url ).append( '\'' );
+ sb.append( ", groupId='" ).append( groupId ).append( '\'' );
+ sb.append( ", artifactId='" ).append( artifactId ).append( '\'' );
+ sb.append( ", repositoryId='" ).append( repositoryId ).append( '\'' );
+ sb.append( ", version='" ).append( version ).append( '\'' );
+ sb.append( ", prefix='" ).append( prefix ).append( '\'' );
+ sb.append( ", goals=" ).append( goals );
+ sb.append( ", bundleVersion='" ).append( bundleVersion ).append( '\'' );
+ sb.append( ", bundleSymbolicName='" ).append( bundleSymbolicName ).append( '\'' );
+ sb.append( ", bundleExportPackage='" ).append( bundleExportPackage ).append( '\'' );
+ sb.append( ", bundleExportService='" ).append( bundleExportService ).append( '\'' );
+ sb.append( ", bundleDescription='" ).append( bundleDescription ).append( '\'' );
+ sb.append( ", bundleName='" ).append( bundleName ).append( '\'' );
+ sb.append( ", bundleLicense='" ).append( bundleLicense ).append( '\'' );
+ sb.append( ", bundleDocUrl='" ).append( bundleDocUrl ).append( '\'' );
+ sb.append( ", bundleImportPackage='" ).append( bundleImportPackage ).append( '\'' );
+ sb.append( ", bundleRequireBundle='" ).append( bundleRequireBundle ).append( '\'' );
+ sb.append( ", classifier='" ).append( classifier ).append( '\'' );
+ sb.append( ", packaging='" ).append( packaging ).append( '\'' );
+ sb.append( ", fileExtension='" ).append( fileExtension ).append( '\'' );
+ sb.append( ", size='" ).append( size ).append( '\'' );
+ sb.append( ", type='" ).append( type ).append( '\'' );
+ sb.append( ", path='" ).append( path ).append( '\'' );
+ sb.append( ", id='" ).append( id ).append( '\'' );
+ sb.append( '}' );
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals( Object o )
+ {
+ if ( this == o )
+ {
+ return true;
+ }
+ if ( !( o instanceof Artifact ) )
+ {
+ return false;
+ }
+
+ Artifact artifact = (Artifact) o;
+
+ if ( !artifactId.equals( artifact.artifactId ) )
+ {
+ return false;
+ }
+ if ( bundleDescription != null
+ ? !bundleDescription.equals( artifact.bundleDescription )
+ : artifact.bundleDescription != null )
+ {
+ return false;
+ }
+ if ( bundleDocUrl != null ? !bundleDocUrl.equals( artifact.bundleDocUrl ) : artifact.bundleDocUrl != null )
+ {
+ return false;
+ }
+ if ( bundleExportPackage != null
+ ? !bundleExportPackage.equals( artifact.bundleExportPackage )
+ : artifact.bundleExportPackage != null )
+ {
+ return false;
+ }
+ if ( bundleExportService != null
+ ? !bundleExportService.equals( artifact.bundleExportService )
+ : artifact.bundleExportService != null )
+ {
+ return false;
+ }
+ if ( bundleImportPackage != null
+ ? !bundleImportPackage.equals( artifact.bundleImportPackage )
+ : artifact.bundleImportPackage != null )
+ {
+ return false;
+ }
+ if ( bundleLicense != null ? !bundleLicense.equals( artifact.bundleLicense ) : artifact.bundleLicense != null )
+ {
+ return false;
+ }
+ if ( bundleName != null ? !bundleName.equals( artifact.bundleName ) : artifact.bundleName != null )
+ {
+ return false;
+ }
+ if ( bundleRequireBundle != null
+ ? !bundleRequireBundle.equals( artifact.bundleRequireBundle )
+ : artifact.bundleRequireBundle != null )
+ {
+ return false;
+ }
+ if ( bundleSymbolicName != null
+ ? !bundleSymbolicName.equals( artifact.bundleSymbolicName )
+ : artifact.bundleSymbolicName != null )
+ {
+ return false;
+ }
+ if ( bundleVersion != null ? !bundleVersion.equals( artifact.bundleVersion ) : artifact.bundleVersion != null )
+ {
+ return false;
+ }
+ if ( classifier != null ? !classifier.equals( artifact.classifier ) : artifact.classifier != null )
+ {
+ return false;
+ }
+ if ( context != null ? !context.equals( artifact.context ) : artifact.context != null )
+ {
+ return false;
+ }
+ if ( fileExtension != null ? !fileExtension.equals( artifact.fileExtension ) : artifact.fileExtension != null )
+ {
+ return false;
+ }
+ if ( goals != null ? !goals.equals( artifact.goals ) : artifact.goals != null )
+ {
+ return false;
+ }
+ if ( !groupId.equals( artifact.groupId ) )
+ {
+ return false;
+ }
+ if ( id != null ? !id.equals( artifact.id ) : artifact.id != null )
+ {
+ return false;
+ }
+ if ( packaging != null ? !packaging.equals( artifact.packaging ) : artifact.packaging != null )
+ {
+ return false;
+ }
+ if ( path != null ? !path.equals( artifact.path ) : artifact.path != null )
+ {
+ return false;
+ }
+ if ( prefix != null ? !prefix.equals( artifact.prefix ) : artifact.prefix != null )
+ {
+ return false;
+ }
+ if ( repositoryId != null ? !repositoryId.equals( artifact.repositoryId ) : artifact.repositoryId != null )
+ {
+ return false;
+ }
+ if ( scope != null ? !scope.equals( artifact.scope ) : artifact.scope != null )
+ {
+ return false;
+ }
+ if ( size != null ? !size.equals( artifact.size ) : artifact.size != null )
+ {
+ return false;
+ }
+ if ( type != null ? !type.equals( artifact.type ) : artifact.type != null )
+ {
+ return false;
+ }
+ if ( url != null ? !url.equals( artifact.url ) : artifact.url != null )
+ {
+ return false;
+ }
+ if ( !version.equals( artifact.version ) )
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ int result = context != null ? context.hashCode() : 0;
+ result = 31 * result + ( url != null ? url.hashCode() : 0 );
+ result = 31 * result + groupId.hashCode();
+ result = 31 * result + artifactId.hashCode();
+ result = 31 * result + ( repositoryId != null ? repositoryId.hashCode() : 0 );
+ result = 31 * result + version.hashCode();
+ result = 31 * result + ( prefix != null ? prefix.hashCode() : 0 );
+ result = 31 * result + ( goals != null ? goals.hashCode() : 0 );
+ result = 31 * result + ( bundleVersion != null ? bundleVersion.hashCode() : 0 );
+ result = 31 * result + ( bundleSymbolicName != null ? bundleSymbolicName.hashCode() : 0 );
+ result = 31 * result + ( bundleExportPackage != null ? bundleExportPackage.hashCode() : 0 );
+ result = 31 * result + ( bundleExportService != null ? bundleExportService.hashCode() : 0 );
+ result = 31 * result + ( bundleDescription != null ? bundleDescription.hashCode() : 0 );
+ result = 31 * result + ( bundleName != null ? bundleName.hashCode() : 0 );
+ result = 31 * result + ( bundleLicense != null ? bundleLicense.hashCode() : 0 );
+ result = 31 * result + ( bundleDocUrl != null ? bundleDocUrl.hashCode() : 0 );
+ result = 31 * result + ( bundleImportPackage != null ? bundleImportPackage.hashCode() : 0 );
+ result = 31 * result + ( bundleRequireBundle != null ? bundleRequireBundle.hashCode() : 0 );
+ result = 31 * result + ( classifier != null ? classifier.hashCode() : 0 );
+ result = 31 * result + ( packaging != null ? packaging.hashCode() : 0 );
+ result = 31 * result + ( fileExtension != null ? fileExtension.hashCode() : 0 );
+ result = 31 * result + ( size != null ? size.hashCode() : 0 );
+ result = 31 * result + ( type != null ? type.hashCode() : 0 );
+ result = 31 * result + ( path != null ? path.hashCode() : 0 );
+ result = 31 * result + ( id != null ? id.hashCode() : 0 );
+ result = 31 * result + ( scope != null ? scope.hashCode() : 0 );
+ return result;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.model;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlTransient;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ */
+@XmlRootElement( name = "treeEntry" )
+public class TreeEntry
+ implements Serializable
+{
+
+ private List<TreeEntry> childs = new ArrayList<>();
+
+ private Artifact artifact;
+
+ private TreeEntry parent;
+
+ public TreeEntry()
+ {
+ // no op
+ }
+
+ public TreeEntry( Artifact artifact )
+ {
+ this.artifact = artifact;
+ }
+
+
+ public Artifact getArtifact()
+ {
+ return artifact;
+ }
+
+ public void setArtifact( Artifact artifact )
+ {
+ this.artifact = artifact;
+ }
+
+ public List<TreeEntry> getChilds()
+ {
+ return childs;
+ }
+
+ public void setChilds( List<TreeEntry> childs )
+ {
+ this.childs = childs;
+ }
+
+ @XmlTransient
+ public TreeEntry getParent()
+ {
+ return parent;
+ }
+
+ public void setParent( TreeEntry parent )
+ {
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean equals( Object o )
+ {
+ if ( this == o )
+ {
+ return true;
+ }
+ if ( !( o instanceof TreeEntry ) )
+ {
+ return false;
+ }
+
+ TreeEntry treeEntry = (TreeEntry) o;
+
+ if ( artifact != null ? !artifact.equals( treeEntry.artifact ) : treeEntry.artifact != null )
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return artifact != null ? artifact.hashCode() : 0;
+ }
+}
+++ /dev/null
-package org.apache.archiva.maven2.model;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.List;
-
-@XmlRootElement( name = "artifact" )
-public class Artifact
- implements Serializable
-{
- // The (optional) context for this result.
- private String context;
-
- // Basic hit, direct to non-artifact resource.
- private String url;
-
- // Advanced hit, reference to groupId.
- private String groupId;
-
- // Advanced hit, reference to artifactId.
- private String artifactId;
-
- private String repositoryId;
-
- private String version;
-
- /**
- * Plugin goal prefix (only if packaging is "maven-plugin")
- */
- private String prefix;
-
- /**
- * Plugin goals (only if packaging is "maven-plugin")
- */
- private List<String> goals;
-
- /**
- * contains osgi metadata Bundle-Version if available
- *
- * @since 1.4-M1
- */
- private String bundleVersion;
-
- /**
- * contains osgi metadata Bundle-SymbolicName if available
- *
- * @since 1.4-M1
- */
- private String bundleSymbolicName;
-
- /**
- * contains osgi metadata Export-Package if available
- *
- * @since 1.4-M1
- */
- private String bundleExportPackage;
-
- /**
- * contains osgi metadata Export-Service if available
- *
- * @since 1.4-M1
- */
- private String bundleExportService;
-
- /**
- * contains osgi metadata Bundle-Description if available
- *
- * @since 1.4-M1
- */
- private String bundleDescription;
-
- /**
- * contains osgi metadata Bundle-Name if available
- *
- * @since 1.4-M1
- */
- private String bundleName;
-
- /**
- * contains osgi metadata Bundle-License if available
- *
- * @since 1.4-M1
- */
- private String bundleLicense;
-
- /**
- * contains osgi metadata Bundle-DocURL if available
- *
- * @since 1.4-M1
- */
- private String bundleDocUrl;
-
- /**
- * contains osgi metadata Import-Package if available
- *
- * @since 1.4-M1
- */
- private String bundleImportPackage;
-
- /**
- * contains osgi metadata Require-Bundle if available
- *
- * @since 1.4-M1
- */
- private String bundleRequireBundle;
-
- private String classifier;
-
- private String packaging;
-
- /**
- * file extension of the artifact
- *
- * @since 1.4-M2
- */
- private String fileExtension;
-
- /**
- * human readable size : not available for all services
- *
- * @since 1.4-M3
- */
- private String size;
-
- /**
- * @since 1.4-M3
- */
- private String type;
-
-
- /**
- * @since 1.4-M3
- */
- private String path;
-
- /**
- * concat of artifactId+'-'+version+'.'+type
- *
- * @since 1.4-M3
- */
- private String id;
-
- /**
- * @since 1.4-M3
- */
- private String scope;
-
-
- public Artifact()
- {
- // no op
- }
-
- public Artifact( String groupId, String artifactId, String version )
- {
- this.artifactId = artifactId;
- this.groupId = groupId;
- this.version = version;
- }
-
- /**
- * @since 1.4-M3
- */
- public Artifact( String groupId, String artifactId, String version, String scope )
- {
- this( groupId, artifactId, version );
- this.scope = scope;
- }
-
- /**
- * @since 1.4-M3
- */
- public Artifact( String groupId, String artifactId, String version, String scope, String classifier )
- {
- this( groupId, artifactId, version );
- this.scope = scope;
- this.classifier = classifier;
- }
-
- public String getGroupId()
- {
- return groupId;
- }
-
- public String getArtifactId()
- {
- return artifactId;
- }
-
- public String getVersion()
- {
- return version;
- }
-
- public String getRepositoryId()
- {
- return repositoryId;
- }
-
- public void setGroupId( String groupId )
- {
- this.groupId = groupId;
- }
-
- public void setArtifactId( String artifactId )
- {
- this.artifactId = artifactId;
- }
-
- public void setVersion( String version )
- {
- this.version = version;
- }
-
- public void setRepositoryId( String repositoryId )
- {
- this.repositoryId = repositoryId;
- }
-
- public String getContext()
- {
- return context;
- }
-
- public void setContext( String context )
- {
- this.context = context;
- }
-
- public String getUrl()
- {
- return url;
- }
-
- public void setUrl( String url )
- {
- this.url = url;
- }
-
- public String getPrefix()
- {
- return prefix;
- }
-
- public void setPrefix( String prefix )
- {
- this.prefix = prefix;
- }
-
- public List<String> getGoals()
- {
- return goals;
- }
-
- public void setGoals( List<String> goals )
- {
- this.goals = goals;
- }
-
- public String getBundleVersion()
- {
- return bundleVersion;
- }
-
- public void setBundleVersion( String bundleVersion )
- {
- this.bundleVersion = bundleVersion;
- }
-
- public String getBundleSymbolicName()
- {
- return bundleSymbolicName;
- }
-
- public void setBundleSymbolicName( String bundleSymbolicName )
- {
- this.bundleSymbolicName = bundleSymbolicName;
- }
-
- public String getBundleExportPackage()
- {
- return bundleExportPackage;
- }
-
- public void setBundleExportPackage( String bundleExportPackage )
- {
- this.bundleExportPackage = bundleExportPackage;
- }
-
- public String getBundleExportService()
- {
- return bundleExportService;
- }
-
- public void setBundleExportService( String bundleExportService )
- {
- this.bundleExportService = bundleExportService;
- }
-
- public String getBundleDescription()
- {
- return bundleDescription;
- }
-
- public void setBundleDescription( String bundleDescription )
- {
- this.bundleDescription = bundleDescription;
- }
-
- public String getBundleName()
- {
- return bundleName;
- }
-
- public void setBundleName( String bundleName )
- {
- this.bundleName = bundleName;
- }
-
- public String getBundleLicense()
- {
- return bundleLicense;
- }
-
- public void setBundleLicense( String bundleLicense )
- {
- this.bundleLicense = bundleLicense;
- }
-
- public String getBundleDocUrl()
- {
- return bundleDocUrl;
- }
-
- public void setBundleDocUrl( String bundleDocUrl )
- {
- this.bundleDocUrl = bundleDocUrl;
- }
-
- public String getBundleImportPackage()
- {
- return bundleImportPackage;
- }
-
- public void setBundleImportPackage( String bundleImportPackage )
- {
- this.bundleImportPackage = bundleImportPackage;
- }
-
- public String getBundleRequireBundle()
- {
- return bundleRequireBundle;
- }
-
- public void setBundleRequireBundle( String bundleRequireBundle )
- {
- this.bundleRequireBundle = bundleRequireBundle;
- }
-
- public String getClassifier()
- {
- return classifier;
- }
-
- public void setClassifier( String classifier )
- {
- this.classifier = classifier;
- }
-
-
- public String getPackaging()
- {
- return packaging;
- }
-
- public void setPackaging( String packaging )
- {
- this.packaging = packaging;
- }
-
- public String getFileExtension()
- {
- return fileExtension;
- }
-
- public void setFileExtension( String fileExtension )
- {
- this.fileExtension = fileExtension;
- }
-
- public String getSize()
- {
- return size;
- }
-
- public void setSize( String size )
- {
- this.size = size;
- }
-
- public String getType()
- {
- return type;
- }
-
- public void setType( String type )
- {
- this.type = type;
- }
-
- public String getPath()
- {
- return path;
- }
-
- public void setPath( String path )
- {
- this.path = path;
- }
-
- public String getId()
- {
- return id;
- }
-
- public void setId( String id )
- {
- this.id = id;
- }
-
- public String getScope()
- {
- return scope;
- }
-
- public void setScope( String scope )
- {
- this.scope = scope;
- }
-
- @Override
- public String toString()
- {
- final StringBuilder sb = new StringBuilder();
- sb.append( "Artifact" );
- sb.append( "{context='" ).append( context ).append( '\'' );
- sb.append( ", url='" ).append( url ).append( '\'' );
- sb.append( ", groupId='" ).append( groupId ).append( '\'' );
- sb.append( ", artifactId='" ).append( artifactId ).append( '\'' );
- sb.append( ", repositoryId='" ).append( repositoryId ).append( '\'' );
- sb.append( ", version='" ).append( version ).append( '\'' );
- sb.append( ", prefix='" ).append( prefix ).append( '\'' );
- sb.append( ", goals=" ).append( goals );
- sb.append( ", bundleVersion='" ).append( bundleVersion ).append( '\'' );
- sb.append( ", bundleSymbolicName='" ).append( bundleSymbolicName ).append( '\'' );
- sb.append( ", bundleExportPackage='" ).append( bundleExportPackage ).append( '\'' );
- sb.append( ", bundleExportService='" ).append( bundleExportService ).append( '\'' );
- sb.append( ", bundleDescription='" ).append( bundleDescription ).append( '\'' );
- sb.append( ", bundleName='" ).append( bundleName ).append( '\'' );
- sb.append( ", bundleLicense='" ).append( bundleLicense ).append( '\'' );
- sb.append( ", bundleDocUrl='" ).append( bundleDocUrl ).append( '\'' );
- sb.append( ", bundleImportPackage='" ).append( bundleImportPackage ).append( '\'' );
- sb.append( ", bundleRequireBundle='" ).append( bundleRequireBundle ).append( '\'' );
- sb.append( ", classifier='" ).append( classifier ).append( '\'' );
- sb.append( ", packaging='" ).append( packaging ).append( '\'' );
- sb.append( ", fileExtension='" ).append( fileExtension ).append( '\'' );
- sb.append( ", size='" ).append( size ).append( '\'' );
- sb.append( ", type='" ).append( type ).append( '\'' );
- sb.append( ", path='" ).append( path ).append( '\'' );
- sb.append( ", id='" ).append( id ).append( '\'' );
- sb.append( '}' );
- return sb.toString();
- }
-
- @Override
- public boolean equals( Object o )
- {
- if ( this == o )
- {
- return true;
- }
- if ( !( o instanceof Artifact ) )
- {
- return false;
- }
-
- Artifact artifact = (Artifact) o;
-
- if ( !artifactId.equals( artifact.artifactId ) )
- {
- return false;
- }
- if ( bundleDescription != null
- ? !bundleDescription.equals( artifact.bundleDescription )
- : artifact.bundleDescription != null )
- {
- return false;
- }
- if ( bundleDocUrl != null ? !bundleDocUrl.equals( artifact.bundleDocUrl ) : artifact.bundleDocUrl != null )
- {
- return false;
- }
- if ( bundleExportPackage != null
- ? !bundleExportPackage.equals( artifact.bundleExportPackage )
- : artifact.bundleExportPackage != null )
- {
- return false;
- }
- if ( bundleExportService != null
- ? !bundleExportService.equals( artifact.bundleExportService )
- : artifact.bundleExportService != null )
- {
- return false;
- }
- if ( bundleImportPackage != null
- ? !bundleImportPackage.equals( artifact.bundleImportPackage )
- : artifact.bundleImportPackage != null )
- {
- return false;
- }
- if ( bundleLicense != null ? !bundleLicense.equals( artifact.bundleLicense ) : artifact.bundleLicense != null )
- {
- return false;
- }
- if ( bundleName != null ? !bundleName.equals( artifact.bundleName ) : artifact.bundleName != null )
- {
- return false;
- }
- if ( bundleRequireBundle != null
- ? !bundleRequireBundle.equals( artifact.bundleRequireBundle )
- : artifact.bundleRequireBundle != null )
- {
- return false;
- }
- if ( bundleSymbolicName != null
- ? !bundleSymbolicName.equals( artifact.bundleSymbolicName )
- : artifact.bundleSymbolicName != null )
- {
- return false;
- }
- if ( bundleVersion != null ? !bundleVersion.equals( artifact.bundleVersion ) : artifact.bundleVersion != null )
- {
- return false;
- }
- if ( classifier != null ? !classifier.equals( artifact.classifier ) : artifact.classifier != null )
- {
- return false;
- }
- if ( context != null ? !context.equals( artifact.context ) : artifact.context != null )
- {
- return false;
- }
- if ( fileExtension != null ? !fileExtension.equals( artifact.fileExtension ) : artifact.fileExtension != null )
- {
- return false;
- }
- if ( goals != null ? !goals.equals( artifact.goals ) : artifact.goals != null )
- {
- return false;
- }
- if ( !groupId.equals( artifact.groupId ) )
- {
- return false;
- }
- if ( id != null ? !id.equals( artifact.id ) : artifact.id != null )
- {
- return false;
- }
- if ( packaging != null ? !packaging.equals( artifact.packaging ) : artifact.packaging != null )
- {
- return false;
- }
- if ( path != null ? !path.equals( artifact.path ) : artifact.path != null )
- {
- return false;
- }
- if ( prefix != null ? !prefix.equals( artifact.prefix ) : artifact.prefix != null )
- {
- return false;
- }
- if ( repositoryId != null ? !repositoryId.equals( artifact.repositoryId ) : artifact.repositoryId != null )
- {
- return false;
- }
- if ( scope != null ? !scope.equals( artifact.scope ) : artifact.scope != null )
- {
- return false;
- }
- if ( size != null ? !size.equals( artifact.size ) : artifact.size != null )
- {
- return false;
- }
- if ( type != null ? !type.equals( artifact.type ) : artifact.type != null )
- {
- return false;
- }
- if ( url != null ? !url.equals( artifact.url ) : artifact.url != null )
- {
- return false;
- }
- if ( !version.equals( artifact.version ) )
- {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int result = context != null ? context.hashCode() : 0;
- result = 31 * result + ( url != null ? url.hashCode() : 0 );
- result = 31 * result + groupId.hashCode();
- result = 31 * result + artifactId.hashCode();
- result = 31 * result + ( repositoryId != null ? repositoryId.hashCode() : 0 );
- result = 31 * result + version.hashCode();
- result = 31 * result + ( prefix != null ? prefix.hashCode() : 0 );
- result = 31 * result + ( goals != null ? goals.hashCode() : 0 );
- result = 31 * result + ( bundleVersion != null ? bundleVersion.hashCode() : 0 );
- result = 31 * result + ( bundleSymbolicName != null ? bundleSymbolicName.hashCode() : 0 );
- result = 31 * result + ( bundleExportPackage != null ? bundleExportPackage.hashCode() : 0 );
- result = 31 * result + ( bundleExportService != null ? bundleExportService.hashCode() : 0 );
- result = 31 * result + ( bundleDescription != null ? bundleDescription.hashCode() : 0 );
- result = 31 * result + ( bundleName != null ? bundleName.hashCode() : 0 );
- result = 31 * result + ( bundleLicense != null ? bundleLicense.hashCode() : 0 );
- result = 31 * result + ( bundleDocUrl != null ? bundleDocUrl.hashCode() : 0 );
- result = 31 * result + ( bundleImportPackage != null ? bundleImportPackage.hashCode() : 0 );
- result = 31 * result + ( bundleRequireBundle != null ? bundleRequireBundle.hashCode() : 0 );
- result = 31 * result + ( classifier != null ? classifier.hashCode() : 0 );
- result = 31 * result + ( packaging != null ? packaging.hashCode() : 0 );
- result = 31 * result + ( fileExtension != null ? fileExtension.hashCode() : 0 );
- result = 31 * result + ( size != null ? size.hashCode() : 0 );
- result = 31 * result + ( type != null ? type.hashCode() : 0 );
- result = 31 * result + ( path != null ? path.hashCode() : 0 );
- result = 31 * result + ( id != null ? id.hashCode() : 0 );
- result = 31 * result + ( scope != null ? scope.hashCode() : 0 );
- return result;
- }
-}
+++ /dev/null
-package org.apache.archiva.maven2.model;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlTransient;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Olivier Lamy
- */
-@XmlRootElement( name = "treeEntry" )
-public class TreeEntry
- implements Serializable
-{
-
- private List<TreeEntry> childs = new ArrayList<>();
-
- private Artifact artifact;
-
- private TreeEntry parent;
-
- public TreeEntry()
- {
- // no op
- }
-
- public TreeEntry( Artifact artifact )
- {
- this.artifact = artifact;
- }
-
-
- public Artifact getArtifact()
- {
- return artifact;
- }
-
- public void setArtifact( Artifact artifact )
- {
- this.artifact = artifact;
- }
-
- public List<TreeEntry> getChilds()
- {
- return childs;
- }
-
- public void setChilds( List<TreeEntry> childs )
- {
- this.childs = childs;
- }
-
- @XmlTransient
- public TreeEntry getParent()
- {
- return parent;
- }
-
- public void setParent( TreeEntry parent )
- {
- this.parent = parent;
- }
-
- @Override
- public boolean equals( Object o )
- {
- if ( this == o )
- {
- return true;
- }
- if ( !( o instanceof TreeEntry ) )
- {
- return false;
- }
-
- TreeEntry treeEntry = (TreeEntry) o;
-
- if ( artifact != null ? !artifact.equals( treeEntry.artifact ) : treeEntry.artifact != null )
- {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode()
- {
- return artifact != null ? artifact.hashCode() : 0;
- }
-}
--- /dev/null
+package org.apache.archiva.maven.model;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES 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.module.jaxb.JaxbAnnotationModule;
+import org.json.JSONObject;
+import org.junit.jupiter.api.Test;
+
+import javax.xml.bind.JAXBException;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+
+public class ModelTest
+{
+ @Test
+ void testTreeEntry() throws JAXBException, IOException
+ {
+ TreeEntry parent = new TreeEntry( );
+ TreeEntry entry = new TreeEntry( );
+ entry.setParent( parent );
+ Artifact artifact1 = new Artifact( );
+ artifact1.setGroupId( "test.group" );
+ artifact1.setArtifactId( "artifact1" );
+ artifact1.setVersion( "1.0" );
+ entry.setArtifact( artifact1 );
+
+ TreeEntry child1 = new TreeEntry( );
+ TreeEntry child2 = new TreeEntry( );
+ child1.setParent( entry );
+ child2.setParent( entry );
+ Artifact artifact2 = new Artifact( );
+ artifact2.setGroupId( "test.group" );
+ artifact2.setArtifactId( "artifact1" );
+ artifact2.setVersion( "1.1" );
+ child1.setArtifact( artifact2 );
+ child2.setArtifact( artifact2 );
+ entry.setChilds( Arrays.asList( child1, child2) );
+
+ ObjectMapper objectMapper = new ObjectMapper( );
+ objectMapper.registerModule( new JaxbAnnotationModule( ) );
+ StringWriter sw = new StringWriter( );
+ objectMapper.writeValue( sw, entry );
+
+ JSONObject js = new JSONObject( sw.toString() );
+ assertFalse( js.has( "parent" ) );
+ assertTrue( js.has( "childs" ) );
+ assertEquals(2, js.getJSONArray( "childs" ).length());
+ assertTrue( js.has( "artifact" ) );
+
+ }
+}
+++ /dev/null
-package org.apache.archiva.maven2.model;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES 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.module.jaxb.JaxbAnnotationModule;
-import org.json.JSONObject;
-import org.junit.jupiter.api.Test;
-
-import javax.xml.bind.JAXBException;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.Arrays;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-
-public class ModelTest
-{
- @Test
- void testTreeEntry() throws JAXBException, IOException
- {
- TreeEntry parent = new TreeEntry( );
- TreeEntry entry = new TreeEntry( );
- entry.setParent( parent );
- Artifact artifact1 = new Artifact( );
- artifact1.setGroupId( "test.group" );
- artifact1.setArtifactId( "artifact1" );
- artifact1.setVersion( "1.0" );
- entry.setArtifact( artifact1 );
-
- TreeEntry child1 = new TreeEntry( );
- TreeEntry child2 = new TreeEntry( );
- child1.setParent( entry );
- child2.setParent( entry );
- Artifact artifact2 = new Artifact( );
- artifact2.setGroupId( "test.group" );
- artifact2.setArtifactId( "artifact1" );
- artifact2.setVersion( "1.1" );
- child1.setArtifact( artifact2 );
- child2.setArtifact( artifact2 );
- entry.setChilds( Arrays.asList( child1, child2) );
-
- ObjectMapper objectMapper = new ObjectMapper( );
- objectMapper.registerModule( new JaxbAnnotationModule( ) );
- StringWriter sw = new StringWriter( );
- objectMapper.writeValue( sw, entry );
-
- JSONObject js = new JSONObject( sw.toString() );
- assertFalse( js.has( "parent" ) );
- assertTrue( js.has( "childs" ) );
- assertEquals(2, js.getJSONArray( "childs" ).length());
- assertTrue( js.has( "artifact" ) );
-
- }
-}
</plugin>
</plugins>
</pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <appserver.base>${project.build.directory}/appserver-base</appserver.base>
+ <plexus.home>${project.build.directory}/appserver-base</plexus.home>
+ <derby.system.home>${project.build.directory}/appserver-base</derby.system.home>
+ <redback.jdbc.url>${redbackTestJdbcUrl}</redback.jdbc.url>
+ <redback.jdbc.driver.name>${redbackTestJdbcDriver}</redback.jdbc.driver.name>
+ <archiva.repositorySessionFactory.id>mock</archiva.repositorySessionFactory.id>
+ <openjpa.Log>${openjpa.Log}</openjpa.Log>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
</build>
<!--
* under the License.
*/
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryException;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.DefaultRepositoryProxyHandler;
import org.apache.archiva.proxy.NotFoundException;
import org.apache.archiva.proxy.NotModifiedException;
urlFailureCache.cacheFailure(url);
throw e;
}
- catch (WagonFactoryException e) {
+ catch ( WagonFactoryException e) {
throw new ProxyException(e.getMessage(), e);
} finally {
if (wagon != null) {
default-lazy-init="true">
<context:annotation-config/>
- <context:component-scan base-package="org.apache.archiva.proxy.maven"/>
+ <context:component-scan base-package="org.apache.archiva.maven.proxy"/>
<bean name="wagon#http" scope="prototype" class="org.apache.maven.wagon.providers.http.HttpWagon"/>
--- /dev/null
+package org.apache.archiva.maven.common.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import junit.framework.TestCase;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
+import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
+import org.apache.maven.wagon.Wagon;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+
+import javax.inject.Inject;
+
+/**
+ * Test the WagonFactory works through Spring to be bound into the RepositoryProxyHandler implementation.
+ */
+@RunWith ( ArchivaSpringJUnit4ClassRunner.class )
+@ContextConfiguration ( locations = { "classpath*:/META-INF/spring-context.xml" } )
+public class WagonFactoryTest
+ extends TestCase
+{
+
+ @Inject
+ WagonFactory factory;
+
+ @Test
+ public void testLookupSuccessiveWagons()
+ throws Exception
+ {
+
+ Wagon first = factory.getWagon( new WagonFactoryRequest().protocol( "wagon#file" ) );
+
+ Wagon second = factory.getWagon( new WagonFactoryRequest().protocol( "wagon#file" ) );
+
+ // ensure we support only protocol name too
+ Wagon third = factory.getWagon( new WagonFactoryRequest().protocol( "file" ) );
+
+ assertNotSame( first, second );
+
+ assertNotSame( first, third );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import net.sf.ehcache.CacheManager;
+import org.apache.archiva.configuration.ArchivaConfiguration;
+import org.apache.archiva.configuration.ArchivaRuntimeConfiguration;
+import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
+import org.apache.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
+import org.apache.archiva.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.PolicyOption;
+import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
+import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.proxy.ProxyRegistry;
+import org.apache.archiva.proxy.model.RepositoryProxyHandler;
+import org.apache.archiva.repository.ManagedRepository;
+import org.apache.archiva.repository.ManagedRepositoryContent;
+import org.apache.archiva.repository.RepositoryRegistry;
+import org.apache.archiva.repository.RepositoryType;
+import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
+import org.apache.archiva.repository.base.managed.BasicManagedRepository;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
+import org.apache.maven.wagon.Wagon;
+import org.easymock.EasyMock;
+import org.easymock.IMocksControl;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.context.ContextConfiguration;
+
+import javax.inject.Inject;
+import java.io.BufferedReader;
+import java.io.FileReader;
+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.nio.file.attribute.FileTime;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.*;
+
+/**
+ * AbstractProxyTestCase
+ */
+@RunWith( ArchivaSpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
+public abstract class AbstractProxyTestCase
+{
+ @Inject
+ protected ApplicationContext applicationContext;
+
+ @Inject
+ private ProxyRegistry proxyRegistry;
+
+ @Inject
+ RepositoryRegistry repositoryRegistry;
+
+ @SuppressWarnings( "unused" )
+ @Inject
+ RepositoryHandlerDependencies repositoryHandlerDependencies;
+
+ protected static final String ID_PROXIED1 = "proxied1";
+
+ protected static final String ID_PROXIED1_TARGET = "proxied1-target";
+
+ protected static final String ID_PROXIED2 = "proxied2";
+
+ protected static final String ID_PROXIED2_TARGET = "proxied2-target";
+
+ protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
+
+ protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
+
+ protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
+
+ protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
+
+ protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
+
+ protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
+
+ // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
+
+ protected IMocksControl wagonMockControl;
+
+ protected Wagon wagonMock;
+
+
+ protected RepositoryProxyHandler proxyHandler;
+
+ protected ManagedRepositoryContent managedDefaultRepository;
+
+ protected Path managedDefaultDir;
+
+ protected MockConfiguration config;
+
+ protected Logger log = LoggerFactory.getLogger( getClass() );
+
+ WagonDelegate delegate;
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ config =
+ (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
+
+ config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
+ config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
+ ArchivaRuntimeConfiguration runtimeConfiguration = new ArchivaRuntimeConfiguration();
+ List<String> checksumTypes = new ArrayList<>();
+ checksumTypes.add("md5");
+ checksumTypes.add("sha256");
+ checksumTypes.add("sha1");
+ checksumTypes.add("asc");
+ runtimeConfiguration.setChecksumTypes(checksumTypes);
+ config.getConfiguration().setArchivaRuntimeConfiguration(runtimeConfiguration);
+ repositoryRegistry.setArchivaConfiguration( config );
+
+ // Setup source repository (using default layout)
+ String name = getClass().getSimpleName();
+ Path repoPath = Paths.get("target/test-repository/managed/" + name);
+
+ managedDefaultRepository =
+ createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath.toString(), "default" );
+
+ managedDefaultDir = repoPath.resolve(ID_DEFAULT_MANAGED) ;
+
+ org.apache.archiva.repository.ManagedRepository repoConfig = repositoryRegistry.getManagedRepository(ID_DEFAULT_MANAGED);
+
+ // Setup target (proxied to) repository.
+ saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
+ Paths.get( REPOPATH_PROXIED1 ).toUri().toURL().toExternalForm(), "default" );
+
+ // Setup target (proxied to) repository.
+ saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
+ Paths.get( REPOPATH_PROXIED2 ).toUri().toURL().toExternalForm(), "default" );
+
+
+ repositoryRegistry.reload();
+ repositoryRegistry.putRepository(repoConfig);
+
+
+ // Setup the proxy handler.
+ //proxyHandler = applicationContext.getBean (RepositoryProxyHandler) lookup( RepositoryProxyHandler.class.getName() );
+
+ proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
+ assertNotNull( proxyRegistry );
+ assertTrue(proxyRegistry.getAllHandler( ).get( RepositoryType.MAVEN).contains( proxyHandler ));
+
+
+ // Setup the wagon mock.
+ wagonMockControl = EasyMock.createNiceControl();
+ wagonMock = wagonMockControl.createMock( Wagon.class );
+
+ delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
+
+ delegate.setDelegate( wagonMock );
+
+ CacheManager.getInstance().clearAll();
+
+ log.info( "\n.\\ {}() \\._________________________________________\n", name );
+ }
+
+ protected void assertChecksums( Path expectedFile, String expectedSha1Contents, String expectedMd5Contents )
+ throws Exception
+ {
+ Path sha1File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString()+ ".sha1" );
+ Path md5File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString() + ".md5" );
+
+ if ( expectedSha1Contents == null )
+ {
+ assertFalse( "SHA1 File should NOT exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
+ }
+ else
+ {
+ assertTrue( "SHA1 File should exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
+ String actualSha1Contents = readChecksumFile( sha1File );
+ assertEquals( "SHA1 File contents: " + sha1File.toAbsolutePath(), expectedSha1Contents, actualSha1Contents );
+ }
+
+ if ( expectedMd5Contents == null )
+ {
+ assertFalse( "MD5 File should NOT exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
+ }
+ else
+ {
+ assertTrue( "MD5 File should exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
+ String actualMd5Contents = readChecksumFile( md5File );
+ assertEquals( "MD5 File contents: " + md5File.toAbsolutePath(), expectedMd5Contents, actualMd5Contents );
+ }
+ }
+
+ protected void assertFileEquals( Path expectedFile, Path actualFile, Path sourceFile )
+ throws Exception
+ {
+ assertNotNull( "Expected File should not be null.", expectedFile );
+ assertNotNull( "Actual File should not be null.", actualFile );
+
+ assertTrue( "Check actual file exists.", Files.exists(actualFile) );
+ assertTrue("Check expected file exists", Files.exists(expectedFile));
+ assertTrue( "Check file is the same.", Files.isSameFile( expectedFile,
+ actualFile));
+ String expectedContents =
+ org.apache.commons.io.FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
+ String actualContents =
+ org.apache.commons.io.FileUtils.readFileToString( actualFile.toFile(), Charset.defaultCharset() );
+ assertEquals( "Check file contents.", expectedContents, actualContents );
+ }
+
+ protected void assertNotDownloaded( StorageAsset downloadedFile )
+ {
+ assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ protected void assertNoTempFiles( Path expectedFile )
+ {
+ Path workingDir = expectedFile.getParent();
+ if ( ( workingDir == null ) || !Files.isDirectory( workingDir) )
+ {
+ return;
+ }
+
+ Collection<Path> tmpFiles = null;
+ try {
+ tmpFiles = Files.list(workingDir).filter(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".tmp")).collect(Collectors.toList());
+ } catch (IOException e) {
+ log.error("Could not retrieve tmpFiles {}", workingDir);
+ }
+ if ( tmpFiles!=null && !tmpFiles.isEmpty() )
+ {
+ StringBuilder emsg = new StringBuilder();
+ emsg.append( "Found Temp Files in dir: " ).append( workingDir.toString() );
+ for ( Path tfile : tmpFiles )
+ {
+ emsg.append( "\n " ).append( tfile.getFileName().toString());
+ }
+ fail( emsg.toString() );
+ }
+ }
+
+ /**
+ * A faster recursive copy that omits .svn directories.
+ *
+ * @param sourceDirectory the source directory to copy
+ * @param destDirectory the target location
+ * @throws java.io.IOException if there is a copying problem
+ * @todo get back into plexus-utils, share with converter module
+ */
+ protected void copyDirectoryStructure( Path sourceDirectory, Path destDirectory )
+ throws IOException
+ {
+ if ( !Files.exists(sourceDirectory) )
+ {
+ throw new IOException( "Source directory doesn't exists (" + sourceDirectory.toAbsolutePath() + ")." );
+ }
+
+ Path[] files = Files.list(sourceDirectory).filter(path -> Files.isRegularFile(path)).toArray(Path[]::new);
+
+ String sourcePath = sourceDirectory.toAbsolutePath().toString();
+
+ for ( int i = 0; i < files.length; i++ )
+ {
+ Path file = files[i];
+
+ String dest = file.toAbsolutePath().toString();
+
+ dest = dest.substring( sourcePath.length() + 1 );
+
+ Path destination = destDirectory.resolve( dest );
+
+ if ( Files.isRegularFile(file) )
+ {
+ destination = destination.getParent();
+
+ org.apache.commons.io.FileUtils.copyFile( file.toFile(), destination.resolve( file.getFileName() ).toFile(), false );
+ // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
+ //FileUtils.copyFileToDirectory( file, destination );
+ }
+ else if ( Files.isDirectory(file) )
+ {
+ if ( !".svn".equals( file.getFileName().toString() ) )
+ {
+ if ( !Files.exists(destination))
+ {
+ Files.createDirectories(destination);
+ }
+
+ copyDirectoryStructure( file, destination );
+ }
+ }
+ else
+ {
+ throw new IOException( "Unknown file type: " + file.toAbsolutePath() );
+ }
+ }
+ }
+
+
+ protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
+ throws Exception
+ {
+ ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
+ repositoryRegistry.putRepository(repo);
+ return repositoryRegistry.getManagedRepository(id).getContent();
+ }
+
+ /**
+ * Read the first line from the checksum file, and return it (trimmed).
+ */
+ protected String readChecksumFile( Path checksumFile )
+ throws Exception
+ {
+ FileReader freader = null;
+ BufferedReader buf = null;
+
+ try
+ {
+ freader = new FileReader( checksumFile.toFile() );
+ buf = new BufferedReader( freader );
+ return buf.readLine();
+ }
+ finally
+ {
+ if ( buf != null )
+ {
+ buf.close();
+ }
+
+ if ( freader != null )
+ {
+ freader.close();
+ }
+ }
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
+ {
+ saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
+ CachedFailuresPolicy.NO, disabled );
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
+ PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, boolean disabled )
+ {
+ saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
+ PropagateErrorsDownloadPolicy.QUEUE, disabled );
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
+ PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
+ boolean disabled )
+ {
+ saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
+ errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
+ }
+
+ protected void saveConnector(String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
+ PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
+ PolicyOption errorOnUpdatePolicy, boolean disabled )
+ {
+ ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
+ connectorConfig.setSourceRepoId( sourceRepoId );
+ connectorConfig.setTargetRepoId( targetRepoId );
+ connectorConfig.setProxyId(sourceRepoId);
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy.getId());
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy.getId() );
+ connectorConfig.setDisabled( disabled );
+
+ int count = config.getConfiguration().getProxyConnectors().size();
+ config.getConfiguration().addProxyConnector( connectorConfig );
+
+ // Proper Triggering ...
+ String prefix = "proxyConnectors.proxyConnector(" + count + ")";
+ config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
+ config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
+ config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
+ config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
+ config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
+ config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
+ config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
+ config.triggerChange( prefix + ".policies.propagate-errors",
+ connectorConfig.getPolicy( "propagate-errors", "" ) );
+ config.triggerChange( prefix + ".policies.propagate-errors-on-update",
+ connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
+ }
+
+ protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
+ {
+ ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
+
+ repoConfig.setId( id );
+ repoConfig.setName( name );
+ repoConfig.setLayout( layout );
+
+ repoConfig.setLocation( path );
+
+ int count = config.getConfiguration().getManagedRepositories().size();
+ config.getConfiguration().addManagedRepository( repoConfig );
+
+ String prefix = "managedRepositories.managedRepository(" + count + ")";
+ config.triggerChange( prefix + ".id", repoConfig.getId() );
+ config.triggerChange( prefix + ".name", repoConfig.getName() );
+ config.triggerChange( prefix + ".location", repoConfig.getLocation() );
+ config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
+ }
+
+ protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
+ {
+ RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
+
+ repoConfig.setId( id );
+ repoConfig.setName( name );
+ repoConfig.setLayout( layout );
+ repoConfig.setUrl( url );
+
+ int count = config.getConfiguration().getRemoteRepositories().size();
+ config.getConfiguration().addRemoteRepository( repoConfig );
+
+ String prefix = "remoteRepositories.remoteRepository(" + count + ")";
+ config.triggerChange( prefix + ".id", repoConfig.getId() );
+ config.triggerChange( prefix + ".name", repoConfig.getName() );
+ config.triggerChange( prefix + ".url", repoConfig.getUrl() );
+ config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
+ repositoryRegistry.reload();
+ }
+
+ protected Path saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
+ throws IOException
+ {
+ Path repoLocation = Paths.get( targetPath );
+ org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoLocation );
+ copyDirectoryStructure( Paths.get(originalPath) , repoLocation );
+
+ saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
+
+ return repoLocation;
+ }
+
+
+ /**
+ * Copy the specified resource directory from the src/test/repository/managed/ to
+ * the testable directory under target/test-repository/managed/${testName}/
+ *
+ * @param resourcePath
+ * @throws IOException
+ */
+ protected void setupTestableManagedRepository( String resourcePath )
+ throws IOException
+ {
+ String resourceDir = resourcePath;
+
+ if ( !resourcePath.endsWith( "/" ) )
+ {
+ int idx = resourcePath.lastIndexOf( '/' );
+ resourceDir = resourcePath.substring( 0, idx );
+ }
+
+ Path sourceRepoDir = Paths.get( REPOPATH_DEFAULT_MANAGED );
+ Path sourceDir = sourceRepoDir.resolve(resourceDir );
+
+ Path destRepoDir = managedDefaultDir;
+ Path destDir = destRepoDir.resolve(resourceDir );
+
+ // Cleanout destination dirs.
+ if ( Files.exists(destDir))
+ {
+ org.apache.archiva.common.utils.FileUtils.deleteDirectory( destDir );
+ }
+
+ // Make the destination dir.
+ Files.createDirectories(destDir);
+
+ // Test the source dir.
+ if ( !Files.exists(sourceDir) )
+ {
+ // This is just a warning.
+ log.error( "[WARN] Skipping setup of testable managed repository, source dir does not exist: {}", //
+ sourceDir );
+ }
+ else
+ {
+
+ // Test that the source is a dir.
+ if ( !Files.isDirectory( sourceDir) )
+ {
+ fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
+ }
+
+ // Copy directory structure.
+ copyDirectoryStructure( sourceDir, destDir );
+ }
+ }
+
+ protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile )
+ {
+ setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
+ }
+
+ protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile, long time )
+ {
+ assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
+ assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
+
+ try
+ {
+ Files.setLastModifiedTime( managedFile,
+ FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() + time, TimeUnit.MILLISECONDS ));
+ }
+ catch ( IOException e )
+ {
+ e.printStackTrace( );
+ }
+
+ try
+ {
+ assertTrue( Files.getLastModifiedTime( managedFile).compareTo( Files.getLastModifiedTime( remoteFile )) > 0);
+ }
+ catch ( IOException e )
+ {
+ e.printStackTrace( );
+ }
+ }
+
+ protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile )
+ {
+ setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
+ }
+
+ protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile, long time )
+ {
+ assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
+ assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
+
+ try
+ {
+ Files.setLastModifiedTime( managedFile,
+ FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() - time, TimeUnit.MILLISECONDS ));
+ }
+ catch ( IOException e )
+ {
+ e.printStackTrace( );
+ }
+
+ try
+ {
+ assertTrue( Files.getLastModifiedTime( managedFile ).compareTo(Files.getLastModifiedTime( remoteFile )) < 0 );
+ }
+ catch ( IOException e )
+ {
+ e.printStackTrace( );
+ }
+
+ }
+
+ protected void assertNotModified( Path file, long expectedModificationTime )
+ {
+ try
+ {
+ assertEquals( "File <" + file.toAbsolutePath() + "> not have been modified.", expectedModificationTime,
+ Files.getLastModifiedTime( file ).toMillis());
+ }
+ catch ( IOException e )
+ {
+ e.printStackTrace( );
+ }
+ }
+
+
+ protected void assertNotExistsInManagedDefaultRepo( Path testFile )
+ throws Exception
+ {
+ Path managedDefaultPath = managedDefaultDir;
+
+ assertTrue( "Unit Test Failure: File <" + testFile
+ + "> should be have been defined within the managed default path of <" + managedDefaultPath
+ + ">", testFile.startsWith( managedDefaultPath ) );
+
+ assertFalse( "File < " + testFile + "> should not exist in managed default repository.", Files.exists(testFile) );
+ }
+
+ protected static Date getFutureDate()
+ throws ParseException
+ {
+ Calendar cal = Calendar.getInstance();
+ cal.add( Calendar.YEAR, 1 );
+ return cal.getTime();
+ }
+
+ protected static Date getPastDate()
+ throws ParseException
+ {
+ return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.utils.PathUtil;
+import org.apache.archiva.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.policies.urlcache.UrlFailureCache;
+import org.apache.archiva.repository.content.Artifact;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import javax.inject.Inject;
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * CacheFailuresTransferTest
+ */
+public class CacheFailuresTransferTest
+ extends AbstractProxyTestCase
+{
+ // TODO: test some hard failures (eg TransferFailedException)
+ // TODO: test the various combinations of fetchFrom* (note: need only test when caching is enabled)
+
+ @Inject
+ UrlFailureCache urlFailureCache;
+
+
+ @Test
+ public void testGetWithCacheFailuresOn( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ Path expectedFile = managedDefaultDir.resolve( path );
+ setupTestableManagedRepository( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+ // ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
+ saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "http://bad.machine.com/anotherrepo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
+
+ EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "resource does not exist." ) ).times( 2 );
+
+
+ wagonMockControl.replay( );
+
+ //noinspection UnusedAssignment
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ wagonMockControl.verify( );
+
+ // Second attempt to download same artifact use cache
+ wagonMockControl.reset( );
+ wagonMockControl.replay( );
+ downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+ wagonMockControl.verify( );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetWithCacheFailuresOff( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ Path expectedFile = managedDefaultDir.resolve( path );
+ setupTestableManagedRepository( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
+ saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "http://bad.machine.com/anotherrepo/", "default" );
+
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "resource does not exist." ) ).times( 2 );
+
+ wagonMockControl.replay( );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ wagonMockControl.verify( );
+
+ // Second attempt to download same artifact DOES NOT use cache
+ wagonMockControl.reset( );
+
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "resource does not exist." ) ).times( 2 );
+
+ wagonMockControl.replay( );
+
+ downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ wagonMockControl.verify( );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetWhenInBothProxiedButFirstCacheFailure( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ Files.deleteIfExists( expectedFile );
+ assertFalse( Files.exists( expectedFile ) );
+
+ String url = PathUtil.toUrl( REPOPATH_PROXIED1 + "/" + path );
+
+ // Intentionally set failure on url in proxied1 (for test)
+ UrlFailureCache failurlCache = lookupUrlFailureCache( );
+ failurlCache.cacheFailure( url );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+ saveConnector( ID_DEFAULT_MANAGED, "proxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ // Validate that file actually came from proxied2 (as intended).
+ Path proxied2File = Paths.get( REPOPATH_PROXIED2, path );
+ assertNotNull( downloadedFile );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ protected UrlFailureCache lookupUrlFailureCache( )
+ throws Exception
+ {
+ assertNotNull( "URL Failure Cache cannot be null.", urlFailureCache );
+ return urlFailureCache;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.utils.FileUtils;
+import org.apache.archiva.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.content.Artifact;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+
+/**
+ * ChecksumTransferTest
+ */
+public class ChecksumTransferTest
+ extends AbstractProxyTestCase
+{
+ @Test
+ public void testGetChecksumWhenConnectorIsDisabled( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ org.apache.archiva.common.utils.FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ assertNull( downloadedFile );
+ }
+
+ @Test
+ public void testGetChecksumBothCorrect( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ org.apache.archiva.common.utils.FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "066d76e459f7782c312c31e8a11b3c0f1e3e43a7 *get-checksum-both-right-1.0.jar",
+ "e58f30c6a150a2e843552438d18e15cb *get-checksum-both-right-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1NoMd5( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
+ null );
+ }
+
+ @Test
+ public void testGetChecksumNoSha1CorrectMd5( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
+ }
+
+ @Test
+ public void testGetWithNoChecksumsUsingIgnoredSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumBadSha1BadMd5IgnoredSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetChecksumBadSha1BadMd5FailSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumBadSha1BadMd5FixSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "4ec20a12dc91557330bd0b39d1805be5e329ae56 get-checksum-both-bad-1.0.jar",
+ "a292491a35925465e693a44809a078b5 get-checksum-both-bad-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1BadMd5UsingFailSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumNoSha1CorrectMd5UsingFailSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ // This is a success situation. No SHA1 with a Good MD5.
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
+ }
+
+ @Test
+ public void testGetWithNoChecksumsUsingFailSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1BadMd5UsingIgnoredSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
+ "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1BadMd5UsingFixSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
+ "c35f3b76268b73a4ba617f6f275c49ab get-checksum-sha1-bad-md5-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumNoSha1CorrectMd5UsingFixSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "71f7dc3f72053a3f2d9fdd6fef9db055ef957ffb get-checksum-md5-only-1.0.jar",
+ "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
+ }
+
+ @Test
+ public void testGetWithNoChecksumsUsingFixSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "1f12821c5e43e1a0b76b9564a6ddb0548ccb9486 get-default-layout-1.0.jar",
+ "3f7341545f21226b6f49a3c2704cb9be get-default-layout-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumNotFoundOnRemote( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParent( ) );
+ assertFalse( Files.exists( expectedFile.getParent( ) ) );
+ assertFalse( Files.exists( expectedFile ) );
+
+ saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "http://bad.machine.com/repo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall( ).once( );
+
+ wagonMock.get( EasyMock.eq( path + ".sha1" ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall( ).once( );
+
+ wagonMock.get( EasyMock.eq( path + ".md5" ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "Resource does not exist." ) ).once( );
+
+ wagonMockControl.replay( );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ wagonMockControl.verify( );
+
+ // Do what the mock doesn't do.
+ Path proxyPath = Paths.get( REPOPATH_PROXIED1, path ).toAbsolutePath( );
+ Path localPath = managedDefaultDir.resolve( path ).toAbsolutePath( );
+ Files.copy( proxyPath, localPath, StandardCopyOption.REPLACE_EXISTING );
+ Files.copy( proxyPath.resolveSibling( proxyPath.getFileName( ) + ".sha1" ),
+ localPath.resolveSibling( localPath.getFileName( ) + ".sha1" ), StandardCopyOption.REPLACE_EXISTING );
+
+ // Test results.
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
+ null );
+ }
+
+ @Test
+ public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingIgnoredSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ Path remoteFile = Paths.get( REPOPATH_PROXIED1, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ // There are no hashcodes on the proxy side to download, hence the local ones should remain invalid.
+ assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFailSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ Path remoteFile = Paths.get( REPOPATH_PROXIED1, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ // There are no hashcodes on the proxy side to download.
+ // The FAIL policy will delete the checksums as bad.
+
+ assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFixSetting( )
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+ Path remoteFile = Paths.get( REPOPATH_PROXIED1, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
+
+ Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "96a08dc80a108cba8efd3b20aec91b32a0b2cbd4 get-bad-local-checksum-1.0.jar",
+ "46fdd6ca55bf1d7a7eb0c858f41e0ccd get-bad-local-checksum-1.0.jar" );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.policies.*;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.content.LayoutException;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.apache.maven.wagon.TransferFailedException;
+import org.apache.maven.wagon.authorization.AuthorizationException;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import static org.junit.Assert.*;
+
+/**
+ * ErrorHandlingTest
+ *
+ *
+ */
+public class ErrorHandlingTest
+ extends AbstractProxyTestCase
+{
+ private static final String PATH_IN_BOTH_REMOTES_NOT_LOCAL =
+ "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
+
+ private static final String PATH_IN_BOTH_REMOTES_AND_LOCAL =
+ "org/apache/maven/test/get-on-multiple-repos/1.0/get-on-multiple-repos-1.0.pom";
+
+ private static final String ID_MOCKED_PROXIED1 = "badproxied1";
+
+ private static final String NAME_MOCKED_PROXIED1 = "Bad Proxied 1";
+
+ private static final String ID_MOCKED_PROXIED2 = "badproxied2";
+
+ private static final String NAME_MOCKED_PROXIED2 = "Bad Proxied 2";
+
+ @Test
+ public void testPropagateErrorImmediatelyWithErrorThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorImmediatelyWithNotFoundThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
+ }
+
+ @Test
+ public void testPropagateErrorImmediatelyWithSuccessThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorImmediatelyWithNotFoundThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithErrorThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithSuccessThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithNotFoundThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithErrorThenNotFound()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithErrorThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[]{ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2} );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithNotFoundThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
+ }
+
+ @Test
+ public void testIgnoreErrorWithErrorThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
+ }
+
+ @Test
+ public void testIgnoreErrorWithSuccessThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
+ }
+
+ @Test
+ public void testIgnoreErrorWithNotFoundThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testIgnoreErrorWithErrorThenNotFound()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testIgnoreErrorWithErrorThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysQueueArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysQueueArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysIgnoreArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysIgnoreArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( Files.exists(expectedFile) );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( Files.exists(expectedFile) );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentQueueArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentQueueArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( Files.exists(expectedFile));
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentIgnoreArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentIgnoreArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( Files.exists(expectedFile));
+ }
+
+ // ------------------------------------------
+ // HELPER METHODS
+ // ------------------------------------------
+
+ private void createMockedProxyConnector( String id, String name, PolicyOption errorPolicy )
+ {
+ saveRemoteRepositoryConfig( id, name, "http://bad.machine.com/repo/", "default" );
+ saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
+ CachedFailuresPolicy.NO, errorPolicy, false );
+ }
+
+ private void createMockedProxyConnector( String id, String name, PolicyOption errorPolicy, PolicyOption errorOnUpdatePolicy )
+ {
+ saveRemoteRepositoryConfig( id, name, "http://bad.machine.com/repo/", "default" );
+ saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
+ CachedFailuresPolicy.NO, errorPolicy, errorOnUpdatePolicy, false );
+ }
+
+ private Path setupRepositoriesWithLocalFileNotPresent( String path )
+ throws Exception
+ {
+ setupTestableManagedRepository( path );
+
+ Path file = managedDefaultDir.resolve( path );
+
+ assertNotExistsInManagedDefaultRepo( file );
+
+ return file;
+ }
+
+ private Path setupRepositoriesWithLocalFilePresent( String path )
+ throws Exception
+ {
+ setupTestableManagedRepository( path );
+
+ Path file = managedDefaultDir.resolve( path );
+
+ assertTrue( Files.exists(file) );
+
+ return file;
+ }
+
+ private void simulateGetError( String path, Path expectedFile, Exception throwable )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ));
+ EasyMock.expectLastCall().andThrow(throwable );
+ }
+
+ private void simulateGetIfNewerError( String path, Path expectedFile, TransferFailedException exception )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException, IOException
+ {
+ wagonMock.getIfNewer( EasyMock.eq( path ), EasyMock.anyObject( File.class ), EasyMock.eq( Files.getLastModifiedTime( expectedFile ).toMillis() ));
+ EasyMock.expectLastCall().andThrow( exception );
+ }
+
+ private Path createExpectedTempFile( Path expectedFile )
+ {
+ return managedDefaultDir.resolve(expectedFile.getFileName().toString() + ".tmp" ).toAbsolutePath();
+ }
+
+ private void confirmSingleFailure( String path, String id )
+ throws LayoutException
+ {
+ confirmFailures( path, new String[]{id} );
+ }
+
+ private void confirmFailures( String path, String[] ids )
+ throws LayoutException
+ {
+ wagonMockControl.replay();
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = null;
+ try
+ {
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(),
+ layout.getArtifact( path ) );
+ fail( "Proxy should not have succeeded" );
+ }
+ catch ( ProxyDownloadException e )
+ {
+ assertEquals( ids.length, e.getFailures().size() );
+ for ( String id : ids )
+ {
+ assertTrue( e.getFailures().keySet().contains( id ) );
+ }
+ }
+
+ wagonMockControl.verify();
+
+ assertNotDownloaded( downloadedFile );
+ }
+
+ private void confirmSuccess( String path, Path expectedFile, String basedir )
+ throws Exception
+ {
+ StorageAsset downloadedFile = performDownload( path );
+
+ Path proxied1File = Paths.get( basedir, path );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied1File );
+ }
+
+ private void confirmNotDownloadedNoError( String path )
+ throws Exception
+ {
+ StorageAsset downloadedFile = performDownload( path );
+
+ assertNotDownloaded( downloadedFile );
+ }
+
+ private StorageAsset performDownload( String path )
+ throws ProxyDownloadException, LayoutException
+ {
+ wagonMockControl.replay();
+
+ // Attempt the proxy fetch.
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(),
+ layout.getArtifact( path ) );
+
+ wagonMockControl.verify();
+ return downloadedFile;
+ }
+
+ private static TransferFailedException createTransferException()
+ {
+ return new TransferFailedException( "test download exception" );
+ }
+
+ private static ResourceDoesNotExistException createResourceNotFoundException()
+ {
+ return new ResourceDoesNotExistException( "test download not found" );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.configuration.ArchivaConfiguration;
+import org.apache.archiva.configuration.NetworkProxyConfiguration;
+import org.apache.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
+import org.apache.archiva.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
+import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.proxy.ProxyRegistry;
+import org.apache.archiva.proxy.model.RepositoryProxyHandler;
+import org.apache.archiva.repository.ManagedRepository;
+import org.apache.archiva.repository.ManagedRepositoryContent;
+import org.apache.archiva.repository.RepositoryRegistry;
+import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
+import org.apache.archiva.repository.base.managed.BasicManagedRepository;
+import org.apache.archiva.repository.content.Artifact;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.maven.wagon.Wagon;
+import org.apache.maven.wagon.providers.http.HttpWagon;
+import org.eclipse.jetty.server.Handler;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Request;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.server.handler.AbstractHandler;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.context.ContextConfiguration;
+
+import javax.inject.Inject;
+import javax.servlet.ServletException;
+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 static org.junit.Assert.*;
+
+/**
+ * Integration test for connecting over a HTTP proxy.
+ *
+ *
+ */
+@RunWith( ArchivaSpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
+public class HttpProxyTransferTest
+{
+ private static final String PROXY_ID = "proxy";
+
+ private static final String MANAGED_ID = "default-managed-repository";
+
+ private static final String PROXIED_ID = "proxied1";
+
+ private static final String PROXIED_BASEDIR = "src/test/repositories/proxied1";
+
+ private RepositoryProxyHandler proxyHandler;
+
+ private ManagedRepositoryContent managedDefaultRepository;
+
+ @Inject
+ private ApplicationContext applicationContext;
+
+ @Inject
+ private RepositoryRegistry repositoryRegistry;
+
+ @Inject
+ private ArchivaConfiguration config;
+
+ @Inject
+ private ProxyRegistry proxyRegistry;
+
+ @SuppressWarnings( "unused" )
+ @Inject
+ RepositoryHandlerDependencies repositoryHandlerDependencies;
+
+
+ private Server server;
+
+ protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
+ throws Exception
+ {
+ ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
+ repositoryRegistry.putRepository(repo);
+ return repositoryRegistry.getManagedRepository(id).getContent();
+ }
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
+
+ // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
+ // made a complete mock
+ config.getConfiguration().getProxyConnectors().clear();
+
+ // Setup source repository (using default layout)
+ String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
+
+ Path destRepoDir = Paths.get( repoPath );
+
+ // Cleanout destination dirs.
+ if ( Files.exists(destRepoDir))
+ {
+ FileUtils.deleteDirectory( destRepoDir.toFile() );
+ }
+
+ // Make the destination dir.
+ Files.createDirectories(destRepoDir);
+
+
+ Handler handler = new AbstractHandler()
+ {
+ @Override
+ public void handle( String s, Request request, HttpServletRequest httpServletRequest,
+ HttpServletResponse response )
+ throws IOException, ServletException
+ {
+ response.setContentType( "text/plain" );
+ response.setStatus( HttpServletResponse.SC_OK );
+ response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
+ assertNotNull( request.getHeader( "Proxy-Connection" ) );
+
+ ( (Request) request ).setHandled( true );
+ }
+
+ public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch )
+ throws IOException, ServletException
+ {
+ response.setContentType( "text/plain" );
+ response.setStatus( HttpServletResponse.SC_OK );
+ response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
+ assertNotNull( request.getHeader( "Proxy-Connection" ) );
+
+ ( (Request) request ).setHandled( true );
+ }
+ };
+
+ server = new Server( );
+ ServerConnector serverConnector = new ServerConnector( server, new HttpConnectionFactory());
+ server.addConnector( serverConnector );
+ server.setHandler( handler );
+ server.start();
+
+ int port = serverConnector.getLocalPort();
+
+ NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
+ proxyConfig.setHost( "localhost" );
+ proxyConfig.setPort( port );
+ proxyConfig.setProtocol( "http" );
+ proxyConfig.setId( PROXY_ID );
+ config.getConfiguration().addNetworkProxy( proxyConfig );
+ ( (MockConfiguration) config ).triggerChange("networkProxies.networkProxy(0).host", "localhost");
+
+ // Setup target (proxied to) repository.
+ RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
+
+ repoConfig.setId( PROXIED_ID );
+ repoConfig.setName( "Proxied Repository 1" );
+ repoConfig.setLayout( "default" );
+ repoConfig.setUrl( "http://www.example.com/" );
+
+ config.getConfiguration().addRemoteRepository( repoConfig );
+
+ Wagon wagon = new HttpWagon( );
+ WagonDelegate delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
+ delegate.setDelegate( wagon );
+
+ proxyRegistry.reload();
+ repositoryRegistry.reload();
+
+ managedDefaultRepository = createRepository(MANAGED_ID, "Default Managed Repository", repoPath, "default");
+
+ }
+
+ @After
+ public void tearDown()
+ throws Exception
+ {
+ if (server!=null) {
+ server.stop();
+ }
+ }
+
+ @Test
+ public void testGetOverHttpProxy()
+ throws Exception
+ {
+ assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyHost" , "" ) ));
+ assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyPort", "" ) ) );
+
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ addConnector();
+
+ managedDefaultRepository = repositoryRegistry.getManagedRepository(MANAGED_ID).getContent();
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Path expectedFile = managedDefaultRepository.getRepository().getRoot().resolve( path ).getFilePath();
+ Files.deleteIfExists( expectedFile );
+ Artifact artifact = layout.getArtifact( path );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path sourceFile = Paths.get( PROXIED_BASEDIR, path );
+ assertNotNull( "Expected File should not be null.", expectedFile );
+ assertNotNull( "Actual File should not be null.", downloadedFile );
+
+ assertTrue( "Check actual file exists.", Files.exists(downloadedFile.getFilePath()));
+ assertTrue( "Check filename path is appropriate.", Files.isSameFile( expectedFile, downloadedFile.getFilePath()));
+ assertTrue( "Check file path matches.", Files.isSameFile( expectedFile, downloadedFile.getFilePath()));
+
+ String expectedContents = FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
+ String actualContents = FileUtils.readFileToString( downloadedFile.getFilePath().toFile(), Charset.defaultCharset() );
+ assertEquals( "Check file contents.", expectedContents, actualContents );
+
+ assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyHost", "" ) ) );
+ assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyPort" , "") ) );
+ }
+
+ private void addConnector()
+ {
+ ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
+ connectorConfig.setProxyId( PROXY_ID );
+ connectorConfig.setSourceRepoId( MANAGED_ID );
+ connectorConfig.setTargetRepoId( PROXIED_ID );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, ChecksumPolicy.FIX.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, ReleasesPolicy.ONCE.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, SnapshotsPolicy.ONCE.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, CachedFailuresPolicy.NO.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS,
+ PropagateErrorsDownloadPolicy.QUEUE.getId() );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT.getId() );
+
+ int count = config.getConfiguration().getProxyConnectors().size();
+ config.getConfiguration().addProxyConnector( connectorConfig );
+
+ // Proper Triggering ...
+ String prefix = "proxyConnectors.proxyConnector(" + count + ")";
+ ( (MockConfiguration) config ).triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.content.Artifact;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import java.io.File;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.*;
+
+/**
+ * ManagedDefaultTransferTest
+ */
+public class ManagedDefaultTransferTest
+ extends AbstractProxyTestCase
+{
+ @Test
+ public void testGetDefaultLayoutNotPresentConnectorOffline()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ // Ensure file isn't present first.
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, true );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+ assertNull( "File should not have been downloaded", downloadedFile );
+ }
+
+ @Test
+ public void testGetDefaultLayoutNotPresent()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ // Ensure file isn't present first.
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path sourceFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), sourceFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetDefaultLayoutNotPresentPassthrough()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar.asc";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ // Ensure file isn't present first.
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), path );
+
+ Path sourceFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertNotNull(downloadedFile);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), sourceFile );
+ assertFalse( Files.exists( downloadedFile.getParent().getFilePath().resolve(downloadedFile.getName() + ".sha1" )) );
+ assertFalse( Files.exists(downloadedFile.getParent().getFilePath().resolve(downloadedFile.getName() + ".md5" ) ));
+ assertFalse( Files.exists( downloadedFile.getParent().getFilePath().resolve(downloadedFile.getName() + ".sha256" ) ));
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * The attempt here should result in no file being transferred.
+ * <p/>
+ * The file exists locally, and the policy is ONCE.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentPolicyOnce()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), expectedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * The attempt here should result in no file being transferred.
+ * <p/>
+ * The file exists locally, and the policy is ONCE.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentPassthrough()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar.asc";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
+
+ assertTrue( Files.exists(expectedFile) );
+
+ // Set the managed File to be newer than local.
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+ long originalModificationTime = Files.getLastModifiedTime(expectedFile).toMillis();
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), path );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, originalModificationTime );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * <p>
+ * Request a file, that exists locally, and remotely.
+ * </p>
+ * <p>
+ * All policies are set to IGNORE.
+ * </p>
+ * <p>
+ * Managed file is newer than remote file.
+ * </p>
+ * <p>
+ * Transfer should not have occured, as managed file is newer.
+ * </p>
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentNewerThanRemotePolicyIgnored()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
+
+ // Set the managed File to be newer than local.
+ setManagedNewerThanRemote( expectedFile, remoteFile );
+
+ long originalModificationTime = Files.getLastModifiedTime( expectedFile).toMillis();
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, originalModificationTime );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * <p>
+ * Request a file, that exists locally, and remotely.
+ * </p>
+ * <p>
+ * All policies are set to IGNORE.
+ * </p>
+ * <p>
+ * Managed file is older than Remote file.
+ * </p>
+ * <p>
+ * Transfer should have occured, as managed file is older than remote.
+ * </p>
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentOlderThanRemotePolicyIgnored()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
+
+ // Set the managed file to be newer than remote file.
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * The attempt here should result in file being transferred.
+ * <p/>
+ * The file exists locally, is over 6 years old, and the policy is DAILY.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutRemoteUpdate()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+ Files.setLastModifiedTime( expectedFile, FileTime.from(getPastDate().getTime(), TimeUnit.MILLISECONDS ));
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.DAILY, SnapshotsPolicy.DAILY,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetWhenInBothProxiedRepos()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxied1File = Paths.get(REPOPATH_PROXIED1, path);
+ Path proxied2File = Paths.get(REPOPATH_PROXIED2, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied1File );
+ assertNoTempFiles( expectedFile );
+
+ // TODO: is this check even needed if it passes above?
+ String actualContents = FileUtils.readFileToString( downloadedFile.getFilePath().toFile(), Charset.defaultCharset() );
+ String badContents = FileUtils.readFileToString( proxied2File.toFile(), Charset.defaultCharset() );
+ assertFalse( "Downloaded file contents should not be that of proxy 2",
+ StringUtils.equals( actualContents, badContents ) );
+ }
+
+ @Test
+ public void testGetInSecondProxiedRepo()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxied2File = Paths.get(REPOPATH_PROXIED2, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testNotFoundInAnyProxies()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/does-not-exist/1.0/does-not-exist-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ assertNull( "File returned was: " + downloadedFile + "; should have got a not found exception",
+ downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetInSecondProxiedRepoFirstFails()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "" +
+ "http://bad.machine.com/repo/", "default" );
+
+ wagonMock.get( EasyMock.eq( path), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall().andThrow( new ResourceDoesNotExistException( "transfer failed" ) );
+ wagonMockControl.replay();
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied", false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ // Attempt the proxy fetch.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ wagonMockControl.verify();
+
+ Path proxied2File = Paths.get(REPOPATH_PROXIED2, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetAllRepositoriesFail()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve( path );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
+ saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "http://dead.machine.com/repo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", false );
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied2", false );
+
+ Path tmpFile = expectedFile.getParent().resolve(expectedFile.getFileName() + ".tmp" );
+
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall().andThrow( new ResourceDoesNotExistException( "Can't find resource." ) );
+
+ wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
+ EasyMock.expectLastCall().andThrow( new ResourceDoesNotExistException( "Can't find resource." ) );
+
+ wagonMockControl.replay();
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ assertNotDownloaded( downloadedFile );
+
+ wagonMockControl.verify();
+ assertNoTempFiles( expectedFile );
+
+ // TODO: do not want failures to present as a not found [MRM-492]
+ // TODO: How much information on each failure should we pass back to the user vs. logging in the proxy?
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.filelock.DefaultFileLockManager;
+import org.apache.archiva.common.utils.VersionUtil;
+import org.apache.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.archiva.model.ArchivaRepositoryMetadata;
+import org.apache.archiva.model.Plugin;
+import org.apache.archiva.model.SnapshotVersion;
+import org.apache.archiva.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.content.ContentItem;
+import org.apache.archiva.repository.content.DataItem;
+import org.apache.archiva.repository.content.ItemSelector;
+import org.apache.archiva.repository.content.Project;
+import org.apache.archiva.repository.content.Version;
+import org.apache.archiva.repository.content.base.ArchivaItemSelector;
+import org.apache.archiva.repository.metadata.RepositoryMetadataException;
+import org.apache.archiva.repository.metadata.base.MetadataTools;
+import org.apache.archiva.repository.metadata.base.RepositoryMetadataWriter;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.archiva.repository.storage.fs.FilesystemStorage;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.maven.wagon.TransferFailedException;
+import org.easymock.EasyMock;
+import org.junit.Test;
+import org.xmlunit.builder.DiffBuilder;
+import org.xmlunit.diff.Diff;
+import org.xmlunit.diff.Difference;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.io.File;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import static org.junit.Assert.*;
+
+/**
+ * MetadataTransferTest - Tests the various fetching / merging concepts surrounding the maven-metadata.xml files
+ * present in the repository.
+ * <p/>
+ * Test Case Naming is as follows.
+ * <p/>
+ * <code>
+ * public void testGet[Release|Snapshot|Project]Metadata[Not]Proxied[Not|On]Local[Not|On|Multiple]Remote
+ * </code>
+ * <p/>
+ * <pre>
+ * Which should leave the following matrix of test cases.
+ *
+ * Metadata | Proxied | Local | Remote
+ * ----------+----------+-------+---------
+ * Release | Not | Not | n/a (1)
+ * Release | Not | On | n/a (1)
+ * Release | | Not | Not
+ * Release | | Not | On
+ * Release | | Not | Multiple
+ * Release | | On | Not
+ * Release | | On | On
+ * Release | | On | Multiple
+ * Snapshot | Not | Not | n/a (1)
+ * Snapshot | Not | On | n/a (1)
+ * Snapshot | | Not | Not
+ * Snapshot | | Not | On
+ * Snapshot | | Not | Multiple
+ * Snapshot | | On | Not
+ * Snapshot | | On | On
+ * Snapshot | | On | Multiple
+ * Project | Not | Not | n/a (1)
+ * Project | Not | On | n/a (1)
+ * Project | | Not | Not
+ * Project | | Not | On
+ * Project | | Not | Multiple
+ * Project | | On | Not
+ * Project | | On | On
+ * Project | | On | Multiple
+ *
+ * (1) If it isn't proxied, no point in having a remote.
+ * </pre>
+ *
+ *
+ */
+public class MetadataTransferTest
+ extends AbstractProxyTestCase
+{
+
+ @Inject
+ @Named(value = "metadataTools#mocked")
+ private MetadataTools metadataTools;
+
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalOnRemoteConnectoDisabled()
+ throws Exception
+ {
+ // New project metadata that does not exist locally but exists on remote.
+ String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ Path expectedFile = managedDefaultDir.resolve(requestedResource);
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ ContentItem metaItem = managedDefaultRepository.toItem( requestedResource );
+ Project project = layout.adaptItem( Project.class, managedDefaultRepository.getParent( metaItem ) );
+ assertNotNull( project );
+ String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem( project ) );
+ StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
+ metaPath ).getFile();
+
+ assertNull( "Should not have downloaded a file.", downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ // TODO: same test for other fetch* methods
+ @Test
+ public void testFetchFromTwoProxiesWhenFirstConnectionFails()
+ throws Exception
+ {
+ // Project metadata that does not exist locally, but has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( "badproxied1", requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // ensure that a hard failure in the first proxy connector is skipped and the second repository checked
+ Path expectedFile = managedDefaultDir.resolve(
+ metadataTools.getRepositorySpecificName( "badproxied1", requestedResource ) );
+
+ wagonMock.get( EasyMock.eq( requestedResource ), EasyMock.anyObject( File.class ));
+ EasyMock.expectLastCall().andThrow( new TransferFailedException( "can't connect" ) );
+
+
+ wagonMockControl.replay();
+
+ assertFetchProjectOrGroup( requestedResource );
+
+ wagonMockControl.verify();
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.1" }, "1.0.1", "1.0.1" );
+ assertNoRepoMetadata( "badproxied1", requestedResource );
+ assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
+ }
+
+ /**
+ * Attempt to get the project metadata for non-existant artifact.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
+ * to the requesting client.
+ */
+ @Test
+ public void testGetProjectMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
+
+ assertResourceNotFound( requestedResource );
+
+ // No proxy setup, nothing fetched, failure expected.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertResourceNotFound( requestedResource );
+ }
+
+ @Test
+ public void testGetProjectMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+
+ // Project metadata that exists and has multiple versions
+ String requestedResource = "org/apache/maven/test/get-project-metadata/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
+
+ assertResourceExists( requestedResource );
+
+ // No proxy setup, nothing fetched from remote, but local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ // A metadata update is not performed in this use case. Local metadata content is only
+ // updated via the metadata updater consumer.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ // Project metadata that does not exist locally, but has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1" }, "1.0.1", "1.0.1" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0" } );
+ assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
+ String requestedResource = "org/apache/maven/test/get-bogus-artifact/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, nothing fetched from remotes, local does not exist.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // Nothing fetched. Nothing should exist.
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ // New project metadata that does not exist locally but exists on remote.
+ String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local does not exist.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local created/updated.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.5" }, "1.0.5", "1.0.5" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.5" } );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally, and has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/get-on-multiple-repos/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata fetched from both repos, and merged with local version.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1", "2.0" }, "2.0", "2.0" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0", "2.0" } );
+ assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0", "1.0.1" } );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+
+ // Project metadata that exist locally, and does not exist in remote repos.
+ String requestedResource = "org/apache/maven/test/get-not-on-remotes/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata not fetched from both repos, and local version exists.
+ // Since there was no updated metadata content from a remote/proxy, a metadata update on
+ // the local file never ran. Local only updates are performed via the metadata updater consumer.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally and exists on remote.
+ String requestedResource = "org/apache/maven/test/get-on-local-on-remote/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local updated.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22", "2.0" }, "2.0", "2.0" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.22", "2.0" } );
+ }
+
+ /**
+ * A request for a release maven-metadata.xml file that does not exist locally, and the managed
+ * repository has no proxied repositories set up.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
+ * to the requesting client.
+ */
+ @Test
+ public void testGetReleaseMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertNoMetadata( requestedResource );
+
+ // No proxy setup, nothing fetched, failure expected.
+ assertFetchVersionedFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertNoMetadata( requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that does exist locally, and the managed
+ * repository has no proxied repositories set up.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is updated locally, based off of the managed repository
+ * information, and then returned to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-default-metadata/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceExists( requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ }
+
+ /**
+ * A request for a release maven-metadata.xml file that does not exist on the managed repository, but
+ * exists on multiple remote repositories.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
+ * file location on the managed repository, a merge of the contents to the requested
+ * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
+ * returned to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that does not exist locally, nor does it exist in a remote
+ * proxied repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is created locally, based off of managed repository
+ * information, and then return to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-bad-metadata/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that does not exist on the managed repository, but
+ * exists on 1 remote repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
+ * file location on the managed repository, a merge of the contents to the requested
+ * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
+ * returned to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that exists in the managed repository, but
+ * not on any remote repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file does not exist on the remote proxied repository and
+ * is not downloaded. There is no repository specific metadata file on the managed
+ * repository. The managed repository maven-metadata.xml is returned to the
+ * client as-is.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-not-on-remotes/1.0-beta-2/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertReleaseMetadataContents( requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that exists in the managed repository, and on multiple
+ * remote repositories.
+ * <p/>
+ * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
+ * and merged into the contents of the existing managed repository copy of
+ * the maven-metadata.xml file.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-on-multiple-repos/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that exists in the managed repository, and on one
+ * remote repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
+ * and merged into the contents of the existing managed repository copy of
+ * the maven-metadata.xml file.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-on-local-on-remote/1.0.22/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource =
+ "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertNoMetadata( requestedResource );
+
+ // No proxy setup, nothing fetched, no local file, failure expected.
+ assertFetchVersionedFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertNoMetadata( requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+ // The artifactId exists locally (but not on a remote repo)
+ String requestedResource =
+ "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceExists( requestedResource );
+
+ // No proxy setup, nothing fetched from remote, local file exists, fetch should succeed.
+ assertFetchVersioned( requestedResource );
+
+ // Local metadata exists, should be updated to reflect the latest release.
+ assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ String requestedResource =
+ "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Proxying 2 repos, both have content, local file updated.
+ assertFetchVersioned( requestedResource );
+
+ assertSnapshotMetadataContents( requestedResource, "20070101", "000103", 2 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20061227", "112101", 2 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070101", "000103", 2 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource =
+ "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertNoMetadata( requestedResource );
+
+ // One proxy setup, nothing fetched, no local file, failure expected.
+ assertFetchVersionedFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertNoMetadata( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ // Artifact exists only in the proxied1 location.
+ String requestedResource = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+
+ // One proxy setup, one metadata fetched, local file created/updated.
+ assertFetchVersioned( requestedResource );
+
+ // Local artifact Id should contain latest (which in this case is from proxied download)
+ assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-snapshot-popular/2.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertSnapshotMetadataContents( requestedResource, "20070822", "021008", 3 );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Proxying 2 repos, both have content, local file updated.
+ assertFetchVersioned( requestedResource );
+
+ assertSnapshotMetadataContents( requestedResource, "20070823", "212711", 6 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20070822", "145534", 9 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070823", "212711", 6 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+ // The artifactId exists locally (but not on a remote repo)
+ String requestedResource =
+ "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceExists( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
+ assertFetchVersioned( requestedResource );
+
+ // Local metadata exists, repo metadatas should not exist, local file updated.
+ assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ // The artifactId exists locally (but not on a remote repo)
+ String requestedResource =
+ "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
+ assertFetchVersioned( requestedResource );
+
+ // Local metadata exists, repo metadata exists, local file updated.
+ assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
+ }
+
+ @Test
+ public void testGetGroupMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource = "org/apache/maven/test/groups/get-default-metadata-nonexistant/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceNotFound( requestedResource );
+
+ // No proxy setup, nothing fetched, failure expected.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertResourceNotFound( requestedResource );
+ }
+
+ @Test
+ public void testGetGroupMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+ // Project metadata that exists and has multiple versions
+ String requestedResource = "org/apache/maven/test/groups/get-project-metadata/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceExists( requestedResource );
+
+ // No proxy setup, nothing fetched from remote, but local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ // A metadata update is not performed in this use case. Local metadata content is only
+ // updated via the metadata updater consumer.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ // Project metadata that does not exist locally, but has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/groups/get-default-layout/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin2", "plugin1" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1" } );
+ assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin2" } );
+ }
+
+ @Test
+ public void testGetGroupsMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
+ String requestedResource = "org/apache/maven/test/groups/get-bogus-artifact/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, nothing fetched from remotes, local does not exist.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // Nothing fetched. Nothing should exist.
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ // New project metadata that does not exist locally but exists on remote.
+ String requestedResource = "org/apache/maven/test/groups/get-found-in-proxy/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local does not exist.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local created/updated.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin3" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin3" } );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally, and has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/groups/get-on-multiple-repos/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata fetched from both repos, and merged with local version.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin1", "plugin2", "plugin4" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1", "plugin4" } );
+ assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin1", "plugin2" } );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally, and does not exist in remote repos.
+ String requestedResource = "org/apache/maven/test/groups/get-not-on-remotes/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata not fetched from both repos, and local version exists.
+ // Since there was no updated metadata content from a remote/proxy, a metadata update on
+ // the local file never ran. Local only updates are performed via the metadata updater consumer.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally and exists on remote.
+ String requestedResource = "org/apache/maven/test/groups/get-on-local-on-remote/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local updated.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7", "plugin4" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin7", "plugin4" } );
+ }
+
+ /**
+ * Transfer the metadata file.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchProjectOrGroup( String requestedResource )
+ throws Exception
+ {
+ Path expectedFile = managedDefaultDir.resolve(requestedResource);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ ContentItem metaItem = managedDefaultRepository.toItem( requestedResource );
+ Project project = layout.adaptItem( Project.class, managedDefaultRepository.getParent( metaItem ) );
+ assertNotNull( project );
+ String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem( project ) );
+
+ StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
+ metaPath ).getFile();
+
+ assertNotNull( "Should have downloaded a file.", downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+
+ /**
+ * Transfer the metadata file, not expected to succeed.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchProjectOrGroupFailed( String requestedResource )
+ throws Exception
+ {
+ Path expectedFile = managedDefaultDir.resolve(requestedResource);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ ContentItem metaItem = managedDefaultRepository.toItem( requestedResource );
+ Project project = layout.adaptItem( Project.class, managedDefaultRepository.getParent( metaItem ) );
+ assertNotNull( project );
+ String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem( project ) );
+ StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
+ metaPath ).getFile();
+
+ assertNull( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Transfer the metadata file.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchVersioned( String requestedResource )
+ throws Exception
+ {
+ Path expectedFile = managedDefaultDir.resolve(requestedResource);
+
+ ContentItem item = managedDefaultRepository.toItem( requestedResource );
+ if (item instanceof DataItem) {
+ item = managedDefaultRepository.getParent( item );
+ }
+ assertNotNull( item );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Version version = layout.adaptItem( Version.class, item );
+ assertNotNull( version );
+ String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem(
+ version ) );
+
+ StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
+ metaPath).getFile();
+
+ assertNotNull( "Should have downloaded a file.", downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+
+ /**
+ * Transfer the metadata file, not expected to succeed.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchVersionedFailed( String requestedResource )
+ throws Exception
+ {
+ Path expectedFile = managedDefaultDir.resolve(requestedResource);
+ ContentItem item = managedDefaultRepository.toItem( requestedResource );
+ assertNotNull( item );
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Version version = layout.adaptItem( Version.class, item );
+ assertNotNull( version );
+ String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem(
+ version ) );
+ assertNotNull( metaPath );
+ StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
+ metaPath ).getFile();
+
+ assertNull( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Test for the existance of the requestedResource in the default managed repository.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertResourceExists( String requestedResource )
+ throws Exception
+ {
+ Path actualFile = managedDefaultDir.resolve(requestedResource);
+ assertTrue( "Resource should exist: " + requestedResource, Files.exists(actualFile) );
+ }
+
+ private void assertMetadataEquals( String expectedMetadataXml, Path actualFile )
+ throws Exception
+ {
+ assertNotNull( "Actual File should not be null.", actualFile );
+
+ assertTrue( "Actual file exists.", Files.exists(actualFile) );
+
+ StringWriter actualContents = new StringWriter();
+ FilesystemStorage fsStorage = new FilesystemStorage(actualFile.getParent(), new DefaultFileLockManager());
+ StorageAsset actualFileAsset = fsStorage.getAsset(actualFile.getFileName().toString());
+ ArchivaRepositoryMetadata metadata = metadataTools.getMetadataReader( null ).read( actualFileAsset );
+ RepositoryMetadataWriter.write( metadata, actualContents );
+
+ Diff detailedDiff = DiffBuilder.compare( expectedMetadataXml).withTest( actualContents.toString() ).checkForSimilar().build();
+ if ( detailedDiff.hasDifferences() )
+ {
+ for ( Difference diff : detailedDiff.getDifferences() )
+ {
+ System.out.println( diff );
+ }
+ assertEquals( expectedMetadataXml, actualContents );
+ }
+
+ // assertEquals( "Check file contents.", expectedMetadataXml, actualContents );
+ }
+
+ /**
+ * Ensures that the requested resource is not present in the managed repository.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertNoMetadata( String requestedResource )
+ throws Exception
+ {
+ Path expectedFile = managedDefaultDir.resolve(requestedResource);
+ assertFalse( "metadata should not exist: " + expectedFile, Files.exists(expectedFile) );
+ }
+
+ /**
+ * Ensures that the proxied repository specific maven metadata file does NOT exist in the
+ * managed repository.
+ *
+ * @param proxiedRepoId the proxied repository id to validate with.
+ * @param requestedResource the resource requested.
+ */
+ private void assertNoRepoMetadata( String proxiedRepoId, String requestedResource )
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ Path actualFile = managedDefaultDir.resolve(proxiedFile);
+ assertFalse( "Repo specific metadata should not exist: " + actualFile, Files.exists(actualFile) );
+ }
+
+ private void assertGroupMetadataContents( String requestedResource, String expectedPlugins[] )
+ throws Exception
+ {
+ Path actualFile = managedDefaultDir.resolve(requestedResource);
+ assertTrue( "Snapshot Metadata should exist: " + requestedResource, Files.exists(actualFile) );
+
+ ItemSelector actualMetadata = createGroupSelector( requestedResource );
+
+ assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
+ }
+
+ private ItemSelector createProjectSelector(String path) throws RepositoryMetadataException
+ {
+ return metadataTools.toProjectSelector( path );
+ }
+
+ private ItemSelector createVersionedSelector(String path) throws RepositoryMetadataException
+ {
+ return metadataTools.toVersionedSelector( path );
+ }
+
+ private ItemSelector createGroupSelector( String requestedResource )
+ throws RepositoryMetadataException
+ {
+ ItemSelector projectSelector = createProjectSelector( requestedResource );
+ ArchivaItemSelector.Builder projectReference = ArchivaItemSelector.builder( ).withSelector( projectSelector );
+ projectReference.withNamespace( projectSelector.getNamespace() + "." + projectSelector.getProjectId() );
+ projectReference.withArtifactId( null );
+ projectReference.withProjectId( null );
+ return projectReference.build();
+ }
+
+ private void assertRepoGroupMetadataContents( String proxiedRepoId, String requestedResource,
+ String expectedPlugins[] )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ Path actualFile = managedDefaultDir.resolve(proxiedFile);
+ assertTrue( "Repo Specific Group Metadata should exist: " + requestedResource, Files.exists(actualFile) );
+
+ ItemSelector actualMetadata = createGroupSelector( requestedResource );
+
+ assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
+ }
+
+ private void assertGroupMetadata( Path actualFile, ItemSelector actualMetadata, String expectedPlugins[] )
+ throws Exception
+ {
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( actualMetadata.getNamespace() );
+
+ for ( String pluginId : expectedPlugins )
+ {
+ Plugin p = new Plugin();
+ p.setPrefix( pluginId );
+ p.setArtifactId( pluginId + "-maven-plugin" );
+ p.setName( "The " + pluginId + " Plugin" );
+ m.getPlugins().add( p );
+ }
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the existance of the requestedResource in the default managed repository, and if it exists,
+ * does it contain the specified list of expected versions?
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertProjectMetadataContents( String requestedResource, String expectedVersions[],
+ String latestVersion, String releaseVersion )
+ throws Exception
+ {
+ Path actualFile = managedDefaultDir.resolve(requestedResource);
+ assertTrue( Files.exists(actualFile) );
+
+ ItemSelector metadata = createProjectSelector( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getNamespace() );
+ m.setArtifactId( metadata.getArtifactId() );
+ m.setLatestVersion( latestVersion );
+ m.setReleasedVersion( releaseVersion );
+
+ if ( expectedVersions != null )
+ {
+ m.getAvailableVersions().addAll( Arrays.asList( expectedVersions ) );
+ }
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the existance of the requestedResource in the default managed repository, and if it exists,
+ * does it contain the expected release maven-metadata.xml contents?
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertReleaseMetadataContents( String requestedResource )
+ throws Exception
+ {
+ Path actualFile = managedDefaultDir.resolve(requestedResource);
+ assertTrue( "Release Metadata should exist: " + requestedResource, Files.exists(actualFile) );
+
+ ItemSelector metadata = createVersionedSelector( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getNamespace() );
+ m.setArtifactId( metadata.getArtifactId() );
+ m.setVersion( metadata.getVersion() );
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the existance of the snapshot metadata in the default managed repository, and if it exists,
+ * does it contain the expected release maven-metadata.xml contents?
+ *
+ * @param requestedResource the requested resource
+ * @param expectedDate the date in "yyyyMMdd" format
+ * @param expectedTime the time in "hhmmss" format
+ * @param expectedBuildnumber the build number
+ * @throws Exception
+ */
+ private void assertSnapshotMetadataContents( String requestedResource, String expectedDate, String expectedTime,
+ int expectedBuildnumber )
+ throws Exception
+ {
+ Path actualFile = managedDefaultDir.resolve(requestedResource);
+ assertTrue( "Snapshot Metadata should exist: " + requestedResource, Files.exists(actualFile) );
+
+ ItemSelector actualMetadata = createVersionedSelector( requestedResource );
+
+ assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
+ }
+
+ /**
+ * Test for the existance of the proxied repository specific snapshot metadata in the default managed
+ * repository, and if it exists, does it contain the expected release maven-metadata.xml contents?
+ *
+ * @param proxiedRepoId the repository id of the proxied repository.
+ * @param requestedResource the requested resource
+ * @param expectedDate the date in "yyyyMMdd" format
+ * @param expectedTime the time in "hhmmss" format
+ * @param expectedBuildnumber the build number
+ * @throws Exception
+ */
+ private void assertRepoSnapshotMetadataContents( String proxiedRepoId, String requestedResource,
+ String expectedDate, String expectedTime, int expectedBuildnumber )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ Path actualFile = managedDefaultDir.resolve(proxiedFile);
+ assertTrue( "Repo Specific Snapshot Metadata should exist: " + requestedResource, Files.exists(actualFile) );
+
+ ItemSelector actualMetadata = createVersionedSelector( requestedResource );
+
+ assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
+ }
+
+ private void assertSnapshotMetadata( Path actualFile, ItemSelector actualMetadata, String expectedDate,
+ String expectedTime, int expectedBuildnumber )
+ throws RepositoryMetadataException, Exception
+ {
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( actualMetadata.getNamespace() );
+ m.setArtifactId( actualMetadata.getArtifactId() );
+ m.setVersion( VersionUtil.getBaseVersion( actualMetadata.getVersion() ) );
+
+ m.setSnapshotVersion( new SnapshotVersion() );
+
+ if ( StringUtils.isNotBlank( expectedDate ) && StringUtils.isNotBlank( expectedTime ) )
+ {
+ m.getSnapshotVersion().setTimestamp( expectedDate + "." + expectedTime );
+ }
+
+ m.getSnapshotVersion().setBuildNumber( expectedBuildnumber );
+
+ m.setLastUpdated( expectedDate + expectedTime );
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Ensures that the repository specific maven metadata file exists, and contains the appropriate
+ * list of expected versions within.
+ *
+ * @param proxiedRepoId
+ * @param requestedResource
+ * @param expectedProxyVersions
+ */
+ private void assertRepoProjectMetadata( String proxiedRepoId, String requestedResource,
+ String[] expectedProxyVersions )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ Path actualFile = managedDefaultDir.resolve(proxiedFile);
+ assertTrue( Files.exists(actualFile) );
+
+ ItemSelector metadata = createProjectSelector( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getNamespace() );
+ m.setArtifactId( metadata.getArtifactId() );
+
+ if ( expectedProxyVersions != null )
+ {
+ m.getAvailableVersions().addAll( Arrays.asList( expectedProxyVersions ) );
+ }
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Ensures that the repository specific maven metadata file exists, and contains the appropriate
+ * list of expected versions within.
+ *
+ * @param proxiedRepoId
+ * @param requestedResource
+ */
+ private void assertRepoReleaseMetadataContents( String proxiedRepoId, String requestedResource )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ Path actualFile = managedDefaultDir.resolve(proxiedFile);
+ assertTrue( "Release metadata for repo should exist: " + actualFile, Files.exists(actualFile) );
+
+ ItemSelector metadata = createVersionedSelector( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getNamespace() );
+ m.setArtifactId( metadata.getArtifactId() );
+ m.setVersion( metadata.getVersion() );
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the non-existance of the requestedResource in the default managed repository.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertResourceNotFound( String requestedResource )
+ throws Exception
+ {
+ Path actualFile = managedDefaultDir.resolve(requestedResource);
+ assertFalse( "Resource should not exist: " + requestedResource, Files.exists(actualFile) );
+ }
+
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.configuration.*;
+import org.apache.archiva.components.registry.Registry;
+import org.apache.archiva.components.registry.RegistryException;
+import org.apache.archiva.components.registry.RegistryListener;
+import org.apache.commons.lang3.StringUtils;
+import org.easymock.EasyMock;
+import org.easymock.IMocksControl;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.*;
+
+/**
+ * MockConfiguration
+ *
+ *
+ */
+@Service( "archivaConfiguration#mock" )
+public class MockConfiguration
+ implements ArchivaConfiguration
+{
+
+ private Configuration configuration = new Configuration();
+
+ private Set<RegistryListener> registryListeners = new HashSet<RegistryListener>();
+
+ private Set<ConfigurationListener> configListeners = new HashSet<ConfigurationListener>();
+
+ private IMocksControl registryControl;
+
+ private Registry registryMock;
+
+ public MockConfiguration()
+ {
+ registryControl = EasyMock.createNiceControl( );
+ registryMock = registryControl.createMock( Registry.class );
+ }
+
+ @PostConstruct
+ public void initialize()
+ throws Exception
+ {
+
+ configuration.setRepositoryScanning( new RepositoryScanningConfiguration()
+ {
+ @Override
+ public List<FileType> getFileTypes()
+ {
+ FileType fileType = new FileType();
+ fileType.setId( FileTypes.ARTIFACTS );
+ fileType.setPatterns( Collections.singletonList( "**/*" ) );
+ return Collections.singletonList( fileType );
+ }
+ } );
+ ArchivaRuntimeConfiguration rt = new ArchivaRuntimeConfiguration();
+ List<String> checksums = new ArrayList<>();
+ checksums.add("MD5");
+ checksums.add("SHA1");
+ checksums.add("SHA256");
+ rt.setChecksumTypes(checksums);
+ configuration.setArchivaRuntimeConfiguration(rt);
+
+ }
+
+ @Override
+ public void addChangeListener( org.apache.archiva.components.registry.RegistryListener listener )
+ {
+ registryListeners.add( listener );
+ }
+
+
+ @Override
+ public void removeChangeListener( RegistryListener listener )
+ {
+ registryListeners.remove( listener );
+ }
+
+ @Override
+ public Configuration getConfiguration()
+ {
+ return configuration;
+ }
+
+ @Override
+ public void save( Configuration configuration )
+ throws RegistryException
+ {
+ /* do nothing */
+ }
+
+ @Override
+ public void save( Configuration configuration, String eventTag ) throws RegistryException, IndeterminateConfigurationException
+ {
+ // do nothing
+ }
+
+ public void triggerChange( String name, String value )
+ {
+ for ( org.apache.archiva.components.registry.RegistryListener listener : registryListeners )
+ {
+ try
+ {
+ listener.afterConfigurationChange( registryMock, name, value );
+ }
+ catch ( Exception e )
+ {
+ e.printStackTrace();
+ }
+ }
+
+ for (ConfigurationListener listener : configListeners) {
+ listener.configurationEvent( new ConfigurationEvent( ConfigurationEvent.CHANGED ) );
+ }
+ }
+
+ @Override
+ public void addListener( ConfigurationListener listener )
+ {
+ configListeners.add( listener );
+ }
+
+ @Override
+ public void removeListener( ConfigurationListener listener )
+ {
+ configListeners.remove( listener );
+ }
+
+ @Override
+ public boolean isDefaulted()
+ {
+ return false;
+ }
+
+ @Override
+ public void reload()
+ {
+ // no op
+ }
+
+ @Override
+ public Locale getDefaultLocale( )
+ {
+ return Locale.getDefault();
+ }
+
+ @Override
+ public List<Locale.LanguageRange> getLanguagePriorities( )
+ {
+ return Locale.LanguageRange.parse( "en,fr,de" );
+ }
+
+ @Override
+ public Path getAppServerBaseDir() {
+ if (System.getProperties().containsKey("appserver.base")) {
+ return Paths.get(System.getProperty("appserver.base"));
+ } else {
+ return Paths.get("");
+ }
+ }
+
+
+ @Override
+ public Path getRepositoryBaseDir() {
+ return getDataDirectory().resolve("repositories");
+ }
+
+ @Override
+ public Path getRemoteRepositoryBaseDir() {
+ return getDataDirectory().resolve("remotes");
+ }
+
+ @Override
+ public Path getRepositoryGroupBaseDir() {
+ return getDataDirectory().resolve("groups");
+ }
+
+ @Override
+ public Path getDataDirectory() {
+ if (configuration!=null && StringUtils.isNotEmpty(configuration.getArchivaRuntimeConfiguration().getDataDirectory())) {
+ return Paths.get(configuration.getArchivaRuntimeConfiguration().getDataDirectory());
+ } else {
+ return getAppServerBaseDir().resolve("data");
+ }
+ }
+
+ @Override
+ public Registry getRegistry( )
+ {
+ return null;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.policies.CachedFailuresPolicy;
+import org.apache.archiva.policies.ChecksumPolicy;
+import org.apache.archiva.policies.ReleasesPolicy;
+import org.apache.archiva.policies.SnapshotsPolicy;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.content.Artifact;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.junit.Test;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.*;
+
+/**
+ * SnapshotTransferTest
+ *
+ *
+ */
+public class SnapshotTransferTest
+ extends AbstractProxyTestCase
+{
+ @Test
+ public void testSnapshotNonExistant()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ Files.deleteIfExists(expectedFile);
+ assertFalse( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testTimestampDrivenSnapshotNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ Files.deleteIfExists(expectedFile);
+ assertFalse( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testNewerTimestampDrivenSnapshotOnFirstRepo()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+ Files.setLastModifiedTime( expectedFile, FileTime.from( getPastDate().getTime(), TimeUnit.MILLISECONDS ));
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testOlderTimestampDrivenSnapshotOnFirstRepo()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
+
+ setManagedNewerThanRemote( expectedFile, remoteFile );
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ // Attempt to download.
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ // Should not have downloaded as managed is newer than remote.
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * TODO: Has problems with wagon implementation not preserving timestamp.
+ */
+ /*
+ public void testNewerTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ ArtifactReference artifact = createArtifactReference( "default", path );
+
+ Files.delete(expectedFile);
+ assertFalse( Files.exists(expectedFile) );
+
+ // Create customized proxy / target repository
+ File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED1_TARGET, REPOPATH_PROXIED1,
+ REPOPATH_PROXIED1_TARGET, "default" );
+
+ new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ // Should have downloaded the content from proxy2, as proxy1 has an old (by file.lastModified check) version.
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED2, path);
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ public void testOlderTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ ArtifactReference artifact = createArtifactReference( "default", path );
+
+ Files.delete(expectedFile);
+ assertFalse( Files.exists(expectedFile) );
+
+ // Create customized proxy / target repository
+ File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED2_TARGET, REPOPATH_PROXIED2,
+ REPOPATH_PROXIED2_TARGET, "default" );
+
+ new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1_TARGET, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ } */
+
+ @Test
+ public void testTimestampDrivenSnapshotNotExpired()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ Files.setLastModifiedTime( proxiedFile, FileTime.from( getFutureDate().getTime(), TimeUnit.MILLISECONDS ));
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testTimestampDrivenSnapshotNotUpdated()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+ Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
+
+ setManagedNewerThanRemote( expectedFile, remoteFile, 12000000 );
+ long expectedTimestamp = Files.getLastModifiedTime( expectedFile ).toMillis();
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, expectedTimestamp );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testTimestampDrivenSnapshotNotPresentAlreadyExpiredCacheFailure()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ Files.deleteIfExists(expectedFile);
+ assertFalse( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testMetadataDrivenSnapshotNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/get-metadata-snapshot-1.0-20050831.101112-1.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ Files.deleteIfExists(expectedFile);
+ assertFalse( Files.exists(expectedFile) );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertNotNull( downloadedFile );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetMetadataDrivenSnapshotRemoteUpdate()
+ throws Exception
+ {
+ // Metadata driven snapshots (using a full timestamp) are treated like a release. It is the timing of the
+ // updates to the metadata files that triggers which will be downloaded
+
+ String path = "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/get-present-metadata-snapshot-1.0-20050831.101112-1.jar";
+ setupTestableManagedRepository( path );
+
+ Path expectedFile = managedDefaultDir.resolve(path);
+
+ BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
+
+ Artifact artifact = layout.getArtifact( path );
+
+ assertTrue( Files.exists(expectedFile) );
+
+ Files.setLastModifiedTime( expectedFile, FileTime.from( getPastDate().getTime(), TimeUnit.MILLISECONDS ));
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
+
+ Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
+ assertNotNull( downloadedFile );
+ assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.maven.wagon.ConnectionException;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.apache.maven.wagon.TransferFailedException;
+import org.apache.maven.wagon.Wagon;
+import org.apache.maven.wagon.authentication.AuthenticationException;
+import org.apache.maven.wagon.authentication.AuthenticationInfo;
+import org.apache.maven.wagon.authorization.AuthorizationException;
+import org.apache.maven.wagon.events.SessionListener;
+import org.apache.maven.wagon.events.TransferListener;
+import org.apache.maven.wagon.proxy.ProxyInfo;
+import org.apache.maven.wagon.proxy.ProxyInfoProvider;
+import org.apache.maven.wagon.repository.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+ * A dummy wagon implementation
+ */
+@Service ("wagon#test")
+public class WagonDelegate
+ implements Wagon
+{
+ private Logger log = LoggerFactory.getLogger( WagonDelegate.class );
+
+ private Wagon delegate;
+
+ private String contentToGet;
+
+ @Override
+ public void get( String resourceName, File destination )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ log.debug( ".get({}, {})", resourceName, destination );
+ delegate.get( resourceName, destination );
+ create( destination.toPath() );
+ }
+
+ @Override
+ public boolean getIfNewer( String resourceName, File destination, long timestamp )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ log.info( ".getIfNewer({}, {}, {})", resourceName, destination, timestamp );
+
+ boolean result = delegate.getIfNewer( resourceName, destination, timestamp );
+ createIfMissing( destination.toPath() );
+ return result;
+ }
+
+ @Override
+ public void put( File source, String destination )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ delegate.put( source, destination );
+ }
+
+ @Override
+ public void putDirectory( File sourceDirectory, String destinationDirectory )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ delegate.putDirectory( sourceDirectory, destinationDirectory );
+ }
+
+ @Override
+ public boolean resourceExists( String resourceName )
+ throws TransferFailedException, AuthorizationException
+ {
+ return delegate.resourceExists( resourceName );
+ }
+
+ @SuppressWarnings ("unchecked")
+ @Override
+ public List<String> getFileList( String destinationDirectory )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ return delegate.getFileList( destinationDirectory );
+ }
+
+ @Override
+ public boolean supportsDirectoryCopy()
+ {
+ return delegate.supportsDirectoryCopy();
+ }
+
+ @Override
+ public void setTimeout( int val )
+ {
+ // ignore
+ }
+
+ @Override
+ public int getTimeout()
+ {
+ return 0;
+ }
+
+ @Override
+ public void setReadTimeout( int timeoutValue )
+ {
+ // ignore
+ }
+
+ @Override
+ public int getReadTimeout()
+ {
+ return 0;
+ }
+
+ @Override
+ public Repository getRepository()
+ {
+ return delegate.getRepository();
+ }
+
+ @Override
+ public void connect( Repository source )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source );
+ }
+
+ @Override
+ public void connect( Repository source, ProxyInfo proxyInfo )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, proxyInfo );
+ }
+
+ @Override
+ public void connect( Repository source, ProxyInfoProvider proxyInfoProvider )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, proxyInfoProvider );
+ }
+
+ @Override
+ public void connect( Repository source, AuthenticationInfo authenticationInfo )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, authenticationInfo );
+ }
+
+ @Override
+ public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, authenticationInfo, proxyInfo );
+ }
+
+ @Override
+ public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, authenticationInfo, proxyInfoProvider );
+ }
+
+ @SuppressWarnings ("deprecation")
+ @Override
+ public void openConnection()
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.openConnection();
+ }
+
+ @Override
+ public void disconnect()
+ throws ConnectionException
+ {
+ delegate.disconnect();
+ }
+
+ @Override
+ public void addSessionListener( SessionListener listener )
+ {
+ delegate.addSessionListener( listener );
+ }
+
+ @Override
+ public void removeSessionListener( SessionListener listener )
+ {
+ delegate.removeSessionListener( listener );
+ }
+
+ @Override
+ public boolean hasSessionListener( SessionListener listener )
+ {
+ return delegate.hasSessionListener( listener );
+ }
+
+ @Override
+ public void addTransferListener( TransferListener listener )
+ {
+ delegate.addTransferListener( listener );
+ }
+
+ @Override
+ public void removeTransferListener( TransferListener listener )
+ {
+ delegate.removeTransferListener( listener );
+ }
+
+ @Override
+ public boolean hasTransferListener( TransferListener listener )
+ {
+ return delegate.hasTransferListener( listener );
+ }
+
+ @Override
+ public boolean isInteractive()
+ {
+ return delegate.isInteractive();
+ }
+
+ @Override
+ public void setInteractive( boolean interactive )
+ {
+ delegate.setInteractive( interactive );
+ }
+
+ public void setDelegate( Wagon delegate )
+ {
+ this.delegate = delegate;
+ }
+
+ void setContentToGet( String content )
+ {
+ contentToGet = content;
+ }
+
+ private void createIfMissing( Path destination )
+ {
+ // since the mock won't actually copy a file, create an empty one to simulate file existence
+ if ( !Files.exists(destination) )
+ {
+ create( destination );
+ }
+ }
+
+ private void create( Path destination )
+ {
+ try
+ {
+ Files.createDirectories(destination.getParent());
+ if ( contentToGet == null && !Files.exists(destination))
+ {
+ Files.createFile(destination);
+ }
+ else if (contentToGet != null)
+ {
+ org.apache.archiva.common.utils.FileUtils.writeStringToFile(destination, Charset.defaultCharset(), contentToGet);
+ }
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ }
+
+ public void cleanup() {
+
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy.mock.metadata.repository;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.components.taskqueue.TaskQueueException;
+import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
+import org.apache.archiva.scheduler.repository.model.RepositoryTask;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author Olivier Lamy
+ */
+@Service ("archivaTaskScheduler#repositoryMock")
+public class MockRepositoryArchivaTaskScheduler
+ implements RepositoryArchivaTaskScheduler
+{
+ @Override
+ public boolean isProcessingRepositoryTask( String repositoryId )
+ {
+ return false;
+ }
+
+ @Override
+ public boolean isProcessingRepositoryTask( RepositoryTask task )
+ {
+ return false;
+ }
+
+ @Override
+ public void queueTask( RepositoryTask task )
+ throws TaskQueueException
+ {
+ // no op
+ }
+
+ @Override
+ public boolean unQueueTask( RepositoryTask task )
+ throws TaskQueueException
+ {
+ return false;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy.mock.repository;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.indexer.ArchivaIndexManager;
+import org.apache.archiva.indexer.ArchivaIndexingContext;
+import org.apache.archiva.indexer.IndexCreationFailedException;
+import org.apache.archiva.indexer.IndexUpdateFailedException;
+import org.apache.archiva.repository.Repository;
+import org.apache.archiva.repository.RepositoryType;
+import org.springframework.stereotype.Service;
+
+import java.net.URI;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author Martin Stockhammer <martin_s@apache.org>
+ */
+@Service("archivaIndexManager#maven")
+public class ArchivaIndexManagerMock implements ArchivaIndexManager {
+
+
+
+ @Override
+ public void pack(ArchivaIndexingContext context) throws IndexUpdateFailedException {
+
+ }
+
+ @Override
+ public void scan(ArchivaIndexingContext context) throws IndexUpdateFailedException {
+
+ }
+
+ @Override
+ public void update(ArchivaIndexingContext context, boolean fullUpdate) throws IndexUpdateFailedException {
+
+ }
+
+ @Override
+ public void addArtifactsToIndex(ArchivaIndexingContext context, Collection<URI> artifactReference) throws IndexUpdateFailedException {
+
+ }
+
+ @Override
+ public void removeArtifactsFromIndex(ArchivaIndexingContext context, Collection<URI> artifactReference) throws IndexUpdateFailedException {
+
+ }
+
+ @Override
+ public boolean supportsRepository(RepositoryType type) {
+ return true;
+ }
+
+ @Override
+ public ArchivaIndexingContext createContext(Repository repository) throws IndexCreationFailedException {
+ return null;
+ }
+
+ @Override
+ public ArchivaIndexingContext reset(ArchivaIndexingContext context) throws IndexUpdateFailedException {
+ return null;
+ }
+
+ @Override
+ public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
+ return null;
+ }
+
+ @Override
+ public void updateLocalIndexPath(Repository repo) {
+
+ }
+
+ @Override
+ public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts, boolean packIndex) throws UnsupportedOperationException, IndexCreationFailedException {
+ return null;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy.mock.repository;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.common.filelock.DefaultFileLockManager;
+import org.apache.archiva.common.utils.VersionUtil;
+import org.apache.archiva.maven.metadata.model.MavenArtifactFacet;
+import org.apache.archiva.metadata.model.ArtifactMetadata;
+import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
+import org.apache.archiva.repository.content.ContentAccessException;
+import org.apache.archiva.repository.ItemDeleteStatus;
+import org.apache.archiva.repository.content.LayoutException;
+import org.apache.archiva.repository.ManagedRepository;
+import org.apache.archiva.repository.ManagedRepositoryContent;
+import org.apache.archiva.repository.content.ManagedRepositoryContentLayout;
+import org.apache.archiva.repository.content.Artifact;
+import org.apache.archiva.repository.content.BaseDataItemTypes;
+import org.apache.archiva.repository.content.ContentItem;
+import org.apache.archiva.repository.content.DataItem;
+import org.apache.archiva.repository.content.ItemNotFoundException;
+import org.apache.archiva.repository.content.ItemSelector;
+import org.apache.archiva.repository.content.Namespace;
+import org.apache.archiva.repository.content.Project;
+import org.apache.archiva.repository.content.Version;
+import org.apache.archiva.repository.content.base.ArchivaArtifact;
+import org.apache.archiva.repository.content.base.ArchivaContentItem;
+import org.apache.archiva.repository.content.base.ArchivaDataItem;
+import org.apache.archiva.repository.content.base.ArchivaNamespace;
+import org.apache.archiva.repository.content.base.ArchivaProject;
+import org.apache.archiva.repository.content.base.ArchivaVersion;
+import org.apache.archiva.repository.storage.RepositoryStorage;
+import org.apache.archiva.repository.storage.StorageAsset;
+import org.apache.archiva.repository.storage.fs.FilesystemStorage;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+/**
+ * @author Martin Stockhammer <martin_s@apache.org>
+ */
+@Service("managedRepositoryContent#mock")
+public class ManagedRepositoryContentMock implements BaseRepositoryContentLayout, ManagedRepositoryContent
+{
+ private static final String PATH_SEPARATOR = "/";
+ private static final String GROUP_SEPARATOR = ".";
+ public static final String MAVEN_METADATA = "maven-metadata.xml";
+
+
+ private ManagedRepository repository;
+ private RepositoryStorage fsStorage;
+
+ ManagedRepositoryContentMock(ManagedRepository repo) {
+ this.repository = repo;
+ this.fsStorage = repo;
+ }
+
+ @Override
+ public <T extends ContentItem> T adaptItem( Class<T> clazz, ContentItem item ) throws LayoutException
+ {
+ if (clazz.isAssignableFrom( Version.class ))
+ {
+ if ( !item.hasCharacteristic( Version.class ) )
+ {
+ item.setCharacteristic( Version.class, createVersionFromPath( item.getAsset() ) );
+ }
+ return (T) item.adapt( Version.class );
+ } else if ( clazz.isAssignableFrom( Project.class )) {
+ if ( !item.hasCharacteristic( Project.class ) )
+ {
+ item.setCharacteristic( Project.class, createProjectFromPath( item.getAsset() ) );
+ }
+ return (T) item.adapt( Project.class );
+ } else if ( clazz.isAssignableFrom( Namespace.class )) {
+ if ( !item.hasCharacteristic( Namespace.class ) )
+ {
+ item.setCharacteristic( Namespace.class, createNamespaceFromPath( item.getAsset() ) );
+ }
+ return (T) item.adapt( Namespace.class );
+ }
+ throw new LayoutException( "Could not convert item to class " + clazz);
+ }
+
+ private Version createVersionFromPath( StorageAsset asset )
+ {
+ Project proj = createProjectFromPath( asset.getParent( ) );
+ return ArchivaVersion.withRepository( this ).withAsset( asset )
+ .withProject( proj ).withVersion( asset.getName( ) ).build();
+ }
+
+ private Project createProjectFromPath( StorageAsset asset) {
+ Namespace ns = createNamespaceFromPath( asset );
+ return ArchivaProject.withRepository( this ).withAsset( asset )
+ .withNamespace( ns ).withId( asset.getName( ) ).build( );
+ }
+
+ private Namespace createNamespaceFromPath( StorageAsset asset) {
+ String namespace = asset.getPath( ).replace( "/", "." );
+ return ArchivaNamespace.withRepository( this )
+ .withAsset( asset ).withNamespace( namespace ).build();
+ }
+
+ @Override
+ public void deleteAllItems( ItemSelector selector, Consumer<ItemDeleteStatus> consumer ) throws ContentAccessException, IllegalArgumentException
+ {
+
+ }
+
+ @Override
+ public void deleteItem( ContentItem item ) throws ItemNotFoundException, ContentAccessException
+ {
+
+ }
+
+ @Override
+ public void copyItem( ContentItem item, ManagedRepository destinationRepository ) throws ItemNotFoundException, ContentAccessException
+ {
+
+ }
+
+ @Override
+ public void copyItem( ContentItem item, ManagedRepository destinationRepository, boolean updateMetadata ) throws ItemNotFoundException, ContentAccessException
+ {
+
+ }
+
+ @Override
+ public ContentItem getItem( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public Namespace getNamespace( ItemSelector namespaceSelector ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public Project getProject( ItemSelector projectSelector ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public Version getVersion( ItemSelector versionCoordinates ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public Artifact getArtifact( ItemSelector selector ) throws ContentAccessException
+ {
+ StringBuilder path = new StringBuilder(selector.getNamespace( ).replace( ".", "/" ));
+ path.append( "/" ).append( selector.getProjectId( ) ).append( "/" ).append( selector.getVersion( ) );
+ path.append( "/" ).append( selector.getArtifactId( ) ).append( "-" ).append( selector.getArtifactVersion( ) ).append( "." ).append( selector.getType( ) );
+ StorageAsset asset = fsStorage.getAsset( path.toString( ) );
+ ArchivaNamespace ns = ArchivaNamespace.withRepository( repository.getContent( ) ).withAsset( asset.getParent( ).getParent( ).getParent( ) ).withNamespace( selector.getNamespace( ) ).build( );
+ ArchivaProject project = ArchivaProject.withRepository( repository.getContent( ) ).withAsset( asset.getParent( ).getParent( ) ).withNamespace( ns ).withId( selector.getProjectId( ) ).build( );
+ ArchivaVersion version = ArchivaVersion.withRepository( repository.getContent( ) ).withAsset( asset.getParent( ) ).withProject( project ).withVersion( selector.getVersion( ) ).build( );
+ ArchivaArtifact artifact = ArchivaArtifact.withAsset( asset ).withVersion( version ).withId( selector.getArtifactId( ) ).withArtifactVersion( selector.getArtifactVersion( ) ).withType( selector.getType( ) ).build( );
+ return artifact;
+ }
+
+ @Override
+ public Artifact getArtifact( String path ) throws LayoutException, ContentAccessException
+ {
+ StorageAsset asset = fsStorage.getAsset( path.toString( ) );
+ String artifactId = asset.getName( );
+ StorageAsset namespacePath = asset.getParent( ).getParent( ).getParent( );
+ String namespaceId = namespacePath.getPath( ).replace( "/", "." );
+ StorageAsset projectPath = asset.getParent( ).getParent( );
+ String projectId = projectPath.getName( );
+ StorageAsset versionPath = asset.getParent( );
+ String versionId = versionPath.getName( );
+ ArchivaNamespace ns = ArchivaNamespace.withRepository( repository.getContent( ) ).withAsset( namespacePath ).withNamespace( namespaceId ).build( );
+ ArchivaProject project = ArchivaProject.withRepository( repository.getContent( ) ).withAsset( projectPath ).withNamespace( ns ).withId( projectId ).build( );
+ ArchivaVersion version = ArchivaVersion.withRepository( repository.getContent( ) ).withAsset( versionPath ).withProject( project ).withVersion( versionId ).build( );
+ ArchivaArtifact artifact = ArchivaArtifact.withAsset( asset ).withVersion( version ).withId( projectId ).withArtifactVersion( versionId ).build( );
+ return artifact;
+ }
+
+ @Override
+ public List<? extends Artifact> getArtifacts( ItemSelector selector ) throws ContentAccessException
+ {
+ return null;
+ }
+
+ @Override
+ public Stream<? extends Artifact> newArtifactStream( ItemSelector selector ) throws ContentAccessException
+ {
+ return null;
+ }
+
+ @Override
+ public Stream<? extends ContentItem> newItemStream( ItemSelector selector, boolean parallel ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public List<? extends Project> getProjects( Namespace namespace ) throws ContentAccessException
+ {
+ return null;
+ }
+
+ @Override
+ public List<? extends Project> getProjects( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public List<? extends Version> getVersions( Project project ) throws ContentAccessException
+ {
+ return null;
+ }
+
+ @Override
+ public List<? extends Version> getVersions( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public List<String> getArtifactVersions( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
+ {
+ return null;
+ }
+
+ @Override
+ public List<? extends Artifact> getArtifacts( ContentItem item ) throws ContentAccessException
+ {
+ return null;
+ }
+
+ @Override
+ public Stream<? extends Artifact> newArtifactStream( ContentItem item ) throws ContentAccessException
+ {
+ return null;
+ }
+
+ @Override
+ public boolean hasContent( ItemSelector selector )
+ {
+ return false;
+ }
+
+ @Override
+ public ContentItem getParent( ContentItem item )
+ {
+ try
+ {
+ return toItem( item.getAsset( ).getParent( ) );
+ }
+ catch ( LayoutException e )
+ {
+ throw new RuntimeException( "Bad layout conversion " + e.getMessage( ) );
+ }
+ }
+
+ @Override
+ public List<? extends ContentItem> getChildren( ContentItem item )
+ {
+ return null;
+ }
+
+ @Override
+ public <T extends ContentItem> T applyCharacteristic( Class<T> clazz, ContentItem item ) throws LayoutException
+ {
+ return null;
+ }
+
+ @Override
+ public <T extends ManagedRepositoryContentLayout> T getLayout( Class<T> clazz ) throws LayoutException
+ {
+ return (T) this;
+ }
+
+ @Override
+ public <T extends ManagedRepositoryContentLayout> boolean supportsLayout( Class<T> clazz )
+ {
+ return true;
+ }
+
+ @Override
+ public List<Class<? extends ManagedRepositoryContentLayout>> getSupportedLayouts( )
+ {
+ return null;
+ }
+
+ @Override
+ public void addArtifact( Path sourceFile, Artifact destination ) throws IllegalArgumentException
+ {
+
+ }
+
+ @Override
+ public DataItem getMetadataItem( Version version )
+ {
+ return ArchivaDataItem.withAsset( version.getAsset( ).resolve( "maven-metadata.xml" ) ).withId( "maven-metadata.xml" )
+ .withDataType( BaseDataItemTypes.METADATA ).build();
+ }
+
+ @Override
+ public DataItem getMetadataItem( Project project )
+ {
+ return ArchivaDataItem.withAsset( project.getAsset( ).resolve( "maven-metadata.xml" ) ).withId( "maven-metadata.xml" )
+ .withDataType( BaseDataItemTypes.METADATA ).build( );
+ }
+
+ @Override
+ public ContentItem toItem( String path ) throws LayoutException
+ {
+ StorageAsset asset = repository.getRoot().resolve( path );
+ return toItem( asset );
+ }
+
+ @Override
+ public ContentItem toItem( StorageAsset asset ) throws LayoutException
+ {
+ if (asset.isLeaf()) {
+ return ArchivaDataItem.withAsset( asset ).withId( asset.getName( ) ).build();
+ } else
+ {
+ return ArchivaContentItem.withRepository( this )
+ .withAsset( asset )
+ .build( );
+ }
+ }
+
+ @Override
+ public String toPath( ContentItem item )
+ {
+ return item.getAsset( ).getPath( );
+ }
+
+ @Override
+ public String getId( )
+ {
+ return repository.getId();
+ }
+
+ private StorageAsset getRepoRootAsset() {
+ if (fsStorage==null) {
+ try {
+ fsStorage = new FilesystemStorage(Paths.get("", "target", "test-repository", "managed"), new DefaultFileLockManager());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ return fsStorage.getRoot();
+ }
+
+ @Override
+ public ManagedRepository getRepository( )
+ {
+ return repository;
+ }
+
+ @Override
+ public void setRepository( ManagedRepository repo )
+ {
+ this.repository = repo;
+ }
+
+ public ArtifactMetadata getArtifactForPath( String repoId, String relativePath )
+ {
+ String[] parts = relativePath.replace( '\\', '/' ).split( "/" );
+
+ int len = parts.length;
+ if ( len < 4 )
+ {
+ throw new IllegalArgumentException(
+ "Not a valid artifact path in a Maven 2 repository, not enough directories: " + relativePath );
+ }
+
+ String id = parts[--len];
+ String baseVersion = parts[--len];
+ String artifactId = parts[--len];
+ StringBuilder groupIdBuilder = new StringBuilder();
+ for ( int i = 0; i < len - 1; i++ )
+ {
+ groupIdBuilder.append( parts[i] );
+ groupIdBuilder.append( '.' );
+ }
+ groupIdBuilder.append( parts[len - 1] );
+
+ return getArtifactFromId( repoId, groupIdBuilder.toString(), artifactId, baseVersion, id );
+ }
+
+ private static final Pattern TIMESTAMP_PATTERN = Pattern.compile( "([0-9]{8}.[0-9]{6})-([0-9]+).*" );
+
+
+
+ public ArtifactMetadata getArtifactFromId( String repoId, String namespace, String projectId, String projectVersion,
+ String id )
+ {
+ if ( !id.startsWith( projectId + "-" ) )
+ {
+ throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
+ + "' doesn't start with artifact ID '" + projectId + "'" );
+ }
+
+ MavenArtifactFacet facet = new MavenArtifactFacet();
+
+ int index = projectId.length() + 1;
+ String version;
+ String idSubStrFromVersion = id.substring( index );
+ if ( idSubStrFromVersion.startsWith( projectVersion ) && !VersionUtil.isUniqueSnapshot( projectVersion ) )
+ {
+ // non-snapshot versions, or non-timestamped snapshot versions
+ version = projectVersion;
+ }
+ else if ( VersionUtil.isGenericSnapshot( projectVersion ) )
+ {
+ // timestamped snapshots
+ try
+ {
+ int mainVersionLength = projectVersion.length() - 8; // 8 is length of "SNAPSHOT"
+ if ( mainVersionLength == 0 )
+ {
+ throw new IllegalArgumentException(
+ "Timestamped snapshots must contain the main version, filename was '" + id + "'" );
+ }
+
+ Matcher m = TIMESTAMP_PATTERN.matcher( idSubStrFromVersion.substring( mainVersionLength ) );
+ m.matches();
+ String timestamp = m.group( 1 );
+ String buildNumber = m.group( 2 );
+ facet.setTimestamp( timestamp );
+ facet.setBuildNumber( Integer.parseInt( buildNumber ) );
+ version = idSubStrFromVersion.substring( 0, mainVersionLength ) + timestamp + "-" + buildNumber;
+ }
+ catch ( IllegalStateException e )
+ {
+ throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
+ + "' doesn't contain a timestamped version matching snapshot '"
+ + projectVersion + "'", e);
+ }
+ }
+ else
+ {
+ // invalid
+ throw new IllegalArgumentException(
+ "Not a valid artifact path in a Maven 2 repository, filename '" + id + "' doesn't contain version '"
+ + projectVersion + "'" );
+ }
+
+ String classifier;
+ String ext;
+ index += version.length();
+ if ( index == id.length() )
+ {
+ // no classifier or extension
+ classifier = null;
+ ext = null;
+ }
+ else
+ {
+ char c = id.charAt( index );
+ if ( c == '-' )
+ {
+ // classifier up until '.'
+ int extIndex = id.indexOf( '.', index );
+ if ( extIndex >= 0 )
+ {
+ classifier = id.substring( index + 1, extIndex );
+ ext = id.substring( extIndex + 1 );
+ }
+ else
+ {
+ classifier = id.substring( index + 1 );
+ ext = null;
+ }
+ }
+ else if ( c == '.' )
+ {
+ // rest is the extension
+ classifier = null;
+ ext = id.substring( index + 1 );
+ }
+ else
+ {
+ throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
+ + "' expected classifier or extension but got '"
+ + id.substring( index ) + "'" );
+ }
+ }
+
+ ArtifactMetadata metadata = new ArtifactMetadata();
+ metadata.setId( id );
+ metadata.setNamespace( namespace );
+ metadata.setProject( projectId );
+ metadata.setRepositoryId( repoId );
+ metadata.setProjectVersion( projectVersion );
+ metadata.setVersion( version );
+
+ facet.setClassifier( classifier );
+
+ // we use our own provider here instead of directly accessing Maven's artifact handlers as it has no way
+ // to select the correct order to apply multiple extensions mappings to a preferred type
+ // TODO: this won't allow the user to decide order to apply them if there are conflicts or desired changes -
+ // perhaps the plugins could register missing entries in configuration, then we just use configuration
+ // here?
+
+ String type = null;
+
+
+ // use extension as default
+ if ( type == null )
+ {
+ type = ext;
+ }
+
+ // TODO: should we allow this instead?
+ if ( type == null )
+ {
+ throw new IllegalArgumentException(
+ "Not a valid artifact path in a Maven 2 repository, filename '" + id + "' does not have a type" );
+ }
+
+ facet.setType( type );
+ metadata.addFacet( facet );
+
+ return metadata;
+ }
+
+
+ private String formatAsDirectory( String directory )
+ {
+ return directory.replace( GROUP_SEPARATOR, PATH_SEPARATOR );
+ }
+
+ @Override
+ public String toPath( ItemSelector selector )
+ {
+ return null;
+ }
+
+ @Override
+ public ItemSelector toItemSelector( String path ) throws LayoutException
+ {
+ return null;
+ }
+
+ @Override
+ public ManagedRepositoryContent getGenericContent( )
+ {
+ return null;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy.mock.repository;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.common.utils.VersionUtil;
+import org.apache.archiva.repository.content.LayoutException;
+import org.apache.archiva.repository.RemoteRepository;
+import org.apache.archiva.repository.RemoteRepositoryContent;
+import org.apache.archiva.repository.content.ItemSelector;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author Martin Stockhammer <martin_s@apache.org>
+ */
+@Service("remoteRepositoryContent#mock")
+public class RemoteRepositoryContentMock implements RemoteRepositoryContent
+{
+ RemoteRepository repository;
+
+ RemoteRepositoryContentMock(RemoteRepository repo) {
+ this.repository = repo;
+ }
+
+ @Override
+ public String getId( )
+ {
+ return repository.getId();
+ }
+
+ @Override
+ public RemoteRepository getRepository( )
+ {
+ return repository;
+ }
+
+ @Override
+ public void setRepository( RemoteRepository repo )
+ {
+ this.repository = repo;
+ }
+
+ @Override
+ public String toPath( ItemSelector selector )
+ {
+ String baseVersion;
+ if (!selector.hasVersion() && VersionUtil.isSnapshot(selector.getArtifactVersion())) {
+ baseVersion=VersionUtil.getBaseVersion(selector.getArtifactVersion());
+ } else {
+ baseVersion=selector.getVersion();
+ }
+ return selector.getNamespace().replaceAll("\\.", "/")+"/"+selector.getArtifactId()+"/"+baseVersion+"/"
+ +selector.getArtifactId()+"-"+selector.getVersion()+(
+ StringUtils.isNotEmpty(selector.getClassifier()) ? "-"+selector.getClassifier() : "")+"."+selector.getType();
+ }
+
+ @Override
+ public ItemSelector toItemSelector( String path ) throws LayoutException
+ {
+ return null;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.maven.proxy.mock.repository;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.repository.*;
+import org.springframework.stereotype.Service;
+
+import java.util.HashSet;
+import java.util.Set;
+
+@Service("repositoryContentProvider#mock")
+public class RepositoryContentProviderMock implements RepositoryContentProvider {
+
+ private static final Set<RepositoryType> REPOSITORY_TYPES = new HashSet<>();
+ static {
+ REPOSITORY_TYPES.add(RepositoryType.MAVEN);
+ REPOSITORY_TYPES.add(RepositoryType.NPM);
+ }
+
+ @Override
+ public boolean supportsLayout(String layout) {
+ return true;
+ }
+
+ @Override
+ public Set<RepositoryType> getSupportedRepositoryTypes() {
+ return REPOSITORY_TYPES;
+ }
+
+ @Override
+ public boolean supports(RepositoryType type) {
+ return true;
+ }
+
+ @Override
+ public RemoteRepositoryContent createRemoteContent(RemoteRepository repository) throws RepositoryException {
+ return new RemoteRepositoryContentMock(repository);
+ }
+
+ @Override
+ public ManagedRepositoryContent createManagedContent( ManagedRepository repository) throws RepositoryException {
+ return new ManagedRepositoryContentMock(repository);
+ }
+
+ @Override
+ public <T extends RepositoryContent, V extends Repository> T createContent(Class<T> clazz, V repository) throws RepositoryException {
+ return null;
+ }
+}
--- /dev/null
+package org.apache.archiva.maven.proxy.mock.repository;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
+import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
+import org.apache.archiva.configuration.RepositoryGroupConfiguration;
+import org.apache.archiva.event.EventHandler;
+import org.apache.archiva.repository.base.managed.BasicManagedRepository;
+import org.apache.archiva.repository.base.remote.BasicRemoteRepository;
+import org.apache.archiva.repository.EditableManagedRepository;
+import org.apache.archiva.repository.EditableRemoteRepository;
+import org.apache.archiva.repository.EditableRepositoryGroup;
+import org.apache.archiva.repository.ManagedRepository;
+import org.apache.archiva.repository.base.PasswordCredentials;
+import org.apache.archiva.repository.ReleaseScheme;
+import org.apache.archiva.repository.RemoteRepository;
+import org.apache.archiva.repository.RepositoryCredentials;
+import org.apache.archiva.event.Event;
+import org.apache.archiva.repository.RepositoryException;
+import org.apache.archiva.repository.RepositoryGroup;
+import org.apache.archiva.repository.RepositoryProvider;
+import org.apache.archiva.repository.RepositoryType;
+import org.apache.archiva.repository.event.RepositoryEvent;
+import org.apache.archiva.repository.features.ArtifactCleanupFeature;
+import org.apache.archiva.repository.features.IndexCreationFeature;
+import org.apache.archiva.repository.features.RemoteIndexFeature;
+import org.apache.archiva.repository.features.StagingRepositoryFeature;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.time.Period;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Just a simple mock class for the repository provider
+ */
+@Service("mockRepositoryProvider")
+public class RepositoryProviderMock implements RepositoryProvider
+{
+
+ private static final Set<RepositoryType> TYPES = new HashSet<>( );
+
+ static
+ {
+ TYPES.add( RepositoryType.MAVEN );
+ TYPES.add( RepositoryType.NPM );
+ }
+
+ @Override
+ public Set<RepositoryType> provides( )
+ {
+ return TYPES;
+ }
+
+ @Override
+ public EditableManagedRepository createManagedInstance( String id, String name ) throws IOException {
+ return BasicManagedRepository.newFilesystemInstance(id, name, Paths.get("target/repositories").resolve(id));
+ }
+
+ @Override
+ public EditableRemoteRepository createRemoteInstance( String id, String name )
+ {
+ try {
+ return BasicRemoteRepository.newFilesystemInstance( id, name, Paths.get("target/remotes") );
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public EditableRepositoryGroup createRepositoryGroup( String id, String name )
+ {
+ return null;
+ }
+
+ @Override
+ public ManagedRepository createManagedInstance( ManagedRepositoryConfiguration configuration ) throws RepositoryException
+ {
+ BasicManagedRepository managedRepository = null;
+ try {
+ managedRepository = BasicManagedRepository.newFilesystemInstance( configuration.getId( ), configuration.getName( ) , Paths.get("target/repositories").resolve(configuration.getId()));
+ } catch (IOException e) {
+ throw new RepositoryException(e);
+ }
+ updateManagedInstance( managedRepository, configuration );
+ return managedRepository;
+ }
+
+
+ @Override
+ public void updateManagedInstance( EditableManagedRepository managedRepository, ManagedRepositoryConfiguration configuration ) throws RepositoryException
+ {
+ try
+ {
+ managedRepository.setName( managedRepository.getPrimaryLocale(), configuration.getName( ) );
+ managedRepository.setLocation( new URI( configuration.getLocation( )==null ?"" : configuration.getLocation() ) );
+ managedRepository.setBaseUri( new URI( "" ) );
+ managedRepository.setBlocksRedeployment( configuration.isBlockRedeployments( ) );
+ managedRepository.setDescription( managedRepository.getPrimaryLocale(), configuration.getDescription( ) );
+ managedRepository.setLayout( configuration.getLayout( ) );
+ managedRepository.setScanned( configuration.isScanned( ) );
+ managedRepository.setSchedulingDefinition( configuration.getRefreshCronExpression( ) );
+ if (configuration.isReleases()) {
+ managedRepository.addActiveReleaseScheme( ReleaseScheme.RELEASE );
+ }
+ if (configuration.isSnapshots()) {
+ managedRepository.addActiveReleaseScheme( ReleaseScheme.SNAPSHOT );
+ }
+ ArtifactCleanupFeature acf = managedRepository.getFeature( ArtifactCleanupFeature.class ).get( );
+ acf.setRetentionPeriod( Period.ofDays( configuration.getRetentionPeriod( ) ) );
+ acf.setDeleteReleasedSnapshots( configuration.isDeleteReleasedSnapshots( ) );
+ acf.setRetentionCount( configuration.getRetentionCount( ) );
+ IndexCreationFeature icf = managedRepository.getFeature( IndexCreationFeature.class ).get( );
+ icf.setIndexPath( new URI( configuration.getIndexDir( ) ) );
+ icf.setSkipPackedIndexCreation( configuration.isSkipPackedIndexCreation( ) );
+ StagingRepositoryFeature srf = managedRepository.getFeature( StagingRepositoryFeature.class ).get( );
+ srf.setStageRepoNeeded( configuration.isStageRepoNeeded( ) );
+ }
+ catch ( Exception e )
+ {
+ throw new RepositoryException( "Error", e );
+ }
+
+ }
+
+
+ @Override
+ public ManagedRepository createStagingInstance( ManagedRepositoryConfiguration configuration ) throws RepositoryException
+ {
+ String id = configuration.getId( ) + StagingRepositoryFeature.STAGING_REPO_POSTFIX;
+ BasicManagedRepository managedRepository = null;
+ try {
+ managedRepository = BasicManagedRepository.newFilesystemInstance(id, configuration.getName(), Paths.get("target/repositories").resolve(id));
+ } catch (IOException e) {
+ throw new RepositoryException(e);
+ }
+ updateManagedInstance( managedRepository, configuration );
+ return managedRepository;
+ }
+
+ @Override
+ public RemoteRepository createRemoteInstance( RemoteRepositoryConfiguration configuration ) throws RepositoryException
+ {
+ BasicRemoteRepository remoteRepository = null;
+ try {
+ remoteRepository = BasicRemoteRepository.newFilesystemInstance( configuration.getId( ), configuration.getName( ), Paths.get("target/remotes") );
+ } catch (IOException e) {
+ throw new RepositoryException(e);
+ }
+ updateRemoteInstance( remoteRepository, configuration );
+ return remoteRepository;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void updateRemoteInstance( EditableRemoteRepository remoteRepository, RemoteRepositoryConfiguration configuration ) throws RepositoryException
+ {
+ try
+ {
+ remoteRepository.setName( remoteRepository.getPrimaryLocale(), configuration.getName( ) );
+ remoteRepository.setBaseUri( new URI( "" ) );
+ remoteRepository.setDescription( remoteRepository.getPrimaryLocale(), configuration.getDescription( ) );
+ remoteRepository.setLayout( configuration.getLayout( ) );
+ remoteRepository.setSchedulingDefinition( configuration.getRefreshCronExpression( ) );
+ remoteRepository.setCheckPath( configuration.getCheckPath( ) );
+ remoteRepository.setExtraHeaders( configuration.getExtraHeaders( ) );
+ remoteRepository.setExtraParameters( configuration.getExtraParameters( ) );
+ remoteRepository.setTimeout( Duration.ofSeconds( configuration.getTimeout( ) ) );
+ char[] pwd = configuration.getPassword()==null ? "".toCharArray() : configuration.getPassword().toCharArray();
+ remoteRepository.setCredentials( new PasswordCredentials( configuration.getUsername( ), pwd ) );
+ remoteRepository.setLocation( new URI( configuration.getUrl( )==null ? "" : configuration.getUrl() ) );
+ RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
+ rif.setDownloadRemoteIndexOnStartup( configuration.isDownloadRemoteIndexOnStartup( ) );
+ rif.setDownloadRemoteIndex( configuration.isDownloadRemoteIndex( ) );
+ rif.setIndexUri( new URI( configuration.getIndexDir( ) ) );
+ rif.setDownloadTimeout( Duration.ofSeconds( configuration.getRemoteDownloadTimeout( ) ) );
+ rif.setProxyId( configuration.getRemoteDownloadNetworkProxyId( ) );
+ IndexCreationFeature icf = remoteRepository.getFeature(IndexCreationFeature.class).get();
+ icf.setIndexPath(new URI(".index" ));
+ }
+ catch ( Exception e )
+ {
+ throw new RepositoryException( "Error while updating remote instance: "+e.getMessage(), e );
+ }
+
+ }
+
+ @Override
+ public RepositoryGroup createRepositoryGroup( RepositoryGroupConfiguration configuration ) throws RepositoryException
+ {
+ return null;
+ }
+
+ @Override
+ public void updateRepositoryGroupInstance( EditableRepositoryGroup repositoryGroup, RepositoryGroupConfiguration configuration ) throws RepositoryException
+ {
+
+ }
+
+ @Override
+ public ManagedRepositoryConfiguration getManagedConfiguration( ManagedRepository managedRepository ) throws RepositoryException
+ {
+ ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration( );
+ configuration.setId( managedRepository.getId( ) );
+ configuration.setName(managedRepository.getName());
+ configuration.setLocation( managedRepository.getLocation( ) == null ? "" : managedRepository.getLocation().toString( ) );
+ configuration.setBlockRedeployments( managedRepository.blocksRedeployments( ) );
+ configuration.setDescription( managedRepository.getDescription( ) );
+ configuration.setLayout( managedRepository.getLayout( ) );
+ configuration.setScanned( managedRepository.isScanned( ) );
+ configuration.setRefreshCronExpression( managedRepository.getSchedulingDefinition( ) );
+ configuration.setReleases( managedRepository.getActiveReleaseSchemes().contains(ReleaseScheme.RELEASE) );
+ configuration.setSnapshots( managedRepository.getActiveReleaseSchemes().contains(ReleaseScheme.SNAPSHOT) );
+ ArtifactCleanupFeature acf = managedRepository.getFeature( ArtifactCleanupFeature.class ).get( );
+ configuration.setRetentionPeriod( acf.getRetentionPeriod( ).getDays( ) );
+ configuration.setDeleteReleasedSnapshots( acf.isDeleteReleasedSnapshots( ) );
+ configuration.setRetentionCount( acf.getRetentionCount( ) );
+ IndexCreationFeature icf = managedRepository.getFeature( IndexCreationFeature.class ).get( );
+ configuration.setSkipPackedIndexCreation( icf.isSkipPackedIndexCreation( ) );
+ configuration.setIndexDir( icf.getIndexPath( ) == null ? "" : icf.getIndexPath().toString( ) );
+ StagingRepositoryFeature srf = managedRepository.getFeature( StagingRepositoryFeature.class ).get( );
+ configuration.setStageRepoNeeded( srf.isStageRepoNeeded( ) );
+ return configuration;
+ }
+
+ @Override
+ public RepositoryGroupConfiguration getRepositoryGroupConfiguration( RepositoryGroup repositoryGroup ) throws RepositoryException
+ {
+ return null;
+ }
+
+ @Override
+ public void addRepositoryEventHandler( EventHandler<? super RepositoryEvent> eventHandler )
+ {
+ // do nothing
+ }
+
+
+ @Override
+ public RemoteRepositoryConfiguration getRemoteConfiguration( RemoteRepository remoteRepository ) throws RepositoryException
+ {
+ RemoteRepositoryConfiguration configuration = new RemoteRepositoryConfiguration( );
+ configuration.setId( remoteRepository.getId( ) );
+ configuration.setName( remoteRepository.getName( ) );
+ configuration.setDescription( remoteRepository.getDescription( ) );
+ configuration.setLayout( remoteRepository.getLayout( ) );
+ configuration.setRefreshCronExpression( remoteRepository.getSchedulingDefinition( ) );
+ configuration.setCheckPath( remoteRepository.getCheckPath( ) );
+ configuration.setExtraHeaders( remoteRepository.getExtraHeaders( ) );
+ configuration.setExtraParameters( remoteRepository.getExtraParameters( ) );
+ configuration.setTimeout( (int) remoteRepository.getTimeout( ).getSeconds( ) );
+ RepositoryCredentials creds = remoteRepository.getLoginCredentials( );
+ if (creds!=null)
+ {
+ PasswordCredentials pwdCreds = (PasswordCredentials) creds;
+ configuration.setUsername( pwdCreds.getUsername( ) );
+ configuration.setPassword( new String( pwdCreds.getPassword( ) ) );
+ }
+ configuration.setUrl( remoteRepository.getLocation( ) == null ? "" : remoteRepository.getLocation().toString( ) );
+ RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
+ configuration.setDownloadRemoteIndex( rif.isDownloadRemoteIndex( ) );
+ configuration.setDownloadRemoteIndexOnStartup( rif.isDownloadRemoteIndexOnStartup( ) );
+ configuration.setIndexDir( rif.getIndexUri( )==null ? "" : rif.getIndexUri().toString( ) );
+ configuration.setRemoteDownloadNetworkProxyId( rif.getProxyId( ) );
+ return configuration;
+ }
+
+ @Override
+ public void handle(Event event) {
+
+ }
+}
+++ /dev/null
-package org.apache.archiva.metadata.repository;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.archiva.components.taskqueue.TaskQueueException;
-import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
-import org.apache.archiva.scheduler.repository.model.RepositoryTask;
-import org.springframework.stereotype.Service;
-
-/**
- * @author Olivier Lamy
- */
-@Service ("archivaTaskScheduler#repositoryMock")
-public class MockRepositoryArchivaTaskScheduler
- implements RepositoryArchivaTaskScheduler
-{
- @Override
- public boolean isProcessingRepositoryTask( String repositoryId )
- {
- return false;
- }
-
- @Override
- public boolean isProcessingRepositoryTask( RepositoryTask task )
- {
- return false;
- }
-
- @Override
- public void queueTask( RepositoryTask task )
- throws TaskQueueException
- {
- // no op
- }
-
- @Override
- public boolean unQueueTask( RepositoryTask task )
- throws TaskQueueException
- {
- return false;
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import net.sf.ehcache.CacheManager;
-import org.apache.archiva.configuration.ArchivaConfiguration;
-import org.apache.archiva.configuration.ArchivaRuntimeConfiguration;
-import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
-import org.apache.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
-import org.apache.archiva.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.PolicyOption;
-import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
-import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.proxy.model.RepositoryProxyHandler;
-import org.apache.archiva.repository.ManagedRepository;
-import org.apache.archiva.repository.ManagedRepositoryContent;
-import org.apache.archiva.repository.RepositoryRegistry;
-import org.apache.archiva.repository.RepositoryType;
-import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
-import org.apache.archiva.repository.base.managed.BasicManagedRepository;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
-import org.apache.maven.wagon.Wagon;
-import org.easymock.EasyMock;
-import org.easymock.IMocksControl;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-
-import javax.inject.Inject;
-import java.io.BufferedReader;
-import java.io.FileReader;
-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.nio.file.attribute.FileTime;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-import static org.junit.Assert.*;
-
-/**
- * AbstractProxyTestCase
- */
-@RunWith( ArchivaSpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
-public abstract class AbstractProxyTestCase
-{
- @Inject
- protected ApplicationContext applicationContext;
-
- @Inject
- private ProxyRegistry proxyRegistry;
-
- @Inject
- RepositoryRegistry repositoryRegistry;
-
- @SuppressWarnings( "unused" )
- @Inject
- RepositoryHandlerDependencies repositoryHandlerDependencies;
-
- protected static final String ID_PROXIED1 = "proxied1";
-
- protected static final String ID_PROXIED1_TARGET = "proxied1-target";
-
- protected static final String ID_PROXIED2 = "proxied2";
-
- protected static final String ID_PROXIED2_TARGET = "proxied2-target";
-
- protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
-
- protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
-
- protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
-
- protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
-
- protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
-
- protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
-
- // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
-
- protected IMocksControl wagonMockControl;
-
- protected Wagon wagonMock;
-
-
- protected RepositoryProxyHandler proxyHandler;
-
- protected ManagedRepositoryContent managedDefaultRepository;
-
- protected Path managedDefaultDir;
-
- protected MockConfiguration config;
-
- protected Logger log = LoggerFactory.getLogger( getClass() );
-
- WagonDelegate delegate;
-
- @Before
- public void setUp()
- throws Exception
- {
- config =
- (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
-
- config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
- config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
- ArchivaRuntimeConfiguration runtimeConfiguration = new ArchivaRuntimeConfiguration();
- List<String> checksumTypes = new ArrayList<>();
- checksumTypes.add("md5");
- checksumTypes.add("sha256");
- checksumTypes.add("sha1");
- checksumTypes.add("asc");
- runtimeConfiguration.setChecksumTypes(checksumTypes);
- config.getConfiguration().setArchivaRuntimeConfiguration(runtimeConfiguration);
- repositoryRegistry.setArchivaConfiguration( config );
-
- // Setup source repository (using default layout)
- String name = getClass().getSimpleName();
- Path repoPath = Paths.get("target/test-repository/managed/" + name);
-
- managedDefaultRepository =
- createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath.toString(), "default" );
-
- managedDefaultDir = repoPath.resolve(ID_DEFAULT_MANAGED) ;
-
- org.apache.archiva.repository.ManagedRepository repoConfig = repositoryRegistry.getManagedRepository(ID_DEFAULT_MANAGED);
-
- // Setup target (proxied to) repository.
- saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
- Paths.get( REPOPATH_PROXIED1 ).toUri().toURL().toExternalForm(), "default" );
-
- // Setup target (proxied to) repository.
- saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
- Paths.get( REPOPATH_PROXIED2 ).toUri().toURL().toExternalForm(), "default" );
-
-
- repositoryRegistry.reload();
- repositoryRegistry.putRepository(repoConfig);
-
-
- // Setup the proxy handler.
- //proxyHandler = applicationContext.getBean (RepositoryProxyHandler) lookup( RepositoryProxyHandler.class.getName() );
-
- proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
- assertNotNull( proxyRegistry );
- assertTrue(proxyRegistry.getAllHandler( ).get( RepositoryType.MAVEN).contains( proxyHandler ));
-
-
- // Setup the wagon mock.
- wagonMockControl = EasyMock.createNiceControl();
- wagonMock = wagonMockControl.createMock( Wagon.class );
-
- delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
-
- delegate.setDelegate( wagonMock );
-
- CacheManager.getInstance().clearAll();
-
- log.info( "\n.\\ {}() \\._________________________________________\n", name );
- }
-
- protected void assertChecksums( Path expectedFile, String expectedSha1Contents, String expectedMd5Contents )
- throws Exception
- {
- Path sha1File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString()+ ".sha1" );
- Path md5File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString() + ".md5" );
-
- if ( expectedSha1Contents == null )
- {
- assertFalse( "SHA1 File should NOT exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
- }
- else
- {
- assertTrue( "SHA1 File should exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
- String actualSha1Contents = readChecksumFile( sha1File );
- assertEquals( "SHA1 File contents: " + sha1File.toAbsolutePath(), expectedSha1Contents, actualSha1Contents );
- }
-
- if ( expectedMd5Contents == null )
- {
- assertFalse( "MD5 File should NOT exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
- }
- else
- {
- assertTrue( "MD5 File should exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
- String actualMd5Contents = readChecksumFile( md5File );
- assertEquals( "MD5 File contents: " + md5File.toAbsolutePath(), expectedMd5Contents, actualMd5Contents );
- }
- }
-
- protected void assertFileEquals( Path expectedFile, Path actualFile, Path sourceFile )
- throws Exception
- {
- assertNotNull( "Expected File should not be null.", expectedFile );
- assertNotNull( "Actual File should not be null.", actualFile );
-
- assertTrue( "Check actual file exists.", Files.exists(actualFile) );
- assertTrue("Check expected file exists", Files.exists(expectedFile));
- assertTrue( "Check file is the same.", Files.isSameFile( expectedFile,
- actualFile));
- String expectedContents =
- org.apache.commons.io.FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
- String actualContents =
- org.apache.commons.io.FileUtils.readFileToString( actualFile.toFile(), Charset.defaultCharset() );
- assertEquals( "Check file contents.", expectedContents, actualContents );
- }
-
- protected void assertNotDownloaded( StorageAsset downloadedFile )
- {
- assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
- }
-
- @SuppressWarnings( "unchecked" )
- protected void assertNoTempFiles( Path expectedFile )
- {
- Path workingDir = expectedFile.getParent();
- if ( ( workingDir == null ) || !Files.isDirectory( workingDir) )
- {
- return;
- }
-
- Collection<Path> tmpFiles = null;
- try {
- tmpFiles = Files.list(workingDir).filter(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".tmp")).collect(Collectors.toList());
- } catch (IOException e) {
- log.error("Could not retrieve tmpFiles {}", workingDir);
- }
- if ( tmpFiles!=null && !tmpFiles.isEmpty() )
- {
- StringBuilder emsg = new StringBuilder();
- emsg.append( "Found Temp Files in dir: " ).append( workingDir.toString() );
- for ( Path tfile : tmpFiles )
- {
- emsg.append( "\n " ).append( tfile.getFileName().toString());
- }
- fail( emsg.toString() );
- }
- }
-
- /**
- * A faster recursive copy that omits .svn directories.
- *
- * @param sourceDirectory the source directory to copy
- * @param destDirectory the target location
- * @throws java.io.IOException if there is a copying problem
- * @todo get back into plexus-utils, share with converter module
- */
- protected void copyDirectoryStructure( Path sourceDirectory, Path destDirectory )
- throws IOException
- {
- if ( !Files.exists(sourceDirectory) )
- {
- throw new IOException( "Source directory doesn't exists (" + sourceDirectory.toAbsolutePath() + ")." );
- }
-
- Path[] files = Files.list(sourceDirectory).filter(path -> Files.isRegularFile(path)).toArray(Path[]::new);
-
- String sourcePath = sourceDirectory.toAbsolutePath().toString();
-
- for ( int i = 0; i < files.length; i++ )
- {
- Path file = files[i];
-
- String dest = file.toAbsolutePath().toString();
-
- dest = dest.substring( sourcePath.length() + 1 );
-
- Path destination = destDirectory.resolve( dest );
-
- if ( Files.isRegularFile(file) )
- {
- destination = destination.getParent();
-
- org.apache.commons.io.FileUtils.copyFile( file.toFile(), destination.resolve( file.getFileName() ).toFile(), false );
- // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
- //FileUtils.copyFileToDirectory( file, destination );
- }
- else if ( Files.isDirectory(file) )
- {
- if ( !".svn".equals( file.getFileName().toString() ) )
- {
- if ( !Files.exists(destination))
- {
- Files.createDirectories(destination);
- }
-
- copyDirectoryStructure( file, destination );
- }
- }
- else
- {
- throw new IOException( "Unknown file type: " + file.toAbsolutePath() );
- }
- }
- }
-
-
- protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
- throws Exception
- {
- ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
- repositoryRegistry.putRepository(repo);
- return repositoryRegistry.getManagedRepository(id).getContent();
- }
-
- /**
- * Read the first line from the checksum file, and return it (trimmed).
- */
- protected String readChecksumFile( Path checksumFile )
- throws Exception
- {
- FileReader freader = null;
- BufferedReader buf = null;
-
- try
- {
- freader = new FileReader( checksumFile.toFile() );
- buf = new BufferedReader( freader );
- return buf.readLine();
- }
- finally
- {
- if ( buf != null )
- {
- buf.close();
- }
-
- if ( freader != null )
- {
- freader.close();
- }
- }
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
- {
- saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
- CachedFailuresPolicy.NO, disabled );
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
- PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, boolean disabled )
- {
- saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
- PropagateErrorsDownloadPolicy.QUEUE, disabled );
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
- PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
- boolean disabled )
- {
- saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
- errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
- }
-
- protected void saveConnector(String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
- PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
- PolicyOption errorOnUpdatePolicy, boolean disabled )
- {
- ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
- connectorConfig.setSourceRepoId( sourceRepoId );
- connectorConfig.setTargetRepoId( targetRepoId );
- connectorConfig.setProxyId(sourceRepoId);
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy.getId());
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy.getId() );
- connectorConfig.setDisabled( disabled );
-
- int count = config.getConfiguration().getProxyConnectors().size();
- config.getConfiguration().addProxyConnector( connectorConfig );
-
- // Proper Triggering ...
- String prefix = "proxyConnectors.proxyConnector(" + count + ")";
- config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
- config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
- config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
- config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
- config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
- config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
- config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
- config.triggerChange( prefix + ".policies.propagate-errors",
- connectorConfig.getPolicy( "propagate-errors", "" ) );
- config.triggerChange( prefix + ".policies.propagate-errors-on-update",
- connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
- }
-
- protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
- {
- ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
-
- repoConfig.setId( id );
- repoConfig.setName( name );
- repoConfig.setLayout( layout );
-
- repoConfig.setLocation( path );
-
- int count = config.getConfiguration().getManagedRepositories().size();
- config.getConfiguration().addManagedRepository( repoConfig );
-
- String prefix = "managedRepositories.managedRepository(" + count + ")";
- config.triggerChange( prefix + ".id", repoConfig.getId() );
- config.triggerChange( prefix + ".name", repoConfig.getName() );
- config.triggerChange( prefix + ".location", repoConfig.getLocation() );
- config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
- }
-
- protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
- {
- RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
-
- repoConfig.setId( id );
- repoConfig.setName( name );
- repoConfig.setLayout( layout );
- repoConfig.setUrl( url );
-
- int count = config.getConfiguration().getRemoteRepositories().size();
- config.getConfiguration().addRemoteRepository( repoConfig );
-
- String prefix = "remoteRepositories.remoteRepository(" + count + ")";
- config.triggerChange( prefix + ".id", repoConfig.getId() );
- config.triggerChange( prefix + ".name", repoConfig.getName() );
- config.triggerChange( prefix + ".url", repoConfig.getUrl() );
- config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
- repositoryRegistry.reload();
- }
-
- protected Path saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
- throws IOException
- {
- Path repoLocation = Paths.get( targetPath );
- org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoLocation );
- copyDirectoryStructure( Paths.get(originalPath) , repoLocation );
-
- saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
-
- return repoLocation;
- }
-
-
- /**
- * Copy the specified resource directory from the src/test/repository/managed/ to
- * the testable directory under target/test-repository/managed/${testName}/
- *
- * @param resourcePath
- * @throws IOException
- */
- protected void setupTestableManagedRepository( String resourcePath )
- throws IOException
- {
- String resourceDir = resourcePath;
-
- if ( !resourcePath.endsWith( "/" ) )
- {
- int idx = resourcePath.lastIndexOf( '/' );
- resourceDir = resourcePath.substring( 0, idx );
- }
-
- Path sourceRepoDir = Paths.get( REPOPATH_DEFAULT_MANAGED );
- Path sourceDir = sourceRepoDir.resolve(resourceDir );
-
- Path destRepoDir = managedDefaultDir;
- Path destDir = destRepoDir.resolve(resourceDir );
-
- // Cleanout destination dirs.
- if ( Files.exists(destDir))
- {
- org.apache.archiva.common.utils.FileUtils.deleteDirectory( destDir );
- }
-
- // Make the destination dir.
- Files.createDirectories(destDir);
-
- // Test the source dir.
- if ( !Files.exists(sourceDir) )
- {
- // This is just a warning.
- log.error( "[WARN] Skipping setup of testable managed repository, source dir does not exist: {}", //
- sourceDir );
- }
- else
- {
-
- // Test that the source is a dir.
- if ( !Files.isDirectory( sourceDir) )
- {
- fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
- }
-
- // Copy directory structure.
- copyDirectoryStructure( sourceDir, destDir );
- }
- }
-
- protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile )
- {
- setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
- }
-
- protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile, long time )
- {
- assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
- assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
-
- try
- {
- Files.setLastModifiedTime( managedFile,
- FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() + time, TimeUnit.MILLISECONDS ));
- }
- catch ( IOException e )
- {
- e.printStackTrace( );
- }
-
- try
- {
- assertTrue( Files.getLastModifiedTime( managedFile).compareTo( Files.getLastModifiedTime( remoteFile )) > 0);
- }
- catch ( IOException e )
- {
- e.printStackTrace( );
- }
- }
-
- protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile )
- {
- setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
- }
-
- protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile, long time )
- {
- assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
- assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
-
- try
- {
- Files.setLastModifiedTime( managedFile,
- FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() - time, TimeUnit.MILLISECONDS ));
- }
- catch ( IOException e )
- {
- e.printStackTrace( );
- }
-
- try
- {
- assertTrue( Files.getLastModifiedTime( managedFile ).compareTo(Files.getLastModifiedTime( remoteFile )) < 0 );
- }
- catch ( IOException e )
- {
- e.printStackTrace( );
- }
-
- }
-
- protected void assertNotModified( Path file, long expectedModificationTime )
- {
- try
- {
- assertEquals( "File <" + file.toAbsolutePath() + "> not have been modified.", expectedModificationTime,
- Files.getLastModifiedTime( file ).toMillis());
- }
- catch ( IOException e )
- {
- e.printStackTrace( );
- }
- }
-
-
- protected void assertNotExistsInManagedDefaultRepo( Path testFile )
- throws Exception
- {
- Path managedDefaultPath = managedDefaultDir;
-
- assertTrue( "Unit Test Failure: File <" + testFile
- + "> should be have been defined within the managed default path of <" + managedDefaultPath
- + ">", testFile.startsWith( managedDefaultPath ) );
-
- assertFalse( "File < " + testFile + "> should not exist in managed default repository.", Files.exists(testFile) );
- }
-
- protected static Date getFutureDate()
- throws ParseException
- {
- Calendar cal = Calendar.getInstance();
- cal.add( Calendar.YEAR, 1 );
- return cal.getTime();
- }
-
- protected static Date getPastDate()
- throws ParseException
- {
- return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.utils.PathUtil;
-import org.apache.archiva.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.policies.urlcache.UrlFailureCache;
-import org.apache.archiva.repository.content.Artifact;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import javax.inject.Inject;
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-
-/**
- * CacheFailuresTransferTest
- */
-public class CacheFailuresTransferTest
- extends AbstractProxyTestCase
-{
- // TODO: test some hard failures (eg TransferFailedException)
- // TODO: test the various combinations of fetchFrom* (note: need only test when caching is enabled)
-
- @Inject
- UrlFailureCache urlFailureCache;
-
-
- @Test
- public void testGetWithCacheFailuresOn( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- Path expectedFile = managedDefaultDir.resolve( path );
- setupTestableManagedRepository( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
- // ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
- saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "http://bad.machine.com/anotherrepo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
- saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
-
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
-
- EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "resource does not exist." ) ).times( 2 );
-
-
- wagonMockControl.replay( );
-
- //noinspection UnusedAssignment
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- wagonMockControl.verify( );
-
- // Second attempt to download same artifact use cache
- wagonMockControl.reset( );
- wagonMockControl.replay( );
- downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
- wagonMockControl.verify( );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetWithCacheFailuresOff( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- Path expectedFile = managedDefaultDir.resolve( path );
- setupTestableManagedRepository( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
- saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "http://bad.machine.com/anotherrepo/", "default" );
-
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "resource does not exist." ) ).times( 2 );
-
- wagonMockControl.replay( );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- wagonMockControl.verify( );
-
- // Second attempt to download same artifact DOES NOT use cache
- wagonMockControl.reset( );
-
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "resource does not exist." ) ).times( 2 );
-
- wagonMockControl.replay( );
-
- downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- wagonMockControl.verify( );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetWhenInBothProxiedButFirstCacheFailure( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- Files.deleteIfExists( expectedFile );
- assertFalse( Files.exists( expectedFile ) );
-
- String url = PathUtil.toUrl( REPOPATH_PROXIED1 + "/" + path );
-
- // Intentionally set failure on url in proxied1 (for test)
- UrlFailureCache failurlCache = lookupUrlFailureCache( );
- failurlCache.cacheFailure( url );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
- saveConnector( ID_DEFAULT_MANAGED, "proxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- // Validate that file actually came from proxied2 (as intended).
- Path proxied2File = Paths.get( REPOPATH_PROXIED2, path );
- assertNotNull( downloadedFile );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- protected UrlFailureCache lookupUrlFailureCache( )
- throws Exception
- {
- assertNotNull( "URL Failure Cache cannot be null.", urlFailureCache );
- return urlFailureCache;
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.utils.FileUtils;
-import org.apache.archiva.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.content.Artifact;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-
-/**
- * ChecksumTransferTest
- */
-public class ChecksumTransferTest
- extends AbstractProxyTestCase
-{
- @Test
- public void testGetChecksumWhenConnectorIsDisabled( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- org.apache.archiva.common.utils.FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- assertNull( downloadedFile );
- }
-
- @Test
- public void testGetChecksumBothCorrect( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- org.apache.archiva.common.utils.FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "066d76e459f7782c312c31e8a11b3c0f1e3e43a7 *get-checksum-both-right-1.0.jar",
- "e58f30c6a150a2e843552438d18e15cb *get-checksum-both-right-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumCorrectSha1NoMd5( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
- null );
- }
-
- @Test
- public void testGetChecksumNoSha1CorrectMd5( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
- }
-
- @Test
- public void testGetWithNoChecksumsUsingIgnoredSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumBadSha1BadMd5IgnoredSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
- }
-
- @Test
- public void testGetChecksumBadSha1BadMd5FailSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- assertNotDownloaded( downloadedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumBadSha1BadMd5FixSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "4ec20a12dc91557330bd0b39d1805be5e329ae56 get-checksum-both-bad-1.0.jar",
- "a292491a35925465e693a44809a078b5 get-checksum-both-bad-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumCorrectSha1BadMd5UsingFailSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- assertNotDownloaded( downloadedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumNoSha1CorrectMd5UsingFailSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- // This is a success situation. No SHA1 with a Good MD5.
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
- }
-
- @Test
- public void testGetWithNoChecksumsUsingFailSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- assertNotDownloaded( downloadedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumCorrectSha1BadMd5UsingIgnoredSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
- "invalid checksum file" );
- }
-
- @Test
- public void testGetChecksumCorrectSha1BadMd5UsingFixSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
- "c35f3b76268b73a4ba617f6f275c49ab get-checksum-sha1-bad-md5-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumNoSha1CorrectMd5UsingFixSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "71f7dc3f72053a3f2d9fdd6fef9db055ef957ffb get-checksum-md5-only-1.0.jar",
- "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
- }
-
- @Test
- public void testGetWithNoChecksumsUsingFixSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile ) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "1f12821c5e43e1a0b76b9564a6ddb0548ccb9486 get-default-layout-1.0.jar",
- "3f7341545f21226b6f49a3c2704cb9be get-default-layout-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumNotFoundOnRemote( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- FileUtils.deleteDirectory( expectedFile.getParent( ) );
- assertFalse( Files.exists( expectedFile.getParent( ) ) );
- assertFalse( Files.exists( expectedFile ) );
-
- saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "http://bad.machine.com/repo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall( ).once( );
-
- wagonMock.get( EasyMock.eq( path + ".sha1" ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall( ).once( );
-
- wagonMock.get( EasyMock.eq( path + ".md5" ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall( ).andThrow( new ResourceDoesNotExistException( "Resource does not exist." ) ).once( );
-
- wagonMockControl.replay( );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- wagonMockControl.verify( );
-
- // Do what the mock doesn't do.
- Path proxyPath = Paths.get( REPOPATH_PROXIED1, path ).toAbsolutePath( );
- Path localPath = managedDefaultDir.resolve( path ).toAbsolutePath( );
- Files.copy( proxyPath, localPath, StandardCopyOption.REPLACE_EXISTING );
- Files.copy( proxyPath.resolveSibling( proxyPath.getFileName( ) + ".sha1" ),
- localPath.resolveSibling( localPath.getFileName( ) + ".sha1" ), StandardCopyOption.REPLACE_EXISTING );
-
- // Test results.
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
- null );
- }
-
- @Test
- public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingIgnoredSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- Path remoteFile = Paths.get( REPOPATH_PROXIED1, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- // There are no hashcodes on the proxy side to download, hence the local ones should remain invalid.
- assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
- }
-
- @Test
- public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFailSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- Path remoteFile = Paths.get( REPOPATH_PROXIED1, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- // There are no hashcodes on the proxy side to download.
- // The FAIL policy will delete the checksums as bad.
-
- assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
- }
-
- @Test
- public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFixSetting( )
- throws Exception
- {
- String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
- Path remoteFile = Paths.get( REPOPATH_PROXIED1, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository( ), artifact );
-
- Path proxied1File = Paths.get( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath( ), proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "96a08dc80a108cba8efd3b20aec91b32a0b2cbd4 get-bad-local-checksum-1.0.jar",
- "46fdd6ca55bf1d7a7eb0c858f41e0ccd get-bad-local-checksum-1.0.jar" );
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.policies.*;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.content.LayoutException;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.apache.maven.wagon.TransferFailedException;
-import org.apache.maven.wagon.authorization.AuthorizationException;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-import static org.junit.Assert.*;
-
-/**
- * ErrorHandlingTest
- *
- *
- */
-public class ErrorHandlingTest
- extends AbstractProxyTestCase
-{
- private static final String PATH_IN_BOTH_REMOTES_NOT_LOCAL =
- "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
-
- private static final String PATH_IN_BOTH_REMOTES_AND_LOCAL =
- "org/apache/maven/test/get-on-multiple-repos/1.0/get-on-multiple-repos-1.0.pom";
-
- private static final String ID_MOCKED_PROXIED1 = "badproxied1";
-
- private static final String NAME_MOCKED_PROXIED1 = "Bad Proxied 1";
-
- private static final String ID_MOCKED_PROXIED2 = "badproxied2";
-
- private static final String NAME_MOCKED_PROXIED2 = "Bad Proxied 2";
-
- @Test
- public void testPropagateErrorImmediatelyWithErrorThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorImmediatelyWithNotFoundThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
- }
-
- @Test
- public void testPropagateErrorImmediatelyWithSuccessThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorImmediatelyWithNotFoundThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithErrorThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithSuccessThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithNotFoundThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithErrorThenNotFound()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithErrorThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[]{ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2} );
- }
-
- @Test
- public void testPropagateErrorAtEndWithNotFoundThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
- }
-
- @Test
- public void testIgnoreErrorWithErrorThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
- }
-
- @Test
- public void testIgnoreErrorWithSuccessThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
- }
-
- @Test
- public void testIgnoreErrorWithNotFoundThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testIgnoreErrorWithErrorThenNotFound()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testIgnoreErrorWithErrorThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysQueueArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysQueueArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysIgnoreArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysIgnoreArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( Files.exists(expectedFile) );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( Files.exists(expectedFile) );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentQueueArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentQueueArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( Files.exists(expectedFile));
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentIgnoreArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentIgnoreArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- Path expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( Files.exists(expectedFile));
- }
-
- // ------------------------------------------
- // HELPER METHODS
- // ------------------------------------------
-
- private void createMockedProxyConnector( String id, String name, PolicyOption errorPolicy )
- {
- saveRemoteRepositoryConfig( id, name, "http://bad.machine.com/repo/", "default" );
- saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
- CachedFailuresPolicy.NO, errorPolicy, false );
- }
-
- private void createMockedProxyConnector( String id, String name, PolicyOption errorPolicy, PolicyOption errorOnUpdatePolicy )
- {
- saveRemoteRepositoryConfig( id, name, "http://bad.machine.com/repo/", "default" );
- saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
- CachedFailuresPolicy.NO, errorPolicy, errorOnUpdatePolicy, false );
- }
-
- private Path setupRepositoriesWithLocalFileNotPresent( String path )
- throws Exception
- {
- setupTestableManagedRepository( path );
-
- Path file = managedDefaultDir.resolve( path );
-
- assertNotExistsInManagedDefaultRepo( file );
-
- return file;
- }
-
- private Path setupRepositoriesWithLocalFilePresent( String path )
- throws Exception
- {
- setupTestableManagedRepository( path );
-
- Path file = managedDefaultDir.resolve( path );
-
- assertTrue( Files.exists(file) );
-
- return file;
- }
-
- private void simulateGetError( String path, Path expectedFile, Exception throwable )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ));
- EasyMock.expectLastCall().andThrow(throwable );
- }
-
- private void simulateGetIfNewerError( String path, Path expectedFile, TransferFailedException exception )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException, IOException
- {
- wagonMock.getIfNewer( EasyMock.eq( path ), EasyMock.anyObject( File.class ), EasyMock.eq( Files.getLastModifiedTime( expectedFile ).toMillis() ));
- EasyMock.expectLastCall().andThrow( exception );
- }
-
- private Path createExpectedTempFile( Path expectedFile )
- {
- return managedDefaultDir.resolve(expectedFile.getFileName().toString() + ".tmp" ).toAbsolutePath();
- }
-
- private void confirmSingleFailure( String path, String id )
- throws LayoutException
- {
- confirmFailures( path, new String[]{id} );
- }
-
- private void confirmFailures( String path, String[] ids )
- throws LayoutException
- {
- wagonMockControl.replay();
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = null;
- try
- {
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(),
- layout.getArtifact( path ) );
- fail( "Proxy should not have succeeded" );
- }
- catch ( ProxyDownloadException e )
- {
- assertEquals( ids.length, e.getFailures().size() );
- for ( String id : ids )
- {
- assertTrue( e.getFailures().keySet().contains( id ) );
- }
- }
-
- wagonMockControl.verify();
-
- assertNotDownloaded( downloadedFile );
- }
-
- private void confirmSuccess( String path, Path expectedFile, String basedir )
- throws Exception
- {
- StorageAsset downloadedFile = performDownload( path );
-
- Path proxied1File = Paths.get( basedir, path );
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied1File );
- }
-
- private void confirmNotDownloadedNoError( String path )
- throws Exception
- {
- StorageAsset downloadedFile = performDownload( path );
-
- assertNotDownloaded( downloadedFile );
- }
-
- private StorageAsset performDownload( String path )
- throws ProxyDownloadException, LayoutException
- {
- wagonMockControl.replay();
-
- // Attempt the proxy fetch.
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(),
- layout.getArtifact( path ) );
-
- wagonMockControl.verify();
- return downloadedFile;
- }
-
- private static TransferFailedException createTransferException()
- {
- return new TransferFailedException( "test download exception" );
- }
-
- private static ResourceDoesNotExistException createResourceNotFoundException()
- {
- return new ResourceDoesNotExistException( "test download not found" );
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.configuration.ArchivaConfiguration;
-import org.apache.archiva.configuration.NetworkProxyConfiguration;
-import org.apache.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
-import org.apache.archiva.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
-import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.proxy.model.RepositoryProxyHandler;
-import org.apache.archiva.repository.ManagedRepository;
-import org.apache.archiva.repository.ManagedRepositoryContent;
-import org.apache.archiva.repository.RepositoryRegistry;
-import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
-import org.apache.archiva.repository.base.managed.BasicManagedRepository;
-import org.apache.archiva.repository.content.Artifact;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.maven.wagon.Wagon;
-import org.apache.maven.wagon.providers.http.HttpWagon;
-import org.eclipse.jetty.server.Handler;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.handler.AbstractHandler;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.context.ApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-
-import javax.inject.Inject;
-import javax.servlet.ServletException;
-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 static org.junit.Assert.*;
-
-/**
- * Integration test for connecting over a HTTP proxy.
- *
- *
- */
-@RunWith( ArchivaSpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
-public class HttpProxyTransferTest
-{
- private static final String PROXY_ID = "proxy";
-
- private static final String MANAGED_ID = "default-managed-repository";
-
- private static final String PROXIED_ID = "proxied1";
-
- private static final String PROXIED_BASEDIR = "src/test/repositories/proxied1";
-
- private RepositoryProxyHandler proxyHandler;
-
- private ManagedRepositoryContent managedDefaultRepository;
-
- @Inject
- private ApplicationContext applicationContext;
-
- @Inject
- private RepositoryRegistry repositoryRegistry;
-
- @Inject
- private ArchivaConfiguration config;
-
- @Inject
- private ProxyRegistry proxyRegistry;
-
- @SuppressWarnings( "unused" )
- @Inject
- RepositoryHandlerDependencies repositoryHandlerDependencies;
-
-
- private Server server;
-
- protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
- throws Exception
- {
- ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
- repositoryRegistry.putRepository(repo);
- return repositoryRegistry.getManagedRepository(id).getContent();
- }
-
- @Before
- public void setUp()
- throws Exception
- {
- proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
-
- // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
- // made a complete mock
- config.getConfiguration().getProxyConnectors().clear();
-
- // Setup source repository (using default layout)
- String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
-
- Path destRepoDir = Paths.get( repoPath );
-
- // Cleanout destination dirs.
- if ( Files.exists(destRepoDir))
- {
- FileUtils.deleteDirectory( destRepoDir.toFile() );
- }
-
- // Make the destination dir.
- Files.createDirectories(destRepoDir);
-
-
- Handler handler = new AbstractHandler()
- {
- @Override
- public void handle( String s, Request request, HttpServletRequest httpServletRequest,
- HttpServletResponse response )
- throws IOException, ServletException
- {
- response.setContentType( "text/plain" );
- response.setStatus( HttpServletResponse.SC_OK );
- response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
- assertNotNull( request.getHeader( "Proxy-Connection" ) );
-
- ( (Request) request ).setHandled( true );
- }
-
- public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch )
- throws IOException, ServletException
- {
- response.setContentType( "text/plain" );
- response.setStatus( HttpServletResponse.SC_OK );
- response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
- assertNotNull( request.getHeader( "Proxy-Connection" ) );
-
- ( (Request) request ).setHandled( true );
- }
- };
-
- server = new Server( );
- ServerConnector serverConnector = new ServerConnector( server, new HttpConnectionFactory());
- server.addConnector( serverConnector );
- server.setHandler( handler );
- server.start();
-
- int port = serverConnector.getLocalPort();
-
- NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
- proxyConfig.setHost( "localhost" );
- proxyConfig.setPort( port );
- proxyConfig.setProtocol( "http" );
- proxyConfig.setId( PROXY_ID );
- config.getConfiguration().addNetworkProxy( proxyConfig );
- ( (MockConfiguration) config ).triggerChange("networkProxies.networkProxy(0).host", "localhost");
-
- // Setup target (proxied to) repository.
- RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
-
- repoConfig.setId( PROXIED_ID );
- repoConfig.setName( "Proxied Repository 1" );
- repoConfig.setLayout( "default" );
- repoConfig.setUrl( "http://www.example.com/" );
-
- config.getConfiguration().addRemoteRepository( repoConfig );
-
- Wagon wagon = new HttpWagon( );
- WagonDelegate delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
- delegate.setDelegate( wagon );
-
- proxyRegistry.reload();
- repositoryRegistry.reload();
-
- managedDefaultRepository = createRepository(MANAGED_ID, "Default Managed Repository", repoPath, "default");
-
- }
-
- @After
- public void tearDown()
- throws Exception
- {
- if (server!=null) {
- server.stop();
- }
- }
-
- @Test
- public void testGetOverHttpProxy()
- throws Exception
- {
- assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyHost" , "" ) ));
- assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyPort", "" ) ) );
-
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
-
- // Configure Connector (usually done within archiva.xml configuration)
- addConnector();
-
- managedDefaultRepository = repositoryRegistry.getManagedRepository(MANAGED_ID).getContent();
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Path expectedFile = managedDefaultRepository.getRepository().getRoot().resolve( path ).getFilePath();
- Files.deleteIfExists( expectedFile );
- Artifact artifact = layout.getArtifact( path );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path sourceFile = Paths.get( PROXIED_BASEDIR, path );
- assertNotNull( "Expected File should not be null.", expectedFile );
- assertNotNull( "Actual File should not be null.", downloadedFile );
-
- assertTrue( "Check actual file exists.", Files.exists(downloadedFile.getFilePath()));
- assertTrue( "Check filename path is appropriate.", Files.isSameFile( expectedFile, downloadedFile.getFilePath()));
- assertTrue( "Check file path matches.", Files.isSameFile( expectedFile, downloadedFile.getFilePath()));
-
- String expectedContents = FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
- String actualContents = FileUtils.readFileToString( downloadedFile.getFilePath().toFile(), Charset.defaultCharset() );
- assertEquals( "Check file contents.", expectedContents, actualContents );
-
- assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyHost", "" ) ) );
- assertTrue( StringUtils.isEmpty( System.getProperty( "http.proxyPort" , "") ) );
- }
-
- private void addConnector()
- {
- ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
- connectorConfig.setProxyId( PROXY_ID );
- connectorConfig.setSourceRepoId( MANAGED_ID );
- connectorConfig.setTargetRepoId( PROXIED_ID );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, ChecksumPolicy.FIX.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, ReleasesPolicy.ONCE.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, SnapshotsPolicy.ONCE.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, CachedFailuresPolicy.NO.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS,
- PropagateErrorsDownloadPolicy.QUEUE.getId() );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT.getId() );
-
- int count = config.getConfiguration().getProxyConnectors().size();
- config.getConfiguration().addProxyConnector( connectorConfig );
-
- // Proper Triggering ...
- String prefix = "proxyConnectors.proxyConnector(" + count + ")";
- ( (MockConfiguration) config ).triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.content.Artifact;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import java.io.File;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.attribute.FileTime;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.*;
-
-/**
- * ManagedDefaultTransferTest
- */
-public class ManagedDefaultTransferTest
- extends AbstractProxyTestCase
-{
- @Test
- public void testGetDefaultLayoutNotPresentConnectorOffline()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- // Ensure file isn't present first.
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, true );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
- assertNull( "File should not have been downloaded", downloadedFile );
- }
-
- @Test
- public void testGetDefaultLayoutNotPresent()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- // Ensure file isn't present first.
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path sourceFile = Paths.get(REPOPATH_PROXIED1, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), sourceFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetDefaultLayoutNotPresentPassthrough()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar.asc";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- // Ensure file isn't present first.
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), path );
-
- Path sourceFile = Paths.get(REPOPATH_PROXIED1, path);
- assertNotNull(downloadedFile);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), sourceFile );
- assertFalse( Files.exists( downloadedFile.getParent().getFilePath().resolve(downloadedFile.getName() + ".sha1" )) );
- assertFalse( Files.exists(downloadedFile.getParent().getFilePath().resolve(downloadedFile.getName() + ".md5" ) ));
- assertFalse( Files.exists( downloadedFile.getParent().getFilePath().resolve(downloadedFile.getName() + ".sha256" ) ));
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * The attempt here should result in no file being transferred.
- * <p/>
- * The file exists locally, and the policy is ONCE.
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentPolicyOnce()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), expectedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * The attempt here should result in no file being transferred.
- * <p/>
- * The file exists locally, and the policy is ONCE.
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentPassthrough()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar.asc";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
-
- assertTrue( Files.exists(expectedFile) );
-
- // Set the managed File to be newer than local.
- setManagedOlderThanRemote( expectedFile, remoteFile );
- long originalModificationTime = Files.getLastModifiedTime(expectedFile).toMillis();
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), path );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, originalModificationTime );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * <p>
- * Request a file, that exists locally, and remotely.
- * </p>
- * <p>
- * All policies are set to IGNORE.
- * </p>
- * <p>
- * Managed file is newer than remote file.
- * </p>
- * <p>
- * Transfer should not have occured, as managed file is newer.
- * </p>
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentNewerThanRemotePolicyIgnored()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
-
- // Set the managed File to be newer than local.
- setManagedNewerThanRemote( expectedFile, remoteFile );
-
- long originalModificationTime = Files.getLastModifiedTime( expectedFile).toMillis();
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, originalModificationTime );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * <p>
- * Request a file, that exists locally, and remotely.
- * </p>
- * <p>
- * All policies are set to IGNORE.
- * </p>
- * <p>
- * Managed file is older than Remote file.
- * </p>
- * <p>
- * Transfer should have occured, as managed file is older than remote.
- * </p>
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentOlderThanRemotePolicyIgnored()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
-
- // Set the managed file to be newer than remote file.
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * The attempt here should result in file being transferred.
- * <p/>
- * The file exists locally, is over 6 years old, and the policy is DAILY.
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutRemoteUpdate()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
- Files.setLastModifiedTime( expectedFile, FileTime.from(getPastDate().getTime(), TimeUnit.MILLISECONDS ));
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.DAILY, SnapshotsPolicy.DAILY,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetWhenInBothProxiedRepos()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxied1File = Paths.get(REPOPATH_PROXIED1, path);
- Path proxied2File = Paths.get(REPOPATH_PROXIED2, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied1File );
- assertNoTempFiles( expectedFile );
-
- // TODO: is this check even needed if it passes above?
- String actualContents = FileUtils.readFileToString( downloadedFile.getFilePath().toFile(), Charset.defaultCharset() );
- String badContents = FileUtils.readFileToString( proxied2File.toFile(), Charset.defaultCharset() );
- assertFalse( "Downloaded file contents should not be that of proxy 2",
- StringUtils.equals( actualContents, badContents ) );
- }
-
- @Test
- public void testGetInSecondProxiedRepo()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxied2File = Paths.get(REPOPATH_PROXIED2, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testNotFoundInAnyProxies()
- throws Exception
- {
- String path = "org/apache/maven/test/does-not-exist/1.0/does-not-exist-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- assertNull( "File returned was: " + downloadedFile + "; should have got a not found exception",
- downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetInSecondProxiedRepoFirstFails()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "" +
- "http://bad.machine.com/repo/", "default" );
-
- wagonMock.get( EasyMock.eq( path), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall().andThrow( new ResourceDoesNotExistException( "transfer failed" ) );
- wagonMockControl.replay();
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied", false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- // Attempt the proxy fetch.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- wagonMockControl.verify();
-
- Path proxied2File = Paths.get(REPOPATH_PROXIED2, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetAllRepositoriesFail()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve( path );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
- saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "http://dead.machine.com/repo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", false );
- saveConnector( ID_DEFAULT_MANAGED, "badproxied2", false );
-
- Path tmpFile = expectedFile.getParent().resolve(expectedFile.getFileName() + ".tmp" );
-
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall().andThrow( new ResourceDoesNotExistException( "Can't find resource." ) );
-
- wagonMock.get( EasyMock.eq( path ), EasyMock.anyObject( File.class ) );
- EasyMock.expectLastCall().andThrow( new ResourceDoesNotExistException( "Can't find resource." ) );
-
- wagonMockControl.replay();
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- assertNotDownloaded( downloadedFile );
-
- wagonMockControl.verify();
- assertNoTempFiles( expectedFile );
-
- // TODO: do not want failures to present as a not found [MRM-492]
- // TODO: How much information on each failure should we pass back to the user vs. logging in the proxy?
- }
-
-
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.filelock.DefaultFileLockManager;
-import org.apache.archiva.common.utils.VersionUtil;
-import org.apache.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.archiva.model.ArchivaRepositoryMetadata;
-import org.apache.archiva.model.Plugin;
-import org.apache.archiva.model.SnapshotVersion;
-import org.apache.archiva.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.content.ContentItem;
-import org.apache.archiva.repository.content.DataItem;
-import org.apache.archiva.repository.content.ItemSelector;
-import org.apache.archiva.repository.content.Project;
-import org.apache.archiva.repository.content.Version;
-import org.apache.archiva.repository.content.base.ArchivaItemSelector;
-import org.apache.archiva.repository.metadata.RepositoryMetadataException;
-import org.apache.archiva.repository.metadata.base.MetadataTools;
-import org.apache.archiva.repository.metadata.base.RepositoryMetadataWriter;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.archiva.repository.storage.fs.FilesystemStorage;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.maven.wagon.TransferFailedException;
-import org.easymock.EasyMock;
-import org.junit.Test;
-import org.xmlunit.builder.DiffBuilder;
-import org.xmlunit.diff.Diff;
-import org.xmlunit.diff.Difference;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.io.File;
-import java.io.StringWriter;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import static org.junit.Assert.*;
-
-/**
- * MetadataTransferTest - Tests the various fetching / merging concepts surrounding the maven-metadata.xml files
- * present in the repository.
- * <p/>
- * Test Case Naming is as follows.
- * <p/>
- * <code>
- * public void testGet[Release|Snapshot|Project]Metadata[Not]Proxied[Not|On]Local[Not|On|Multiple]Remote
- * </code>
- * <p/>
- * <pre>
- * Which should leave the following matrix of test cases.
- *
- * Metadata | Proxied | Local | Remote
- * ----------+----------+-------+---------
- * Release | Not | Not | n/a (1)
- * Release | Not | On | n/a (1)
- * Release | | Not | Not
- * Release | | Not | On
- * Release | | Not | Multiple
- * Release | | On | Not
- * Release | | On | On
- * Release | | On | Multiple
- * Snapshot | Not | Not | n/a (1)
- * Snapshot | Not | On | n/a (1)
- * Snapshot | | Not | Not
- * Snapshot | | Not | On
- * Snapshot | | Not | Multiple
- * Snapshot | | On | Not
- * Snapshot | | On | On
- * Snapshot | | On | Multiple
- * Project | Not | Not | n/a (1)
- * Project | Not | On | n/a (1)
- * Project | | Not | Not
- * Project | | Not | On
- * Project | | Not | Multiple
- * Project | | On | Not
- * Project | | On | On
- * Project | | On | Multiple
- *
- * (1) If it isn't proxied, no point in having a remote.
- * </pre>
- *
- *
- */
-public class MetadataTransferTest
- extends AbstractProxyTestCase
-{
-
- @Inject
- @Named(value = "metadataTools#mocked")
- private MetadataTools metadataTools;
-
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalOnRemoteConnectoDisabled()
- throws Exception
- {
- // New project metadata that does not exist locally but exists on remote.
- String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- Path expectedFile = managedDefaultDir.resolve(requestedResource);
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- ContentItem metaItem = managedDefaultRepository.toItem( requestedResource );
- Project project = layout.adaptItem( Project.class, managedDefaultRepository.getParent( metaItem ) );
- assertNotNull( project );
- String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem( project ) );
- StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
- metaPath ).getFile();
-
- assertNull( "Should not have downloaded a file.", downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- // TODO: same test for other fetch* methods
- @Test
- public void testFetchFromTwoProxiesWhenFirstConnectionFails()
- throws Exception
- {
- // Project metadata that does not exist locally, but has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "http://bad.machine.com/repo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( "badproxied1", requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // ensure that a hard failure in the first proxy connector is skipped and the second repository checked
- Path expectedFile = managedDefaultDir.resolve(
- metadataTools.getRepositorySpecificName( "badproxied1", requestedResource ) );
-
- wagonMock.get( EasyMock.eq( requestedResource ), EasyMock.anyObject( File.class ));
- EasyMock.expectLastCall().andThrow( new TransferFailedException( "can't connect" ) );
-
-
- wagonMockControl.replay();
-
- assertFetchProjectOrGroup( requestedResource );
-
- wagonMockControl.verify();
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.1" }, "1.0.1", "1.0.1" );
- assertNoRepoMetadata( "badproxied1", requestedResource );
- assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
- }
-
- /**
- * Attempt to get the project metadata for non-existant artifact.
- * <p/>
- * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
- * to the requesting client.
- */
- @Test
- public void testGetProjectMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
-
- assertResourceNotFound( requestedResource );
-
- // No proxy setup, nothing fetched, failure expected.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertResourceNotFound( requestedResource );
- }
-
- @Test
- public void testGetProjectMetadataNotProxiedOnLocal()
- throws Exception
- {
-
- // Project metadata that exists and has multiple versions
- String requestedResource = "org/apache/maven/test/get-project-metadata/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
-
- assertResourceExists( requestedResource );
-
- // No proxy setup, nothing fetched from remote, but local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- // A metadata update is not performed in this use case. Local metadata content is only
- // updated via the metadata updater consumer.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- // Project metadata that does not exist locally, but has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1" }, "1.0.1", "1.0.1" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0" } );
- assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
- String requestedResource = "org/apache/maven/test/get-bogus-artifact/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, nothing fetched from remotes, local does not exist.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // Nothing fetched. Nothing should exist.
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- // New project metadata that does not exist locally but exists on remote.
- String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local does not exist.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local created/updated.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.5" }, "1.0.5", "1.0.5" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.5" } );
- }
-
- @Test
- public void testGetProjectMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- // Project metadata that exist locally, and has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/get-on-multiple-repos/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata fetched from both repos, and merged with local version.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1", "2.0" }, "2.0", "2.0" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0", "2.0" } );
- assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0", "1.0.1" } );
- }
-
- @Test
- public void testGetProjectMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
-
- // Project metadata that exist locally, and does not exist in remote repos.
- String requestedResource = "org/apache/maven/test/get-not-on-remotes/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
-
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata not fetched from both repos, and local version exists.
- // Since there was no updated metadata content from a remote/proxy, a metadata update on
- // the local file never ran. Local only updates are performed via the metadata updater consumer.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetProjectMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- // Project metadata that exist locally and exists on remote.
- String requestedResource = "org/apache/maven/test/get-on-local-on-remote/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local updated.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22", "2.0" }, "2.0", "2.0" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.22", "2.0" } );
- }
-
- /**
- * A request for a release maven-metadata.xml file that does not exist locally, and the managed
- * repository has no proxied repositories set up.
- * <p/>
- * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
- * to the requesting client.
- */
- @Test
- public void testGetReleaseMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertNoMetadata( requestedResource );
-
- // No proxy setup, nothing fetched, failure expected.
- assertFetchVersionedFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertNoMetadata( requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that does exist locally, and the managed
- * repository has no proxied repositories set up.
- * <p/>
- * Expected result: the maven-metadata.xml file is updated locally, based off of the managed repository
- * information, and then returned to the client.
- */
- @Test
- public void testGetReleaseMetadataNotProxiedOnLocal()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-default-metadata/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceExists( requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- }
-
- /**
- * A request for a release maven-metadata.xml file that does not exist on the managed repository, but
- * exists on multiple remote repositories.
- * <p/>
- * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
- * file location on the managed repository, a merge of the contents to the requested
- * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
- * returned to the client.
- */
- @Test
- public void testGetReleaseMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that does not exist locally, nor does it exist in a remote
- * proxied repository.
- * <p/>
- * Expected result: the maven-metadata.xml file is created locally, based off of managed repository
- * information, and then return to the client.
- */
- @Test
- public void testGetReleaseMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-bad-metadata/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
-
- assertFetchProjectOrGroupFailed( requestedResource );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that does not exist on the managed repository, but
- * exists on 1 remote repository.
- * <p/>
- * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
- * file location on the managed repository, a merge of the contents to the requested
- * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
- * returned to the client.
- */
- @Test
- public void testGetReleaseMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that exists in the managed repository, but
- * not on any remote repository.
- * <p/>
- * Expected result: the maven-metadata.xml file does not exist on the remote proxied repository and
- * is not downloaded. There is no repository specific metadata file on the managed
- * repository. The managed repository maven-metadata.xml is returned to the
- * client as-is.
- */
- @Test
- public void testGetReleaseMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-not-on-remotes/1.0-beta-2/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertReleaseMetadataContents( requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that exists in the managed repository, and on multiple
- * remote repositories.
- * <p/>
- * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
- * and merged into the contents of the existing managed repository copy of
- * the maven-metadata.xml file.
- */
- @Test
- public void testGetReleaseMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-on-multiple-repos/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertReleaseMetadataContents( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that exists in the managed repository, and on one
- * remote repository.
- * <p/>
- * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
- * and merged into the contents of the existing managed repository copy of
- * the maven-metadata.xml file.
- */
- @Test
- public void testGetReleaseMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-on-local-on-remote/1.0.22/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertReleaseMetadataContents( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource =
- "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertNoMetadata( requestedResource );
-
- // No proxy setup, nothing fetched, no local file, failure expected.
- assertFetchVersionedFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertNoMetadata( requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataNotProxiedOnLocal()
- throws Exception
- {
- // The artifactId exists locally (but not on a remote repo)
- String requestedResource =
- "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceExists( requestedResource );
-
- // No proxy setup, nothing fetched from remote, local file exists, fetch should succeed.
- assertFetchVersioned( requestedResource );
-
- // Local metadata exists, should be updated to reflect the latest release.
- assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- String requestedResource =
- "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Proxying 2 repos, both have content, local file updated.
- assertFetchVersioned( requestedResource );
-
- assertSnapshotMetadataContents( requestedResource, "20070101", "000103", 2 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20061227", "112101", 2 );
- assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070101", "000103", 2 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource =
- "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertNoMetadata( requestedResource );
-
- // One proxy setup, nothing fetched, no local file, failure expected.
- assertFetchVersionedFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertNoMetadata( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- // Artifact exists only in the proxied1 location.
- String requestedResource = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
-
- // One proxy setup, one metadata fetched, local file created/updated.
- assertFetchVersioned( requestedResource );
-
- // Local artifact Id should contain latest (which in this case is from proxied download)
- assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-snapshot-popular/2.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertSnapshotMetadataContents( requestedResource, "20070822", "021008", 3 );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Proxying 2 repos, both have content, local file updated.
- assertFetchVersioned( requestedResource );
-
- assertSnapshotMetadataContents( requestedResource, "20070823", "212711", 6 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20070822", "145534", 9 );
- assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070823", "212711", 6 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
- // The artifactId exists locally (but not on a remote repo)
- String requestedResource =
- "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceExists( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
- assertFetchVersioned( requestedResource );
-
- // Local metadata exists, repo metadatas should not exist, local file updated.
- assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- // The artifactId exists locally (but not on a remote repo)
- String requestedResource =
- "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
- assertFetchVersioned( requestedResource );
-
- // Local metadata exists, repo metadata exists, local file updated.
- assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
- }
-
- @Test
- public void testGetGroupMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource = "org/apache/maven/test/groups/get-default-metadata-nonexistant/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceNotFound( requestedResource );
-
- // No proxy setup, nothing fetched, failure expected.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertResourceNotFound( requestedResource );
- }
-
- @Test
- public void testGetGroupMetadataNotProxiedOnLocal()
- throws Exception
- {
- // Project metadata that exists and has multiple versions
- String requestedResource = "org/apache/maven/test/groups/get-project-metadata/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceExists( requestedResource );
-
- // No proxy setup, nothing fetched from remote, but local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- // A metadata update is not performed in this use case. Local metadata content is only
- // updated via the metadata updater consumer.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
- }
-
- @Test
- public void testGetGroupMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- // Project metadata that does not exist locally, but has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/groups/get-default-layout/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin2", "plugin1" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1" } );
- assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin2" } );
- }
-
- @Test
- public void testGetGroupsMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
- String requestedResource = "org/apache/maven/test/groups/get-bogus-artifact/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, nothing fetched from remotes, local does not exist.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // Nothing fetched. Nothing should exist.
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetGroupMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- // New project metadata that does not exist locally but exists on remote.
- String requestedResource = "org/apache/maven/test/groups/get-found-in-proxy/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local does not exist.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local created/updated.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin3" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin3" } );
- }
-
- @Test
- public void testGetGroupMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- // Project metadata that exist locally, and has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/groups/get-on-multiple-repos/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata fetched from both repos, and merged with local version.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin1", "plugin2", "plugin4" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1", "plugin4" } );
- assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin1", "plugin2" } );
- }
-
- @Test
- public void testGetGroupMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
- // Project metadata that exist locally, and does not exist in remote repos.
- String requestedResource = "org/apache/maven/test/groups/get-not-on-remotes/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata not fetched from both repos, and local version exists.
- // Since there was no updated metadata content from a remote/proxy, a metadata update on
- // the local file never ran. Local only updates are performed via the metadata updater consumer.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetGroupMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- // Project metadata that exist locally and exists on remote.
- String requestedResource = "org/apache/maven/test/groups/get-on-local-on-remote/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local updated.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7", "plugin4" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin7", "plugin4" } );
- }
-
- /**
- * Transfer the metadata file.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchProjectOrGroup( String requestedResource )
- throws Exception
- {
- Path expectedFile = managedDefaultDir.resolve(requestedResource);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- ContentItem metaItem = managedDefaultRepository.toItem( requestedResource );
- Project project = layout.adaptItem( Project.class, managedDefaultRepository.getParent( metaItem ) );
- assertNotNull( project );
- String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem( project ) );
-
- StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
- metaPath ).getFile();
-
- assertNotNull( "Should have downloaded a file.", downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
-
- /**
- * Transfer the metadata file, not expected to succeed.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchProjectOrGroupFailed( String requestedResource )
- throws Exception
- {
- Path expectedFile = managedDefaultDir.resolve(requestedResource);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- ContentItem metaItem = managedDefaultRepository.toItem( requestedResource );
- Project project = layout.adaptItem( Project.class, managedDefaultRepository.getParent( metaItem ) );
- assertNotNull( project );
- String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem( project ) );
- StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
- metaPath ).getFile();
-
- assertNull( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Transfer the metadata file.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchVersioned( String requestedResource )
- throws Exception
- {
- Path expectedFile = managedDefaultDir.resolve(requestedResource);
-
- ContentItem item = managedDefaultRepository.toItem( requestedResource );
- if (item instanceof DataItem) {
- item = managedDefaultRepository.getParent( item );
- }
- assertNotNull( item );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Version version = layout.adaptItem( Version.class, item );
- assertNotNull( version );
- String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem(
- version ) );
-
- StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
- metaPath).getFile();
-
- assertNotNull( "Should have downloaded a file.", downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
-
- /**
- * Transfer the metadata file, not expected to succeed.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchVersionedFailed( String requestedResource )
- throws Exception
- {
- Path expectedFile = managedDefaultDir.resolve(requestedResource);
- ContentItem item = managedDefaultRepository.toItem( requestedResource );
- assertNotNull( item );
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Version version = layout.adaptItem( Version.class, item );
- assertNotNull( version );
- String metaPath = managedDefaultRepository.toPath( layout.getMetadataItem(
- version ) );
- assertNotNull( metaPath );
- StorageAsset downloadedFile = proxyHandler.fetchMetadataFromProxies( managedDefaultRepository.getRepository(),
- metaPath ).getFile();
-
- assertNull( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Test for the existance of the requestedResource in the default managed repository.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertResourceExists( String requestedResource )
- throws Exception
- {
- Path actualFile = managedDefaultDir.resolve(requestedResource);
- assertTrue( "Resource should exist: " + requestedResource, Files.exists(actualFile) );
- }
-
- private void assertMetadataEquals( String expectedMetadataXml, Path actualFile )
- throws Exception
- {
- assertNotNull( "Actual File should not be null.", actualFile );
-
- assertTrue( "Actual file exists.", Files.exists(actualFile) );
-
- StringWriter actualContents = new StringWriter();
- FilesystemStorage fsStorage = new FilesystemStorage(actualFile.getParent(), new DefaultFileLockManager());
- StorageAsset actualFileAsset = fsStorage.getAsset(actualFile.getFileName().toString());
- ArchivaRepositoryMetadata metadata = metadataTools.getMetadataReader( null ).read( actualFileAsset );
- RepositoryMetadataWriter.write( metadata, actualContents );
-
- Diff detailedDiff = DiffBuilder.compare( expectedMetadataXml).withTest( actualContents.toString() ).checkForSimilar().build();
- if ( detailedDiff.hasDifferences() )
- {
- for ( Difference diff : detailedDiff.getDifferences() )
- {
- System.out.println( diff );
- }
- assertEquals( expectedMetadataXml, actualContents );
- }
-
- // assertEquals( "Check file contents.", expectedMetadataXml, actualContents );
- }
-
- /**
- * Ensures that the requested resource is not present in the managed repository.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertNoMetadata( String requestedResource )
- throws Exception
- {
- Path expectedFile = managedDefaultDir.resolve(requestedResource);
- assertFalse( "metadata should not exist: " + expectedFile, Files.exists(expectedFile) );
- }
-
- /**
- * Ensures that the proxied repository specific maven metadata file does NOT exist in the
- * managed repository.
- *
- * @param proxiedRepoId the proxied repository id to validate with.
- * @param requestedResource the resource requested.
- */
- private void assertNoRepoMetadata( String proxiedRepoId, String requestedResource )
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- Path actualFile = managedDefaultDir.resolve(proxiedFile);
- assertFalse( "Repo specific metadata should not exist: " + actualFile, Files.exists(actualFile) );
- }
-
- private void assertGroupMetadataContents( String requestedResource, String expectedPlugins[] )
- throws Exception
- {
- Path actualFile = managedDefaultDir.resolve(requestedResource);
- assertTrue( "Snapshot Metadata should exist: " + requestedResource, Files.exists(actualFile) );
-
- ItemSelector actualMetadata = createGroupSelector( requestedResource );
-
- assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
- }
-
- private ItemSelector createProjectSelector(String path) throws RepositoryMetadataException
- {
- return metadataTools.toProjectSelector( path );
- }
-
- private ItemSelector createVersionedSelector(String path) throws RepositoryMetadataException
- {
- return metadataTools.toVersionedSelector( path );
- }
-
- private ItemSelector createGroupSelector( String requestedResource )
- throws RepositoryMetadataException
- {
- ItemSelector projectSelector = createProjectSelector( requestedResource );
- ArchivaItemSelector.Builder projectReference = ArchivaItemSelector.builder( ).withSelector( projectSelector );
- projectReference.withNamespace( projectSelector.getNamespace() + "." + projectSelector.getProjectId() );
- projectReference.withArtifactId( null );
- projectReference.withProjectId( null );
- return projectReference.build();
- }
-
- private void assertRepoGroupMetadataContents( String proxiedRepoId, String requestedResource,
- String expectedPlugins[] )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- Path actualFile = managedDefaultDir.resolve(proxiedFile);
- assertTrue( "Repo Specific Group Metadata should exist: " + requestedResource, Files.exists(actualFile) );
-
- ItemSelector actualMetadata = createGroupSelector( requestedResource );
-
- assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
- }
-
- private void assertGroupMetadata( Path actualFile, ItemSelector actualMetadata, String expectedPlugins[] )
- throws Exception
- {
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( actualMetadata.getNamespace() );
-
- for ( String pluginId : expectedPlugins )
- {
- Plugin p = new Plugin();
- p.setPrefix( pluginId );
- p.setArtifactId( pluginId + "-maven-plugin" );
- p.setName( "The " + pluginId + " Plugin" );
- m.getPlugins().add( p );
- }
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the existance of the requestedResource in the default managed repository, and if it exists,
- * does it contain the specified list of expected versions?
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertProjectMetadataContents( String requestedResource, String expectedVersions[],
- String latestVersion, String releaseVersion )
- throws Exception
- {
- Path actualFile = managedDefaultDir.resolve(requestedResource);
- assertTrue( Files.exists(actualFile) );
-
- ItemSelector metadata = createProjectSelector( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getNamespace() );
- m.setArtifactId( metadata.getArtifactId() );
- m.setLatestVersion( latestVersion );
- m.setReleasedVersion( releaseVersion );
-
- if ( expectedVersions != null )
- {
- m.getAvailableVersions().addAll( Arrays.asList( expectedVersions ) );
- }
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the existance of the requestedResource in the default managed repository, and if it exists,
- * does it contain the expected release maven-metadata.xml contents?
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertReleaseMetadataContents( String requestedResource )
- throws Exception
- {
- Path actualFile = managedDefaultDir.resolve(requestedResource);
- assertTrue( "Release Metadata should exist: " + requestedResource, Files.exists(actualFile) );
-
- ItemSelector metadata = createVersionedSelector( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getNamespace() );
- m.setArtifactId( metadata.getArtifactId() );
- m.setVersion( metadata.getVersion() );
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the existance of the snapshot metadata in the default managed repository, and if it exists,
- * does it contain the expected release maven-metadata.xml contents?
- *
- * @param requestedResource the requested resource
- * @param expectedDate the date in "yyyyMMdd" format
- * @param expectedTime the time in "hhmmss" format
- * @param expectedBuildnumber the build number
- * @throws Exception
- */
- private void assertSnapshotMetadataContents( String requestedResource, String expectedDate, String expectedTime,
- int expectedBuildnumber )
- throws Exception
- {
- Path actualFile = managedDefaultDir.resolve(requestedResource);
- assertTrue( "Snapshot Metadata should exist: " + requestedResource, Files.exists(actualFile) );
-
- ItemSelector actualMetadata = createVersionedSelector( requestedResource );
-
- assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
- }
-
- /**
- * Test for the existance of the proxied repository specific snapshot metadata in the default managed
- * repository, and if it exists, does it contain the expected release maven-metadata.xml contents?
- *
- * @param proxiedRepoId the repository id of the proxied repository.
- * @param requestedResource the requested resource
- * @param expectedDate the date in "yyyyMMdd" format
- * @param expectedTime the time in "hhmmss" format
- * @param expectedBuildnumber the build number
- * @throws Exception
- */
- private void assertRepoSnapshotMetadataContents( String proxiedRepoId, String requestedResource,
- String expectedDate, String expectedTime, int expectedBuildnumber )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- Path actualFile = managedDefaultDir.resolve(proxiedFile);
- assertTrue( "Repo Specific Snapshot Metadata should exist: " + requestedResource, Files.exists(actualFile) );
-
- ItemSelector actualMetadata = createVersionedSelector( requestedResource );
-
- assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
- }
-
- private void assertSnapshotMetadata( Path actualFile, ItemSelector actualMetadata, String expectedDate,
- String expectedTime, int expectedBuildnumber )
- throws RepositoryMetadataException, Exception
- {
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( actualMetadata.getNamespace() );
- m.setArtifactId( actualMetadata.getArtifactId() );
- m.setVersion( VersionUtil.getBaseVersion( actualMetadata.getVersion() ) );
-
- m.setSnapshotVersion( new SnapshotVersion() );
-
- if ( StringUtils.isNotBlank( expectedDate ) && StringUtils.isNotBlank( expectedTime ) )
- {
- m.getSnapshotVersion().setTimestamp( expectedDate + "." + expectedTime );
- }
-
- m.getSnapshotVersion().setBuildNumber( expectedBuildnumber );
-
- m.setLastUpdated( expectedDate + expectedTime );
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Ensures that the repository specific maven metadata file exists, and contains the appropriate
- * list of expected versions within.
- *
- * @param proxiedRepoId
- * @param requestedResource
- * @param expectedProxyVersions
- */
- private void assertRepoProjectMetadata( String proxiedRepoId, String requestedResource,
- String[] expectedProxyVersions )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- Path actualFile = managedDefaultDir.resolve(proxiedFile);
- assertTrue( Files.exists(actualFile) );
-
- ItemSelector metadata = createProjectSelector( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getNamespace() );
- m.setArtifactId( metadata.getArtifactId() );
-
- if ( expectedProxyVersions != null )
- {
- m.getAvailableVersions().addAll( Arrays.asList( expectedProxyVersions ) );
- }
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Ensures that the repository specific maven metadata file exists, and contains the appropriate
- * list of expected versions within.
- *
- * @param proxiedRepoId
- * @param requestedResource
- */
- private void assertRepoReleaseMetadataContents( String proxiedRepoId, String requestedResource )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- Path actualFile = managedDefaultDir.resolve(proxiedFile);
- assertTrue( "Release metadata for repo should exist: " + actualFile, Files.exists(actualFile) );
-
- ItemSelector metadata = createVersionedSelector( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getNamespace() );
- m.setArtifactId( metadata.getArtifactId() );
- m.setVersion( metadata.getVersion() );
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the non-existance of the requestedResource in the default managed repository.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertResourceNotFound( String requestedResource )
- throws Exception
- {
- Path actualFile = managedDefaultDir.resolve(requestedResource);
- assertFalse( "Resource should not exist: " + requestedResource, Files.exists(actualFile) );
- }
-
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.configuration.*;
-import org.apache.archiva.components.registry.Registry;
-import org.apache.archiva.components.registry.RegistryException;
-import org.apache.archiva.components.registry.RegistryListener;
-import org.apache.commons.lang3.StringUtils;
-import org.easymock.EasyMock;
-import org.easymock.IMocksControl;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.*;
-
-/**
- * MockConfiguration
- *
- *
- */
-@Service( "archivaConfiguration#mock" )
-public class MockConfiguration
- implements ArchivaConfiguration
-{
-
- private Configuration configuration = new Configuration();
-
- private Set<RegistryListener> registryListeners = new HashSet<RegistryListener>();
-
- private Set<ConfigurationListener> configListeners = new HashSet<ConfigurationListener>();
-
- private IMocksControl registryControl;
-
- private Registry registryMock;
-
- public MockConfiguration()
- {
- registryControl = EasyMock.createNiceControl( );
- registryMock = registryControl.createMock( Registry.class );
- }
-
- @PostConstruct
- public void initialize()
- throws Exception
- {
-
- configuration.setRepositoryScanning( new RepositoryScanningConfiguration()
- {
- @Override
- public List<FileType> getFileTypes()
- {
- FileType fileType = new FileType();
- fileType.setId( FileTypes.ARTIFACTS );
- fileType.setPatterns( Collections.singletonList( "**/*" ) );
- return Collections.singletonList( fileType );
- }
- } );
- ArchivaRuntimeConfiguration rt = new ArchivaRuntimeConfiguration();
- List<String> checksums = new ArrayList<>();
- checksums.add("MD5");
- checksums.add("SHA1");
- checksums.add("SHA256");
- rt.setChecksumTypes(checksums);
- configuration.setArchivaRuntimeConfiguration(rt);
-
- }
-
- @Override
- public void addChangeListener( org.apache.archiva.components.registry.RegistryListener listener )
- {
- registryListeners.add( listener );
- }
-
-
- @Override
- public void removeChangeListener( RegistryListener listener )
- {
- registryListeners.remove( listener );
- }
-
- @Override
- public Configuration getConfiguration()
- {
- return configuration;
- }
-
- @Override
- public void save( Configuration configuration )
- throws RegistryException
- {
- /* do nothing */
- }
-
- @Override
- public void save( Configuration configuration, String eventTag ) throws RegistryException, IndeterminateConfigurationException
- {
- // do nothing
- }
-
- public void triggerChange( String name, String value )
- {
- for ( org.apache.archiva.components.registry.RegistryListener listener : registryListeners )
- {
- try
- {
- listener.afterConfigurationChange( registryMock, name, value );
- }
- catch ( Exception e )
- {
- e.printStackTrace();
- }
- }
-
- for (ConfigurationListener listener : configListeners) {
- listener.configurationEvent( new ConfigurationEvent( ConfigurationEvent.CHANGED ) );
- }
- }
-
- @Override
- public void addListener( ConfigurationListener listener )
- {
- configListeners.add( listener );
- }
-
- @Override
- public void removeListener( ConfigurationListener listener )
- {
- configListeners.remove( listener );
- }
-
- @Override
- public boolean isDefaulted()
- {
- return false;
- }
-
- @Override
- public void reload()
- {
- // no op
- }
-
- @Override
- public Locale getDefaultLocale( )
- {
- return Locale.getDefault();
- }
-
- @Override
- public List<Locale.LanguageRange> getLanguagePriorities( )
- {
- return Locale.LanguageRange.parse( "en,fr,de" );
- }
-
- @Override
- public Path getAppServerBaseDir() {
- if (System.getProperties().containsKey("appserver.base")) {
- return Paths.get(System.getProperty("appserver.base"));
- } else {
- return Paths.get("");
- }
- }
-
-
- @Override
- public Path getRepositoryBaseDir() {
- return getDataDirectory().resolve("repositories");
- }
-
- @Override
- public Path getRemoteRepositoryBaseDir() {
- return getDataDirectory().resolve("remotes");
- }
-
- @Override
- public Path getRepositoryGroupBaseDir() {
- return getDataDirectory().resolve("groups");
- }
-
- @Override
- public Path getDataDirectory() {
- if (configuration!=null && StringUtils.isNotEmpty(configuration.getArchivaRuntimeConfiguration().getDataDirectory())) {
- return Paths.get(configuration.getArchivaRuntimeConfiguration().getDataDirectory());
- } else {
- return getAppServerBaseDir().resolve("data");
- }
- }
-
- @Override
- public Registry getRegistry( )
- {
- return null;
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.policies.CachedFailuresPolicy;
-import org.apache.archiva.policies.ChecksumPolicy;
-import org.apache.archiva.policies.ReleasesPolicy;
-import org.apache.archiva.policies.SnapshotsPolicy;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.content.Artifact;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.junit.Test;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.attribute.FileTime;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.*;
-
-/**
- * SnapshotTransferTest
- *
- *
- */
-public class SnapshotTransferTest
- extends AbstractProxyTestCase
-{
- @Test
- public void testSnapshotNonExistant()
- throws Exception
- {
- String path = "org/apache/maven/test/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- Files.deleteIfExists(expectedFile);
- assertFalse( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testTimestampDrivenSnapshotNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- Files.deleteIfExists(expectedFile);
- assertFalse( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testNewerTimestampDrivenSnapshotOnFirstRepo()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
- Files.setLastModifiedTime( expectedFile, FileTime.from( getPastDate().getTime(), TimeUnit.MILLISECONDS ));
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testOlderTimestampDrivenSnapshotOnFirstRepo()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
-
- setManagedNewerThanRemote( expectedFile, remoteFile );
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- // Attempt to download.
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- // Should not have downloaded as managed is newer than remote.
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * TODO: Has problems with wagon implementation not preserving timestamp.
- */
- /*
- public void testNewerTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- ArtifactReference artifact = createArtifactReference( "default", path );
-
- Files.delete(expectedFile);
- assertFalse( Files.exists(expectedFile) );
-
- // Create customized proxy / target repository
- File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED1_TARGET, REPOPATH_PROXIED1,
- REPOPATH_PROXIED1_TARGET, "default" );
-
- new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- // Should have downloaded the content from proxy2, as proxy1 has an old (by file.lastModified check) version.
- Path proxiedFile = Paths.get(REPOPATH_PROXIED2, path);
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- public void testOlderTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- ArtifactReference artifact = createArtifactReference( "default", path );
-
- Files.delete(expectedFile);
- assertFalse( Files.exists(expectedFile) );
-
- // Create customized proxy / target repository
- File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED2_TARGET, REPOPATH_PROXIED2,
- REPOPATH_PROXIED2_TARGET, "default" );
-
- new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1_TARGET, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- } */
-
- @Test
- public void testTimestampDrivenSnapshotNotExpired()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- Files.setLastModifiedTime( proxiedFile, FileTime.from( getFutureDate().getTime(), TimeUnit.MILLISECONDS ));
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testTimestampDrivenSnapshotNotUpdated()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
- Path remoteFile = Paths.get(REPOPATH_PROXIED1, path);
-
- setManagedNewerThanRemote( expectedFile, remoteFile, 12000000 );
- long expectedTimestamp = Files.getLastModifiedTime( expectedFile ).toMillis();
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, expectedTimestamp );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testTimestampDrivenSnapshotNotPresentAlreadyExpiredCacheFailure()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- Files.deleteIfExists(expectedFile);
- assertFalse( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testMetadataDrivenSnapshotNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/get-metadata-snapshot-1.0-20050831.101112-1.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- Files.deleteIfExists(expectedFile);
- assertFalse( Files.exists(expectedFile) );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertNotNull( downloadedFile );
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetMetadataDrivenSnapshotRemoteUpdate()
- throws Exception
- {
- // Metadata driven snapshots (using a full timestamp) are treated like a release. It is the timing of the
- // updates to the metadata files that triggers which will be downloaded
-
- String path = "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/get-present-metadata-snapshot-1.0-20050831.101112-1.jar";
- setupTestableManagedRepository( path );
-
- Path expectedFile = managedDefaultDir.resolve(path);
-
- BaseRepositoryContentLayout layout = managedDefaultRepository.getLayout( BaseRepositoryContentLayout.class );
-
- Artifact artifact = layout.getArtifact( path );
-
- assertTrue( Files.exists(expectedFile) );
-
- Files.setLastModifiedTime( expectedFile, FileTime.from( getPastDate().getTime(), TimeUnit.MILLISECONDS ));
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
-
- Path proxiedFile = Paths.get(REPOPATH_PROXIED1, path);
- assertNotNull( downloadedFile );
- assertFileEquals( expectedFile, downloadedFile.getFilePath(), proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.apache.maven.wagon.ConnectionException;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.apache.maven.wagon.TransferFailedException;
-import org.apache.maven.wagon.Wagon;
-import org.apache.maven.wagon.authentication.AuthenticationException;
-import org.apache.maven.wagon.authentication.AuthenticationInfo;
-import org.apache.maven.wagon.authorization.AuthorizationException;
-import org.apache.maven.wagon.events.SessionListener;
-import org.apache.maven.wagon.events.TransferListener;
-import org.apache.maven.wagon.proxy.ProxyInfo;
-import org.apache.maven.wagon.proxy.ProxyInfoProvider;
-import org.apache.maven.wagon.repository.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.List;
-
-/**
- * A dummy wagon implementation
- */
-@Service ("wagon#test")
-public class WagonDelegate
- implements Wagon
-{
- private Logger log = LoggerFactory.getLogger( WagonDelegate.class );
-
- private Wagon delegate;
-
- private String contentToGet;
-
- @Override
- public void get( String resourceName, File destination )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- log.debug( ".get({}, {})", resourceName, destination );
- delegate.get( resourceName, destination );
- create( destination.toPath() );
- }
-
- @Override
- public boolean getIfNewer( String resourceName, File destination, long timestamp )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- log.info( ".getIfNewer({}, {}, {})", resourceName, destination, timestamp );
-
- boolean result = delegate.getIfNewer( resourceName, destination, timestamp );
- createIfMissing( destination.toPath() );
- return result;
- }
-
- @Override
- public void put( File source, String destination )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- delegate.put( source, destination );
- }
-
- @Override
- public void putDirectory( File sourceDirectory, String destinationDirectory )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- delegate.putDirectory( sourceDirectory, destinationDirectory );
- }
-
- @Override
- public boolean resourceExists( String resourceName )
- throws TransferFailedException, AuthorizationException
- {
- return delegate.resourceExists( resourceName );
- }
-
- @SuppressWarnings ("unchecked")
- @Override
- public List<String> getFileList( String destinationDirectory )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- return delegate.getFileList( destinationDirectory );
- }
-
- @Override
- public boolean supportsDirectoryCopy()
- {
- return delegate.supportsDirectoryCopy();
- }
-
- @Override
- public void setTimeout( int val )
- {
- // ignore
- }
-
- @Override
- public int getTimeout()
- {
- return 0;
- }
-
- @Override
- public void setReadTimeout( int timeoutValue )
- {
- // ignore
- }
-
- @Override
- public int getReadTimeout()
- {
- return 0;
- }
-
- @Override
- public Repository getRepository()
- {
- return delegate.getRepository();
- }
-
- @Override
- public void connect( Repository source )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source );
- }
-
- @Override
- public void connect( Repository source, ProxyInfo proxyInfo )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, proxyInfo );
- }
-
- @Override
- public void connect( Repository source, ProxyInfoProvider proxyInfoProvider )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, proxyInfoProvider );
- }
-
- @Override
- public void connect( Repository source, AuthenticationInfo authenticationInfo )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, authenticationInfo );
- }
-
- @Override
- public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, authenticationInfo, proxyInfo );
- }
-
- @Override
- public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, authenticationInfo, proxyInfoProvider );
- }
-
- @SuppressWarnings ("deprecation")
- @Override
- public void openConnection()
- throws ConnectionException, AuthenticationException
- {
- delegate.openConnection();
- }
-
- @Override
- public void disconnect()
- throws ConnectionException
- {
- delegate.disconnect();
- }
-
- @Override
- public void addSessionListener( SessionListener listener )
- {
- delegate.addSessionListener( listener );
- }
-
- @Override
- public void removeSessionListener( SessionListener listener )
- {
- delegate.removeSessionListener( listener );
- }
-
- @Override
- public boolean hasSessionListener( SessionListener listener )
- {
- return delegate.hasSessionListener( listener );
- }
-
- @Override
- public void addTransferListener( TransferListener listener )
- {
- delegate.addTransferListener( listener );
- }
-
- @Override
- public void removeTransferListener( TransferListener listener )
- {
- delegate.removeTransferListener( listener );
- }
-
- @Override
- public boolean hasTransferListener( TransferListener listener )
- {
- return delegate.hasTransferListener( listener );
- }
-
- @Override
- public boolean isInteractive()
- {
- return delegate.isInteractive();
- }
-
- @Override
- public void setInteractive( boolean interactive )
- {
- delegate.setInteractive( interactive );
- }
-
- public void setDelegate( Wagon delegate )
- {
- this.delegate = delegate;
- }
-
- void setContentToGet( String content )
- {
- contentToGet = content;
- }
-
- private void createIfMissing( Path destination )
- {
- // since the mock won't actually copy a file, create an empty one to simulate file existence
- if ( !Files.exists(destination) )
- {
- create( destination );
- }
- }
-
- private void create( Path destination )
- {
- try
- {
- Files.createDirectories(destination.getParent());
- if ( contentToGet == null && !Files.exists(destination))
- {
- Files.createFile(destination);
- }
- else if (contentToGet != null)
- {
- org.apache.archiva.common.utils.FileUtils.writeStringToFile(destination, Charset.defaultCharset(), contentToGet);
- }
- }
- catch ( IOException e )
- {
- throw new RuntimeException( e.getMessage(), e );
- }
- }
-
- public void cleanup() {
-
- }
-}
+++ /dev/null
-package org.apache.archiva.proxy.common;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import junit.framework.TestCase;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
-import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
-import org.apache.maven.wagon.Wagon;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.context.ContextConfiguration;
-
-import javax.inject.Inject;
-
-/**
- * Test the WagonFactory works through Spring to be bound into the RepositoryProxyHandler implementation.
- */
-@RunWith ( ArchivaSpringJUnit4ClassRunner.class )
-@ContextConfiguration ( locations = { "classpath*:/META-INF/spring-context.xml" } )
-public class WagonFactoryTest
- extends TestCase
-{
-
- @Inject
- WagonFactory factory;
-
- @Test
- public void testLookupSuccessiveWagons()
- throws Exception
- {
-
- Wagon first = factory.getWagon( new WagonFactoryRequest().protocol( "wagon#file" ) );
-
- Wagon second = factory.getWagon( new WagonFactoryRequest().protocol( "wagon#file" ) );
-
- // ensure we support only protocol name too
- Wagon third = factory.getWagon( new WagonFactoryRequest().protocol( "file" ) );
-
- assertNotSame( first, second );
-
- assertNotSame( first, third );
- }
-}
+++ /dev/null
-package org.apache.archiva.repository.mock;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.indexer.ArchivaIndexManager;
-import org.apache.archiva.indexer.ArchivaIndexingContext;
-import org.apache.archiva.indexer.IndexCreationFailedException;
-import org.apache.archiva.indexer.IndexUpdateFailedException;
-import org.apache.archiva.repository.Repository;
-import org.apache.archiva.repository.RepositoryType;
-import org.springframework.stereotype.Service;
-
-import java.net.URI;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * @author Martin Stockhammer <martin_s@apache.org>
- */
-@Service("archivaIndexManager#maven")
-public class ArchivaIndexManagerMock implements ArchivaIndexManager {
-
-
-
- @Override
- public void pack(ArchivaIndexingContext context) throws IndexUpdateFailedException {
-
- }
-
- @Override
- public void scan(ArchivaIndexingContext context) throws IndexUpdateFailedException {
-
- }
-
- @Override
- public void update(ArchivaIndexingContext context, boolean fullUpdate) throws IndexUpdateFailedException {
-
- }
-
- @Override
- public void addArtifactsToIndex(ArchivaIndexingContext context, Collection<URI> artifactReference) throws IndexUpdateFailedException {
-
- }
-
- @Override
- public void removeArtifactsFromIndex(ArchivaIndexingContext context, Collection<URI> artifactReference) throws IndexUpdateFailedException {
-
- }
-
- @Override
- public boolean supportsRepository(RepositoryType type) {
- return true;
- }
-
- @Override
- public ArchivaIndexingContext createContext(Repository repository) throws IndexCreationFailedException {
- return null;
- }
-
- @Override
- public ArchivaIndexingContext reset(ArchivaIndexingContext context) throws IndexUpdateFailedException {
- return null;
- }
-
- @Override
- public ArchivaIndexingContext move(ArchivaIndexingContext context, Repository repo) throws IndexCreationFailedException {
- return null;
- }
-
- @Override
- public void updateLocalIndexPath(Repository repo) {
-
- }
-
- @Override
- public ArchivaIndexingContext mergeContexts(Repository destinationRepo, List<ArchivaIndexingContext> contexts, boolean packIndex) throws UnsupportedOperationException, IndexCreationFailedException {
- return null;
- }
-}
+++ /dev/null
-package org.apache.archiva.repository.mock;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.filelock.DefaultFileLockManager;
-import org.apache.archiva.common.utils.VersionUtil;
-import org.apache.archiva.maven.metadata.model.MavenArtifactFacet;
-import org.apache.archiva.metadata.model.ArtifactMetadata;
-import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
-import org.apache.archiva.repository.content.ContentAccessException;
-import org.apache.archiva.repository.ItemDeleteStatus;
-import org.apache.archiva.repository.content.LayoutException;
-import org.apache.archiva.repository.ManagedRepository;
-import org.apache.archiva.repository.ManagedRepositoryContent;
-import org.apache.archiva.repository.content.ManagedRepositoryContentLayout;
-import org.apache.archiva.repository.content.Artifact;
-import org.apache.archiva.repository.content.BaseDataItemTypes;
-import org.apache.archiva.repository.content.ContentItem;
-import org.apache.archiva.repository.content.DataItem;
-import org.apache.archiva.repository.content.ItemNotFoundException;
-import org.apache.archiva.repository.content.ItemSelector;
-import org.apache.archiva.repository.content.Namespace;
-import org.apache.archiva.repository.content.Project;
-import org.apache.archiva.repository.content.Version;
-import org.apache.archiva.repository.content.base.ArchivaArtifact;
-import org.apache.archiva.repository.content.base.ArchivaContentItem;
-import org.apache.archiva.repository.content.base.ArchivaDataItem;
-import org.apache.archiva.repository.content.base.ArchivaNamespace;
-import org.apache.archiva.repository.content.base.ArchivaProject;
-import org.apache.archiva.repository.content.base.ArchivaVersion;
-import org.apache.archiva.repository.storage.RepositoryStorage;
-import org.apache.archiva.repository.storage.StorageAsset;
-import org.apache.archiva.repository.storage.fs.FilesystemStorage;
-import org.springframework.stereotype.Service;
-
-import java.io.IOException;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.function.Consumer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Stream;
-
-/**
- * @author Martin Stockhammer <martin_s@apache.org>
- */
-@Service("managedRepositoryContent#mock")
-public class ManagedRepositoryContentMock implements BaseRepositoryContentLayout, ManagedRepositoryContent
-{
- private static final String PATH_SEPARATOR = "/";
- private static final String GROUP_SEPARATOR = ".";
- public static final String MAVEN_METADATA = "maven-metadata.xml";
-
-
- private ManagedRepository repository;
- private RepositoryStorage fsStorage;
-
- ManagedRepositoryContentMock(ManagedRepository repo) {
- this.repository = repo;
- this.fsStorage = repo;
- }
-
- @Override
- public <T extends ContentItem> T adaptItem( Class<T> clazz, ContentItem item ) throws LayoutException
- {
- if (clazz.isAssignableFrom( Version.class ))
- {
- if ( !item.hasCharacteristic( Version.class ) )
- {
- item.setCharacteristic( Version.class, createVersionFromPath( item.getAsset() ) );
- }
- return (T) item.adapt( Version.class );
- } else if ( clazz.isAssignableFrom( Project.class )) {
- if ( !item.hasCharacteristic( Project.class ) )
- {
- item.setCharacteristic( Project.class, createProjectFromPath( item.getAsset() ) );
- }
- return (T) item.adapt( Project.class );
- } else if ( clazz.isAssignableFrom( Namespace.class )) {
- if ( !item.hasCharacteristic( Namespace.class ) )
- {
- item.setCharacteristic( Namespace.class, createNamespaceFromPath( item.getAsset() ) );
- }
- return (T) item.adapt( Namespace.class );
- }
- throw new LayoutException( "Could not convert item to class " + clazz);
- }
-
- private Version createVersionFromPath( StorageAsset asset )
- {
- Project proj = createProjectFromPath( asset.getParent( ) );
- return ArchivaVersion.withRepository( this ).withAsset( asset )
- .withProject( proj ).withVersion( asset.getName( ) ).build();
- }
-
- private Project createProjectFromPath( StorageAsset asset) {
- Namespace ns = createNamespaceFromPath( asset );
- return ArchivaProject.withRepository( this ).withAsset( asset )
- .withNamespace( ns ).withId( asset.getName( ) ).build( );
- }
-
- private Namespace createNamespaceFromPath( StorageAsset asset) {
- String namespace = asset.getPath( ).replace( "/", "." );
- return ArchivaNamespace.withRepository( this )
- .withAsset( asset ).withNamespace( namespace ).build();
- }
-
- @Override
- public void deleteAllItems( ItemSelector selector, Consumer<ItemDeleteStatus> consumer ) throws ContentAccessException, IllegalArgumentException
- {
-
- }
-
- @Override
- public void deleteItem( ContentItem item ) throws ItemNotFoundException, ContentAccessException
- {
-
- }
-
- @Override
- public void copyItem( ContentItem item, ManagedRepository destinationRepository ) throws ItemNotFoundException, ContentAccessException
- {
-
- }
-
- @Override
- public void copyItem( ContentItem item, ManagedRepository destinationRepository, boolean updateMetadata ) throws ItemNotFoundException, ContentAccessException
- {
-
- }
-
- @Override
- public ContentItem getItem( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public Namespace getNamespace( ItemSelector namespaceSelector ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public Project getProject( ItemSelector projectSelector ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public Version getVersion( ItemSelector versionCoordinates ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public Artifact getArtifact( ItemSelector selector ) throws ContentAccessException
- {
- StringBuilder path = new StringBuilder(selector.getNamespace( ).replace( ".", "/" ));
- path.append( "/" ).append( selector.getProjectId( ) ).append( "/" ).append( selector.getVersion( ) );
- path.append( "/" ).append( selector.getArtifactId( ) ).append( "-" ).append( selector.getArtifactVersion( ) ).append( "." ).append( selector.getType( ) );
- StorageAsset asset = fsStorage.getAsset( path.toString( ) );
- ArchivaNamespace ns = ArchivaNamespace.withRepository( repository.getContent( ) ).withAsset( asset.getParent( ).getParent( ).getParent( ) ).withNamespace( selector.getNamespace( ) ).build( );
- ArchivaProject project = ArchivaProject.withRepository( repository.getContent( ) ).withAsset( asset.getParent( ).getParent( ) ).withNamespace( ns ).withId( selector.getProjectId( ) ).build( );
- ArchivaVersion version = ArchivaVersion.withRepository( repository.getContent( ) ).withAsset( asset.getParent( ) ).withProject( project ).withVersion( selector.getVersion( ) ).build( );
- ArchivaArtifact artifact = ArchivaArtifact.withAsset( asset ).withVersion( version ).withId( selector.getArtifactId( ) ).withArtifactVersion( selector.getArtifactVersion( ) ).withType( selector.getType( ) ).build( );
- return artifact;
- }
-
- @Override
- public Artifact getArtifact( String path ) throws LayoutException, ContentAccessException
- {
- StorageAsset asset = fsStorage.getAsset( path.toString( ) );
- String artifactId = asset.getName( );
- StorageAsset namespacePath = asset.getParent( ).getParent( ).getParent( );
- String namespaceId = namespacePath.getPath( ).replace( "/", "." );
- StorageAsset projectPath = asset.getParent( ).getParent( );
- String projectId = projectPath.getName( );
- StorageAsset versionPath = asset.getParent( );
- String versionId = versionPath.getName( );
- ArchivaNamespace ns = ArchivaNamespace.withRepository( repository.getContent( ) ).withAsset( namespacePath ).withNamespace( namespaceId ).build( );
- ArchivaProject project = ArchivaProject.withRepository( repository.getContent( ) ).withAsset( projectPath ).withNamespace( ns ).withId( projectId ).build( );
- ArchivaVersion version = ArchivaVersion.withRepository( repository.getContent( ) ).withAsset( versionPath ).withProject( project ).withVersion( versionId ).build( );
- ArchivaArtifact artifact = ArchivaArtifact.withAsset( asset ).withVersion( version ).withId( projectId ).withArtifactVersion( versionId ).build( );
- return artifact;
- }
-
- @Override
- public List<? extends Artifact> getArtifacts( ItemSelector selector ) throws ContentAccessException
- {
- return null;
- }
-
- @Override
- public Stream<? extends Artifact> newArtifactStream( ItemSelector selector ) throws ContentAccessException
- {
- return null;
- }
-
- @Override
- public Stream<? extends ContentItem> newItemStream( ItemSelector selector, boolean parallel ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public List<? extends Project> getProjects( Namespace namespace ) throws ContentAccessException
- {
- return null;
- }
-
- @Override
- public List<? extends Project> getProjects( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public List<? extends Version> getVersions( Project project ) throws ContentAccessException
- {
- return null;
- }
-
- @Override
- public List<? extends Version> getVersions( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public List<String> getArtifactVersions( ItemSelector selector ) throws ContentAccessException, IllegalArgumentException
- {
- return null;
- }
-
- @Override
- public List<? extends Artifact> getArtifacts( ContentItem item ) throws ContentAccessException
- {
- return null;
- }
-
- @Override
- public Stream<? extends Artifact> newArtifactStream( ContentItem item ) throws ContentAccessException
- {
- return null;
- }
-
- @Override
- public boolean hasContent( ItemSelector selector )
- {
- return false;
- }
-
- @Override
- public ContentItem getParent( ContentItem item )
- {
- try
- {
- return toItem( item.getAsset( ).getParent( ) );
- }
- catch ( LayoutException e )
- {
- throw new RuntimeException( "Bad layout conversion " + e.getMessage( ) );
- }
- }
-
- @Override
- public List<? extends ContentItem> getChildren( ContentItem item )
- {
- return null;
- }
-
- @Override
- public <T extends ContentItem> T applyCharacteristic( Class<T> clazz, ContentItem item ) throws LayoutException
- {
- return null;
- }
-
- @Override
- public <T extends ManagedRepositoryContentLayout> T getLayout( Class<T> clazz ) throws LayoutException
- {
- return (T) this;
- }
-
- @Override
- public <T extends ManagedRepositoryContentLayout> boolean supportsLayout( Class<T> clazz )
- {
- return true;
- }
-
- @Override
- public List<Class<? extends ManagedRepositoryContentLayout>> getSupportedLayouts( )
- {
- return null;
- }
-
- @Override
- public void addArtifact( Path sourceFile, Artifact destination ) throws IllegalArgumentException
- {
-
- }
-
- @Override
- public DataItem getMetadataItem( Version version )
- {
- return ArchivaDataItem.withAsset( version.getAsset( ).resolve( "maven-metadata.xml" ) ).withId( "maven-metadata.xml" )
- .withDataType( BaseDataItemTypes.METADATA ).build();
- }
-
- @Override
- public DataItem getMetadataItem( Project project )
- {
- return ArchivaDataItem.withAsset( project.getAsset( ).resolve( "maven-metadata.xml" ) ).withId( "maven-metadata.xml" )
- .withDataType( BaseDataItemTypes.METADATA ).build( );
- }
-
- @Override
- public ContentItem toItem( String path ) throws LayoutException
- {
- StorageAsset asset = repository.getRoot().resolve( path );
- return toItem( asset );
- }
-
- @Override
- public ContentItem toItem( StorageAsset asset ) throws LayoutException
- {
- if (asset.isLeaf()) {
- return ArchivaDataItem.withAsset( asset ).withId( asset.getName( ) ).build();
- } else
- {
- return ArchivaContentItem.withRepository( this )
- .withAsset( asset )
- .build( );
- }
- }
-
- @Override
- public String toPath( ContentItem item )
- {
- return item.getAsset( ).getPath( );
- }
-
- @Override
- public String getId( )
- {
- return repository.getId();
- }
-
- private StorageAsset getRepoRootAsset() {
- if (fsStorage==null) {
- try {
- fsStorage = new FilesystemStorage(Paths.get("", "target", "test-repository", "managed"), new DefaultFileLockManager());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return fsStorage.getRoot();
- }
-
- @Override
- public ManagedRepository getRepository( )
- {
- return repository;
- }
-
- @Override
- public void setRepository( ManagedRepository repo )
- {
- this.repository = repo;
- }
-
- public ArtifactMetadata getArtifactForPath( String repoId, String relativePath )
- {
- String[] parts = relativePath.replace( '\\', '/' ).split( "/" );
-
- int len = parts.length;
- if ( len < 4 )
- {
- throw new IllegalArgumentException(
- "Not a valid artifact path in a Maven 2 repository, not enough directories: " + relativePath );
- }
-
- String id = parts[--len];
- String baseVersion = parts[--len];
- String artifactId = parts[--len];
- StringBuilder groupIdBuilder = new StringBuilder();
- for ( int i = 0; i < len - 1; i++ )
- {
- groupIdBuilder.append( parts[i] );
- groupIdBuilder.append( '.' );
- }
- groupIdBuilder.append( parts[len - 1] );
-
- return getArtifactFromId( repoId, groupIdBuilder.toString(), artifactId, baseVersion, id );
- }
-
- private static final Pattern TIMESTAMP_PATTERN = Pattern.compile( "([0-9]{8}.[0-9]{6})-([0-9]+).*" );
-
-
-
- public ArtifactMetadata getArtifactFromId( String repoId, String namespace, String projectId, String projectVersion,
- String id )
- {
- if ( !id.startsWith( projectId + "-" ) )
- {
- throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
- + "' doesn't start with artifact ID '" + projectId + "'" );
- }
-
- MavenArtifactFacet facet = new MavenArtifactFacet();
-
- int index = projectId.length() + 1;
- String version;
- String idSubStrFromVersion = id.substring( index );
- if ( idSubStrFromVersion.startsWith( projectVersion ) && !VersionUtil.isUniqueSnapshot( projectVersion ) )
- {
- // non-snapshot versions, or non-timestamped snapshot versions
- version = projectVersion;
- }
- else if ( VersionUtil.isGenericSnapshot( projectVersion ) )
- {
- // timestamped snapshots
- try
- {
- int mainVersionLength = projectVersion.length() - 8; // 8 is length of "SNAPSHOT"
- if ( mainVersionLength == 0 )
- {
- throw new IllegalArgumentException(
- "Timestamped snapshots must contain the main version, filename was '" + id + "'" );
- }
-
- Matcher m = TIMESTAMP_PATTERN.matcher( idSubStrFromVersion.substring( mainVersionLength ) );
- m.matches();
- String timestamp = m.group( 1 );
- String buildNumber = m.group( 2 );
- facet.setTimestamp( timestamp );
- facet.setBuildNumber( Integer.parseInt( buildNumber ) );
- version = idSubStrFromVersion.substring( 0, mainVersionLength ) + timestamp + "-" + buildNumber;
- }
- catch ( IllegalStateException e )
- {
- throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
- + "' doesn't contain a timestamped version matching snapshot '"
- + projectVersion + "'", e);
- }
- }
- else
- {
- // invalid
- throw new IllegalArgumentException(
- "Not a valid artifact path in a Maven 2 repository, filename '" + id + "' doesn't contain version '"
- + projectVersion + "'" );
- }
-
- String classifier;
- String ext;
- index += version.length();
- if ( index == id.length() )
- {
- // no classifier or extension
- classifier = null;
- ext = null;
- }
- else
- {
- char c = id.charAt( index );
- if ( c == '-' )
- {
- // classifier up until '.'
- int extIndex = id.indexOf( '.', index );
- if ( extIndex >= 0 )
- {
- classifier = id.substring( index + 1, extIndex );
- ext = id.substring( extIndex + 1 );
- }
- else
- {
- classifier = id.substring( index + 1 );
- ext = null;
- }
- }
- else if ( c == '.' )
- {
- // rest is the extension
- classifier = null;
- ext = id.substring( index + 1 );
- }
- else
- {
- throw new IllegalArgumentException( "Not a valid artifact path in a Maven 2 repository, filename '" + id
- + "' expected classifier or extension but got '"
- + id.substring( index ) + "'" );
- }
- }
-
- ArtifactMetadata metadata = new ArtifactMetadata();
- metadata.setId( id );
- metadata.setNamespace( namespace );
- metadata.setProject( projectId );
- metadata.setRepositoryId( repoId );
- metadata.setProjectVersion( projectVersion );
- metadata.setVersion( version );
-
- facet.setClassifier( classifier );
-
- // we use our own provider here instead of directly accessing Maven's artifact handlers as it has no way
- // to select the correct order to apply multiple extensions mappings to a preferred type
- // TODO: this won't allow the user to decide order to apply them if there are conflicts or desired changes -
- // perhaps the plugins could register missing entries in configuration, then we just use configuration
- // here?
-
- String type = null;
-
-
- // use extension as default
- if ( type == null )
- {
- type = ext;
- }
-
- // TODO: should we allow this instead?
- if ( type == null )
- {
- throw new IllegalArgumentException(
- "Not a valid artifact path in a Maven 2 repository, filename '" + id + "' does not have a type" );
- }
-
- facet.setType( type );
- metadata.addFacet( facet );
-
- return metadata;
- }
-
-
- private String formatAsDirectory( String directory )
- {
- return directory.replace( GROUP_SEPARATOR, PATH_SEPARATOR );
- }
-
- @Override
- public String toPath( ItemSelector selector )
- {
- return null;
- }
-
- @Override
- public ItemSelector toItemSelector( String path ) throws LayoutException
- {
- return null;
- }
-
- @Override
- public ManagedRepositoryContent getGenericContent( )
- {
- return null;
- }
-}
+++ /dev/null
-package org.apache.archiva.repository.mock;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.common.utils.VersionUtil;
-import org.apache.archiva.repository.content.LayoutException;
-import org.apache.archiva.repository.RemoteRepository;
-import org.apache.archiva.repository.RemoteRepositoryContent;
-import org.apache.archiva.repository.content.ItemSelector;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.stereotype.Service;
-
-/**
- * @author Martin Stockhammer <martin_s@apache.org>
- */
-@Service("remoteRepositoryContent#mock")
-public class RemoteRepositoryContentMock implements RemoteRepositoryContent
-{
- RemoteRepository repository;
-
- RemoteRepositoryContentMock(RemoteRepository repo) {
- this.repository = repo;
- }
-
- @Override
- public String getId( )
- {
- return repository.getId();
- }
-
- @Override
- public RemoteRepository getRepository( )
- {
- return repository;
- }
-
- @Override
- public void setRepository( RemoteRepository repo )
- {
- this.repository = repo;
- }
-
- @Override
- public String toPath( ItemSelector selector )
- {
- String baseVersion;
- if (!selector.hasVersion() && VersionUtil.isSnapshot(selector.getArtifactVersion())) {
- baseVersion=VersionUtil.getBaseVersion(selector.getArtifactVersion());
- } else {
- baseVersion=selector.getVersion();
- }
- return selector.getNamespace().replaceAll("\\.", "/")+"/"+selector.getArtifactId()+"/"+baseVersion+"/"
- +selector.getArtifactId()+"-"+selector.getVersion()+(
- StringUtils.isNotEmpty(selector.getClassifier()) ? "-"+selector.getClassifier() : "")+"."+selector.getType();
- }
-
- @Override
- public ItemSelector toItemSelector( String path ) throws LayoutException
- {
- return null;
- }
-
-}
+++ /dev/null
-package org.apache.archiva.repository.mock;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.repository.*;
-import org.springframework.stereotype.Service;
-
-import java.util.HashSet;
-import java.util.Set;
-
-@Service("repositoryContentProvider#mock")
-public class RepositoryContentProviderMock implements RepositoryContentProvider {
-
- private static final Set<RepositoryType> REPOSITORY_TYPES = new HashSet<>();
- static {
- REPOSITORY_TYPES.add(RepositoryType.MAVEN);
- REPOSITORY_TYPES.add(RepositoryType.NPM);
- }
-
- @Override
- public boolean supportsLayout(String layout) {
- return true;
- }
-
- @Override
- public Set<RepositoryType> getSupportedRepositoryTypes() {
- return REPOSITORY_TYPES;
- }
-
- @Override
- public boolean supports(RepositoryType type) {
- return true;
- }
-
- @Override
- public RemoteRepositoryContent createRemoteContent(RemoteRepository repository) throws RepositoryException {
- return new RemoteRepositoryContentMock(repository);
- }
-
- @Override
- public ManagedRepositoryContent createManagedContent( ManagedRepository repository) throws RepositoryException {
- return new ManagedRepositoryContentMock(repository);
- }
-
- @Override
- public <T extends RepositoryContent, V extends Repository> T createContent(Class<T> clazz, V repository) throws RepositoryException {
- return null;
- }
-}
+++ /dev/null
-package org.apache.archiva.repository.mock;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.configuration.ManagedRepositoryConfiguration;
-import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
-import org.apache.archiva.configuration.RepositoryGroupConfiguration;
-import org.apache.archiva.event.EventHandler;
-import org.apache.archiva.repository.base.managed.BasicManagedRepository;
-import org.apache.archiva.repository.base.remote.BasicRemoteRepository;
-import org.apache.archiva.repository.EditableManagedRepository;
-import org.apache.archiva.repository.EditableRemoteRepository;
-import org.apache.archiva.repository.EditableRepositoryGroup;
-import org.apache.archiva.repository.ManagedRepository;
-import org.apache.archiva.repository.base.PasswordCredentials;
-import org.apache.archiva.repository.ReleaseScheme;
-import org.apache.archiva.repository.RemoteRepository;
-import org.apache.archiva.repository.RepositoryCredentials;
-import org.apache.archiva.event.Event;
-import org.apache.archiva.repository.RepositoryException;
-import org.apache.archiva.repository.RepositoryGroup;
-import org.apache.archiva.repository.RepositoryProvider;
-import org.apache.archiva.repository.RepositoryType;
-import org.apache.archiva.repository.event.RepositoryEvent;
-import org.apache.archiva.repository.features.ArtifactCleanupFeature;
-import org.apache.archiva.repository.features.IndexCreationFeature;
-import org.apache.archiva.repository.features.RemoteIndexFeature;
-import org.apache.archiva.repository.features.StagingRepositoryFeature;
-import org.springframework.stereotype.Service;
-
-import java.io.IOException;
-import java.net.URI;
-import java.nio.file.Paths;
-import java.time.Duration;
-import java.time.Period;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Just a simple mock class for the repository provider
- */
-@Service("mockRepositoryProvider")
-public class RepositoryProviderMock implements RepositoryProvider
-{
-
- private static final Set<RepositoryType> TYPES = new HashSet<>( );
-
- static
- {
- TYPES.add( RepositoryType.MAVEN );
- TYPES.add( RepositoryType.NPM );
- }
-
- @Override
- public Set<RepositoryType> provides( )
- {
- return TYPES;
- }
-
- @Override
- public EditableManagedRepository createManagedInstance( String id, String name ) throws IOException {
- return BasicManagedRepository.newFilesystemInstance(id, name, Paths.get("target/repositories").resolve(id));
- }
-
- @Override
- public EditableRemoteRepository createRemoteInstance( String id, String name )
- {
- try {
- return BasicRemoteRepository.newFilesystemInstance( id, name, Paths.get("target/remotes") );
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public EditableRepositoryGroup createRepositoryGroup( String id, String name )
- {
- return null;
- }
-
- @Override
- public ManagedRepository createManagedInstance( ManagedRepositoryConfiguration configuration ) throws RepositoryException
- {
- BasicManagedRepository managedRepository = null;
- try {
- managedRepository = BasicManagedRepository.newFilesystemInstance( configuration.getId( ), configuration.getName( ) , Paths.get("target/repositories").resolve(configuration.getId()));
- } catch (IOException e) {
- throw new RepositoryException(e);
- }
- updateManagedInstance( managedRepository, configuration );
- return managedRepository;
- }
-
-
- @Override
- public void updateManagedInstance( EditableManagedRepository managedRepository, ManagedRepositoryConfiguration configuration ) throws RepositoryException
- {
- try
- {
- managedRepository.setName( managedRepository.getPrimaryLocale(), configuration.getName( ) );
- managedRepository.setLocation( new URI( configuration.getLocation( )==null ?"" : configuration.getLocation() ) );
- managedRepository.setBaseUri( new URI( "" ) );
- managedRepository.setBlocksRedeployment( configuration.isBlockRedeployments( ) );
- managedRepository.setDescription( managedRepository.getPrimaryLocale(), configuration.getDescription( ) );
- managedRepository.setLayout( configuration.getLayout( ) );
- managedRepository.setScanned( configuration.isScanned( ) );
- managedRepository.setSchedulingDefinition( configuration.getRefreshCronExpression( ) );
- if (configuration.isReleases()) {
- managedRepository.addActiveReleaseScheme( ReleaseScheme.RELEASE );
- }
- if (configuration.isSnapshots()) {
- managedRepository.addActiveReleaseScheme( ReleaseScheme.SNAPSHOT );
- }
- ArtifactCleanupFeature acf = managedRepository.getFeature( ArtifactCleanupFeature.class ).get( );
- acf.setRetentionPeriod( Period.ofDays( configuration.getRetentionPeriod( ) ) );
- acf.setDeleteReleasedSnapshots( configuration.isDeleteReleasedSnapshots( ) );
- acf.setRetentionCount( configuration.getRetentionCount( ) );
- IndexCreationFeature icf = managedRepository.getFeature( IndexCreationFeature.class ).get( );
- icf.setIndexPath( new URI( configuration.getIndexDir( ) ) );
- icf.setSkipPackedIndexCreation( configuration.isSkipPackedIndexCreation( ) );
- StagingRepositoryFeature srf = managedRepository.getFeature( StagingRepositoryFeature.class ).get( );
- srf.setStageRepoNeeded( configuration.isStageRepoNeeded( ) );
- }
- catch ( Exception e )
- {
- throw new RepositoryException( "Error", e );
- }
-
- }
-
-
- @Override
- public ManagedRepository createStagingInstance( ManagedRepositoryConfiguration configuration ) throws RepositoryException
- {
- String id = configuration.getId( ) + StagingRepositoryFeature.STAGING_REPO_POSTFIX;
- BasicManagedRepository managedRepository = null;
- try {
- managedRepository = BasicManagedRepository.newFilesystemInstance(id, configuration.getName(), Paths.get("target/repositories").resolve(id));
- } catch (IOException e) {
- throw new RepositoryException(e);
- }
- updateManagedInstance( managedRepository, configuration );
- return managedRepository;
- }
-
- @Override
- public RemoteRepository createRemoteInstance( RemoteRepositoryConfiguration configuration ) throws RepositoryException
- {
- BasicRemoteRepository remoteRepository = null;
- try {
- remoteRepository = BasicRemoteRepository.newFilesystemInstance( configuration.getId( ), configuration.getName( ), Paths.get("target/remotes") );
- } catch (IOException e) {
- throw new RepositoryException(e);
- }
- updateRemoteInstance( remoteRepository, configuration );
- return remoteRepository;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void updateRemoteInstance( EditableRemoteRepository remoteRepository, RemoteRepositoryConfiguration configuration ) throws RepositoryException
- {
- try
- {
- remoteRepository.setName( remoteRepository.getPrimaryLocale(), configuration.getName( ) );
- remoteRepository.setBaseUri( new URI( "" ) );
- remoteRepository.setDescription( remoteRepository.getPrimaryLocale(), configuration.getDescription( ) );
- remoteRepository.setLayout( configuration.getLayout( ) );
- remoteRepository.setSchedulingDefinition( configuration.getRefreshCronExpression( ) );
- remoteRepository.setCheckPath( configuration.getCheckPath( ) );
- remoteRepository.setExtraHeaders( configuration.getExtraHeaders( ) );
- remoteRepository.setExtraParameters( configuration.getExtraParameters( ) );
- remoteRepository.setTimeout( Duration.ofSeconds( configuration.getTimeout( ) ) );
- char[] pwd = configuration.getPassword()==null ? "".toCharArray() : configuration.getPassword().toCharArray();
- remoteRepository.setCredentials( new PasswordCredentials( configuration.getUsername( ), pwd ) );
- remoteRepository.setLocation( new URI( configuration.getUrl( )==null ? "" : configuration.getUrl() ) );
- RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
- rif.setDownloadRemoteIndexOnStartup( configuration.isDownloadRemoteIndexOnStartup( ) );
- rif.setDownloadRemoteIndex( configuration.isDownloadRemoteIndex( ) );
- rif.setIndexUri( new URI( configuration.getIndexDir( ) ) );
- rif.setDownloadTimeout( Duration.ofSeconds( configuration.getRemoteDownloadTimeout( ) ) );
- rif.setProxyId( configuration.getRemoteDownloadNetworkProxyId( ) );
- IndexCreationFeature icf = remoteRepository.getFeature(IndexCreationFeature.class).get();
- icf.setIndexPath(new URI(".index" ));
- }
- catch ( Exception e )
- {
- throw new RepositoryException( "Error while updating remote instance: "+e.getMessage(), e );
- }
-
- }
-
- @Override
- public RepositoryGroup createRepositoryGroup( RepositoryGroupConfiguration configuration ) throws RepositoryException
- {
- return null;
- }
-
- @Override
- public void updateRepositoryGroupInstance( EditableRepositoryGroup repositoryGroup, RepositoryGroupConfiguration configuration ) throws RepositoryException
- {
-
- }
-
- @Override
- public ManagedRepositoryConfiguration getManagedConfiguration( ManagedRepository managedRepository ) throws RepositoryException
- {
- ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration( );
- configuration.setId( managedRepository.getId( ) );
- configuration.setName(managedRepository.getName());
- configuration.setLocation( managedRepository.getLocation( ) == null ? "" : managedRepository.getLocation().toString( ) );
- configuration.setBlockRedeployments( managedRepository.blocksRedeployments( ) );
- configuration.setDescription( managedRepository.getDescription( ) );
- configuration.setLayout( managedRepository.getLayout( ) );
- configuration.setScanned( managedRepository.isScanned( ) );
- configuration.setRefreshCronExpression( managedRepository.getSchedulingDefinition( ) );
- configuration.setReleases( managedRepository.getActiveReleaseSchemes().contains(ReleaseScheme.RELEASE) );
- configuration.setSnapshots( managedRepository.getActiveReleaseSchemes().contains(ReleaseScheme.SNAPSHOT) );
- ArtifactCleanupFeature acf = managedRepository.getFeature( ArtifactCleanupFeature.class ).get( );
- configuration.setRetentionPeriod( acf.getRetentionPeriod( ).getDays( ) );
- configuration.setDeleteReleasedSnapshots( acf.isDeleteReleasedSnapshots( ) );
- configuration.setRetentionCount( acf.getRetentionCount( ) );
- IndexCreationFeature icf = managedRepository.getFeature( IndexCreationFeature.class ).get( );
- configuration.setSkipPackedIndexCreation( icf.isSkipPackedIndexCreation( ) );
- configuration.setIndexDir( icf.getIndexPath( ) == null ? "" : icf.getIndexPath().toString( ) );
- StagingRepositoryFeature srf = managedRepository.getFeature( StagingRepositoryFeature.class ).get( );
- configuration.setStageRepoNeeded( srf.isStageRepoNeeded( ) );
- return configuration;
- }
-
- @Override
- public RepositoryGroupConfiguration getRepositoryGroupConfiguration( RepositoryGroup repositoryGroup ) throws RepositoryException
- {
- return null;
- }
-
- @Override
- public void addRepositoryEventHandler( EventHandler<? super RepositoryEvent> eventHandler )
- {
- // do nothing
- }
-
-
- @Override
- public RemoteRepositoryConfiguration getRemoteConfiguration( RemoteRepository remoteRepository ) throws RepositoryException
- {
- RemoteRepositoryConfiguration configuration = new RemoteRepositoryConfiguration( );
- configuration.setId( remoteRepository.getId( ) );
- configuration.setName( remoteRepository.getName( ) );
- configuration.setDescription( remoteRepository.getDescription( ) );
- configuration.setLayout( remoteRepository.getLayout( ) );
- configuration.setRefreshCronExpression( remoteRepository.getSchedulingDefinition( ) );
- configuration.setCheckPath( remoteRepository.getCheckPath( ) );
- configuration.setExtraHeaders( remoteRepository.getExtraHeaders( ) );
- configuration.setExtraParameters( remoteRepository.getExtraParameters( ) );
- configuration.setTimeout( (int) remoteRepository.getTimeout( ).getSeconds( ) );
- RepositoryCredentials creds = remoteRepository.getLoginCredentials( );
- if (creds!=null)
- {
- PasswordCredentials pwdCreds = (PasswordCredentials) creds;
- configuration.setUsername( pwdCreds.getUsername( ) );
- configuration.setPassword( new String( pwdCreds.getPassword( ) ) );
- }
- configuration.setUrl( remoteRepository.getLocation( ) == null ? "" : remoteRepository.getLocation().toString( ) );
- RemoteIndexFeature rif = remoteRepository.getFeature( RemoteIndexFeature.class ).get( );
- configuration.setDownloadRemoteIndex( rif.isDownloadRemoteIndex( ) );
- configuration.setDownloadRemoteIndexOnStartup( rif.isDownloadRemoteIndexOnStartup( ) );
- configuration.setIndexDir( rif.getIndexUri( )==null ? "" : rif.getIndexUri().toString( ) );
- configuration.setRemoteDownloadNetworkProxyId( rif.getProxyId( ) );
- return configuration;
- }
-
- @Override
- public void handle(Event event) {
-
- }
-}
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init="true">
- <context:component-scan base-package="org.apache.archiva.proxy.maven"/>
+ <context:component-scan base-package="org.apache.archiva.maven.proxy"/>
<bean name="wagon#file" scope="prototype" class="org.apache.maven.wagon.providers.file.FileWagon"/>
default-lazy-init="true">
<context:annotation-config/>
- <context:component-scan base-package="org.apache.archiva.metadata.repository,org.apache.archiva.proxy,org.apache.archiva.repository.mock"/>
+ <context:component-scan base-package="org.apache.archiva.metadata,org.apache.archiva.proxy,org.apache.archiva.maven.proxy.mock"/>
<alias name="mockRepositoryProvider" alias="mavenRepositoryProvider" />
<alias name="archivaConfiguration#mock" alias="archivaConfiguration#default"/>
</property>
</bean>
- <bean name="repositoryContentProvider#mocked" class="org.apache.archiva.repository.mock.RepositoryContentProviderMock" />
+ <bean name="repositoryContentProvider#mocked" class="org.apache.archiva.maven.proxy.mock.repository.RepositoryContentProviderMock" />
<bean name="repositoryProxyHandler#test" class="org.apache.archiva.maven.proxy.MavenRepositoryProxyHandler">
<property name="timeToLiveSeconds" value="1800"/>
</bean>
- <bean name="wagon#http" class="org.apache.archiva.proxy.WagonDelegate" scope="singleton"/>
+ <bean name="wagon#http" class="org.apache.archiva.maven.proxy.WagonDelegate" scope="singleton"/>
<bean name="wagon#file" scope="prototype" class="org.apache.maven.wagon.providers.file.FileWagon"/>
<alias name="userConfiguration#redback" alias="userConfiguration#default"/>
* under the License.
*/
-import org.apache.archiva.maven2.model.TreeEntry;
+import org.apache.archiva.maven.model.TreeEntry;
import org.eclipse.aether.graph.DependencyVisitor;
import java.util.List;
import org.apache.archiva.admin.model.networkproxy.NetworkProxyAdmin;
import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin;
import org.apache.archiva.common.utils.VersionUtil;
-import org.apache.archiva.maven2.model.TreeEntry;
+import org.apache.archiva.maven.model.TreeEntry;
import org.apache.archiva.maven.metadata.MavenMetadataReader;
import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
import org.apache.archiva.model.ArchivaRepositoryMetadata;
* under the License.
*/
-import org.apache.archiva.maven2.model.Artifact;
-import org.apache.archiva.maven2.model.TreeEntry;
+import org.apache.archiva.maven.model.Artifact;
+import org.apache.archiva.maven.model.TreeEntry;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.DependencyVisitor;
import org.modelmapper.ModelMapper;
import org.apache.archiva.model.SnapshotVersion;
import org.apache.archiva.policies.ProxyDownloadException;
import org.apache.archiva.proxy.ProxyRegistry;
-import org.apache.archiva.maven.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.proxy.model.ProxyConnector;
import org.apache.archiva.proxy.model.RepositoryProxyHandler;
import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.model.SnapshotVersion;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryException;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryException;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.RemoteRepository;
import org.apache.archiva.configuration.ArchivaConfiguration;
import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
-import org.apache.archiva.maven2.model.Artifact;
-import org.apache.archiva.maven2.model.TreeEntry;
+import org.apache.archiva.maven.model.Artifact;
+import org.apache.archiva.maven.model.TreeEntry;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.junit.Before;
import org.apache.archiva.metadata.model.MailingList;
import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.repository.ReleaseScheme;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException;
-import org.apache.archiva.maven.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
import org.junit.Before;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException;
import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.archiva.indexer.IndexUpdateFailedException;
import org.apache.archiva.indexer.UnsupportedBaseContextException;
import org.apache.archiva.proxy.ProxyRegistry;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryException;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryException;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.configuration.ConfigurationEvent;
import org.apache.archiva.configuration.ConfigurationListener;
import org.apache.archiva.indexer.UnsupportedBaseContextException;
-import org.apache.archiva.maven.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.features.RemoteIndexFeature;
import org.apache.commons.lang3.StringUtils;
* under the License.
*/
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.base.PasswordCredentials;
import org.apache.archiva.repository.RemoteRepository;
* under the License.
*/
-import org.apache.archiva.maven.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.RemoteRepository;
import org.apache.maven.index.packer.IndexPacker;
import org.apache.archiva.indexer.IndexCreationFailedException;
import org.apache.archiva.indexer.IndexUpdateFailedException;
import org.apache.archiva.indexer.UnsupportedBaseContextException;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryException;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryException;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.ManagedRepository;
* under the License.
*/
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.maven2.model.Artifact;
-import org.apache.archiva.maven2.model.TreeEntry;
+import org.apache.archiva.maven.model.Artifact;
+import org.apache.archiva.maven.model.TreeEntry;
import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.rest.api.model.ActionStatus;
*/
import io.swagger.v3.oas.annotations.tags.Tag;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.security.common.ArchivaRoleConstants;
*/
import io.swagger.v3.oas.annotations.tags.Tag;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
import org.apache.archiva.rest.api.model.ActionStatus;
import io.swagger.v3.oas.annotations.tags.Tag;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.rest.api.model.ChecksumSearch;
import org.apache.archiva.rest.api.model.GroupIdList;
import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin;
import org.apache.archiva.common.utils.VersionUtil;
import org.apache.archiva.indexer.search.SearchResultHit;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.metadata.model.facets.AuditEvent;
import org.apache.archiva.metadata.repository.RepositorySessionFactory;
import org.apache.archiva.repository.ManagedRepositoryContent;
import org.apache.archiva.repository.content.base.ArchivaItemSelector;
import org.apache.archiva.repository.maven.dependency.tree.DependencyTreeBuilder;
-import org.apache.archiva.maven2.model.Artifact;
-import org.apache.archiva.maven2.model.TreeEntry;
+import org.apache.archiva.maven.model.Artifact;
+import org.apache.archiva.maven.model.TreeEntry;
import org.apache.archiva.metadata.generic.GenericMetadataFacet;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.metadata.model.MetadataFacet;
*/
import org.apache.archiva.common.utils.VersionUtil;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.metadata.model.facets.AuditEvent;
import org.apache.archiva.metadata.repository.MetadataRepository;
import org.apache.archiva.admin.model.beans.RemoteRepository;
import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
import org.apache.archiva.proxy.ProxyRegistry;
-import org.apache.archiva.maven.proxy.WagonFactory;
-import org.apache.archiva.maven.proxy.WagonFactoryRequest;
+import org.apache.archiva.maven.common.proxy.WagonFactory;
+import org.apache.archiva.maven.common.proxy.WagonFactoryRequest;
import org.apache.archiva.proxy.model.NetworkProxy;
import org.apache.archiva.rest.api.model.ActionStatus;
import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
import org.apache.archiva.common.utils.VersionUtil;
import org.apache.archiva.components.cache.Cache;
import org.apache.archiva.components.taskqueue.TaskQueueException;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.audit.RepositoryListener;
import org.apache.archiva.maven.metadata.model.MavenArtifactFacet;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.indexer.search.SearchResultHit;
import org.apache.archiva.indexer.search.SearchResultLimits;
import org.apache.archiva.indexer.search.SearchResults;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.metadata.repository.MetadataRepository;
import org.apache.archiva.metadata.repository.MetadataRepositoryException;
* under the License.
*/
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.maven.metadata.model.MavenArtifactFacet;
import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
*/
import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.redback.rest.api.model.Role;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
* under the License.
*/
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.rest.api.services.MergeRepositoriesService;
-import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
*/
import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.redback.rest.api.services.UserService;
import org.apache.archiva.rest.api.model.BrowseResult;
import org.apache.archiva.rest.api.model.BrowseResultEntry;
*/
import org.apache.archiva.admin.model.beans.UiConfiguration;
-import org.apache.archiva.maven2.model.Artifact;
+import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.rest.api.model.ChecksumSearch;
import org.apache.archiva.rest.api.model.SearchRequest;
import org.apache.archiva.rest.api.services.SearchService;
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.maven2.model.Artifact;
+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.redback.rest.services.FakeCreateAdminService;
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.admin.model.beans.ProxyConnector;
import org.apache.archiva.admin.model.beans.RemoteRepository;
import org.apache.archiva.admin.model.beans.RepositoryGroup;
-import org.apache.archiva.maven2.model.Artifact;
+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.redback.rest.services.FakeCreateAdminService;
import org.apache.archiva.rest.api.model.SearchRequest;
import org.apache.archiva.rest.api.services.ManagedRepositoriesService;
import org.apache.archiva.rest.api.services.ProxyConnectorService;