diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml new file mode 100644 index 00000000..63ca7bc8 --- /dev/null +++ b/.github/dependabot.yaml @@ -0,0 +1,28 @@ +# +# Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +version: 2 +updates: + - package-ecosystem: "maven" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" + + - package-ecosystem: "github-actions" # Also update Github actions + directory: "/" + schedule: + # Check for updates to GitHub Actions every week + interval: "weekly" diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml new file mode 100644 index 00000000..0f950c11 --- /dev/null +++ b/.github/workflows/maven-build.yml @@ -0,0 +1,67 @@ +# +# Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +name: build on maven + +on: + watch: + types: [started] + pull_request: + types: [opened, reopened, edited, synchronize, ready_for_review] + push: + branches: + - main + - master + + workflow_dispatch: + +jobs: + build: + name: Build with maven + runs-on: ubuntu-latest + env: + MAVEN_OPTS: "-Xmx4096m -Xms2048m -XX:MaxMetaspaceSize=4096m -Xss8m" + steps: + - uses: actions/checkout@v6 + + - name: Set up JDK 11 for x64 + uses: actions/setup-java@v5 + with: + java-version: '11' + distribution: 'temurin' + architecture: x64 + + - uses: s4u/maven-settings-action@v4.0.0 + with: + sonatypeSnapshots: true + + - name: Build the Maven verify phase + run: mvn -B -V clean verify -Prun-its -Pci + + + - uses: s4u/maven-settings-action@v4.0.0 + if: ${{ github.event_name == 'push' }} + with: + servers: | + [{ + "id": "central-portal-snapshots", + "username": "${{ secrets.SONATYPE_BOT_USERNAME }}", + "password": "${{ secrets.SONATYPE_BOT_TOKEN }}" + }] + + - name: Deploy the artifact + if: ${{ github.event_name == 'push' }} + run: mvn help:effective-settings -B -V clean deploy -e diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..5db1c859 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# build +target + +# eclipse +.classpath +.project +.settings + +# idea +.idea +*.iml +*.iws +*.ipr diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..735c2031 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: java +install: '/bin/true' +script: '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && mvn deploy -s ./travis-settings.xml -V -Prun-its -q -B -e|| mvn install -s ./travis-settings.xml -V -Prun-its -q -B -e' + diff --git a/Jenkinsfile.bak b/Jenkinsfile.bak new file mode 100644 index 00000000..61c4af3d --- /dev/null +++ b/Jenkinsfile.bak @@ -0,0 +1,25 @@ +pipeline { + agent { label 'maven-36-jdk11' } + stages { + stage('Prepare') { + steps { + sh 'printenv' + } + } + stage('Build') { + when { + expression { env.CHANGE_ID != null } // Pull request + } + steps { + sh 'mvn -B -V clean verify -Prun-its -Pci' + } + } + stage('Deploy') { + when { branch 'master' } + steps { + echo "Deploy" + sh 'mvn help:effective-settings -B -V clean deploy -e' + } + } + } +} diff --git a/LICENSE.txt b/LICENSE.txt index 82ad83d5..8f49face 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,3 +1,19 @@ +==== + Copyright (C) 2012 Red Hat, Inc. (jdcasey@commonjava.org) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==== + #------------------------------------------------------------------------------- # Copyright (c) 2014 Red Hat, Inc.. # All rights reserved. This program and the accompanying materials diff --git a/bindings/jackson-identities/pom.xml b/bindings/jackson-identities/pom.xml new file mode 100644 index 00000000..721b6af3 --- /dev/null +++ b/bindings/jackson-identities/pom.xml @@ -0,0 +1,43 @@ + + + + 4.0.0 + + + org.commonjava.atlas + atlas-bindings-parent + 1.2.3-SNAPSHOT + + + atlas-bindings-jackson-identities + + Atlas :: Maven Project-Graph :: Jackson Identities API Bindings + + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-core + + + + diff --git a/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefDeserializer.java b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefDeserializer.java new file mode 100644 index 00000000..206a8965 --- /dev/null +++ b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefDeserializer.java @@ -0,0 +1,48 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.jackson; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; + +import java.io.IOException; + +/** + * Created by jdcasey on 8/26/15. + */ +public class ProjectRefDeserializer + extends StdDeserializer +{ + private static final long serialVersionUID = 1L; + + private final Class refCls; + + public ProjectRefDeserializer( final Class refCls ) + { + super( refCls ); + this.refCls = refCls; + } + + @Override + public T deserialize( final JsonParser jp, final DeserializationContext ctxt ) + throws IOException, JsonProcessingException + { + return SerializerIdentityUtils.parse( jp.getText(), refCls ); + } +} diff --git a/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefKeyDeserializer.java b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefKeyDeserializer.java new file mode 100644 index 00000000..f9b78230 --- /dev/null +++ b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefKeyDeserializer.java @@ -0,0 +1,46 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.jackson; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.KeyDeserializer; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; + +import java.io.IOException; + +/** + * Created by jdcasey on 8/26/15. + */ +public class ProjectRefKeyDeserializer + extends KeyDeserializer +{ + private static final long serialVersionUID = 1L; + + private final Class refCls; + + public ProjectRefKeyDeserializer( final Class type ) + { + this.refCls = type; + } + + @Override + public Object deserializeKey( String key, DeserializationContext ctxt ) + throws IOException, JsonProcessingException + { + return SerializerIdentityUtils.parse( key, refCls ); + } +} diff --git a/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefSerializer.java b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefSerializer.java new file mode 100644 index 00000000..048d80bf --- /dev/null +++ b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectRefSerializer.java @@ -0,0 +1,53 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.jackson; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; + +import java.io.IOException; + +/** + * Created by jdcasey on 8/26/15. + */ +public final class ProjectRefSerializer + extends StdSerializer +{ + private boolean keySer; + + public ProjectRefSerializer( final Class refCls, boolean keySer ) + { + super( refCls ); + this.keySer = keySer; + } + + @Override + public void serialize( final T src, final JsonGenerator generator, final SerializerProvider provider ) + throws IOException, JsonGenerationException + { + if ( keySer ) + { + generator.writeFieldName( src.toString() ); + } + else + { + generator.writeString( src.toString() ); + } + } +} diff --git a/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectVersionRefSerializerModule.java b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectVersionRefSerializerModule.java new file mode 100644 index 00000000..9df68d85 --- /dev/null +++ b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/ProjectVersionRefSerializerModule.java @@ -0,0 +1,88 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.jackson; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleVersionlessArtifactRef; +import org.commonjava.atlas.maven.ident.ref.VersionlessArtifactRef; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.module.SimpleModule; + +public class ProjectVersionRefSerializerModule + extends SimpleModule +{ + + private static final long serialVersionUID = 1L; + + private static final Set> REF_CLASSES; + + static + { + REF_CLASSES = Collections.unmodifiableSet( new HashSet>( + Arrays.asList( ProjectRef.class, ProjectVersionRef.class, ArtifactRef.class, + VersionlessArtifactRef.class, SimpleProjectRef.class, SimpleProjectVersionRef.class, + SimpleArtifactRef.class, SimpleVersionlessArtifactRef.class ) ) ); + } + + public static final ProjectVersionRefSerializerModule INSTANCE = new ProjectVersionRefSerializerModule(); + + public ProjectVersionRefSerializerModule() + { + super( "ProjectRef (with variants) Serializer" ); + + for ( Class cls: REF_CLASSES ) + { + register( cls ); + } + } + + private void register( Class cls ) + { + Logger logger = LoggerFactory.getLogger( getClass() ); + logger.debug( "Registering {} serializers/deserialers", cls.getSimpleName() ); + + addSerializer( cls, new ProjectRefSerializer( cls, false ) ); + addKeySerializer( cls, new ProjectRefSerializer( cls, true ) ); + + addDeserializer( cls, new ProjectRefDeserializer( cls ) ); + addKeyDeserializer( cls, new ProjectRefKeyDeserializer( cls ) ); + } + + @Override + public int hashCode() + { + return getClass().getSimpleName().hashCode() + 17; + } + + @Override + public boolean equals( final Object other ) + { + return getClass().equals( other.getClass() ); + } + +} diff --git a/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/SerializerIdentityUtils.java b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/SerializerIdentityUtils.java new file mode 100644 index 00000000..b7242bc6 --- /dev/null +++ b/bindings/jackson-identities/src/main/java/org/commonjava/atlas/maven/ident/jackson/SerializerIdentityUtils.java @@ -0,0 +1,82 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.jackson; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleVersionlessArtifactRef; +import org.commonjava.atlas.maven.ident.ref.VersionlessArtifactRef; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Created by jdcasey on 8/26/15. + */ +public final class SerializerIdentityUtils +{ + private SerializerIdentityUtils(){} + + public static T parse( final String value, final Class type ) + throws IOException + { + Class realType = null; + if ( ArtifactRef.class.isAssignableFrom( type ) ) + { + realType = SimpleArtifactRef.class; + } + else if ( VersionlessArtifactRef.class.isAssignableFrom( type ) ) + { + realType = SimpleVersionlessArtifactRef.class; + } + else if ( ProjectVersionRef.class.isAssignableFrom( type ) ) + { + realType = SimpleProjectVersionRef.class; + } + else if ( ProjectRef.class.isAssignableFrom( type ) ) + { + realType = SimpleProjectRef.class; + } + else + { + throw new IOException( "Cannot find acceptable deserialization target class to parse: " + type.getSimpleName() ); + } + + try + { + final Method parseMethod = realType.getMethod( "parse", String.class ); + return type.cast( parseMethod.invoke( null, value ) ); + } + catch ( final NoSuchMethodException e ) + { + throw new IOException( "Failed to lookup/invoke parse() method on " + type.getSimpleName(), e ); + } + catch ( final IllegalAccessException e ) + { + throw new IOException( "Failed to lookup/invoke parse() method on " + type.getSimpleName(), e ); + } + catch ( final InvocationTargetException e ) + { + throw new IOException( "Failed to lookup/invoke parse() method on " + type.getSimpleName(), e ); + } + } + +} diff --git a/bindings/jackson-identities/src/test/java/org/commonjava/atlas/maven/ident/jackson/ProjectVersionRefSerializerModuleTest.java b/bindings/jackson-identities/src/test/java/org/commonjava/atlas/maven/ident/jackson/ProjectVersionRefSerializerModuleTest.java new file mode 100644 index 00000000..fc29e031 --- /dev/null +++ b/bindings/jackson-identities/src/test/java/org/commonjava/atlas/maven/ident/jackson/ProjectVersionRefSerializerModuleTest.java @@ -0,0 +1,75 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.jackson; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectRef; +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ProjectVersionRefSerializerModuleTest +{ + + private ObjectMapper mapper; + + @Before + public void setup() + { + mapper = new ObjectMapper(); + mapper.registerModule( new ProjectVersionRefSerializerModule() ); + } + + @Test + public void projectRefRoundTrip() + throws Exception + { + final ProjectRef pr = new SimpleProjectRef( "org.foo", "bar" ); + final String json = mapper.writeValueAsString( pr ); + + final ProjectRef result = mapper.readValue( json, ProjectRef.class ); + + assertThat( result, equalTo( pr ) ); + } + + @Test + public void mapWithProjectRefKeyRoundTrip() + throws Exception + { + final ProjectRef pr = new SimpleProjectRef( "org.foo", "bar" ); + final String value = "this is the value"; + + final Map map = new HashMap(); + map.put( pr, value ); + + final String json = mapper.writeValueAsString( map ); + + final Map result = mapper.readValue( json, new TypeReference>() + { + } ); + + assertThat( result.get( pr ), equalTo( value ) ); + } + +} diff --git a/bindings/pom.xml b/bindings/pom.xml new file mode 100644 index 00000000..0b0cecbd --- /dev/null +++ b/bindings/pom.xml @@ -0,0 +1,43 @@ + + + + 4.0.0 + + + org.commonjava.atlas + atlas-parent + 1.2.3-SNAPSHOT + + + atlas-bindings-parent + pom + + Atlas :: Maven Project-Graph :: Bindings Parent + + + + org.commonjava.atlas + atlas-identities + + + + + jackson-identities + + diff --git a/build-order-improvements.txt b/build-order-improvements.txt index 4220f454..84237d90 100644 --- a/build-order-improvements.txt +++ b/build-order-improvements.txt @@ -1,3 +1,19 @@ +==== + Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==== + #------------------------------------------------------------------------------- # Copyright (c) 2014 Red Hat, Inc.. # All rights reserved. This program and the accompanying materials diff --git a/codestyle.xml b/codestyle.xml new file mode 100644 index 00000000..ee94adcf --- /dev/null +++ b/codestyle.xml @@ -0,0 +1,308 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/drivers/jung/pom.xml b/drivers/jung/pom.xml deleted file mode 100644 index 318fe24a..00000000 --- a/drivers/jung/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - 4.0.0 - - - org.commonjava.maven.atlas - atlas-drivers-parent - 0.12.0-EXP-SNAPSHOT - - - atlas-driver-jung - - Atlas :: Maven Project-Graph :: Jung Driver - - - - net.sf.jung - jung-graph-impl - - - - diff --git a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/CycleDetectionTraversal.java b/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/CycleDetectionTraversal.java deleted file mode 100644 index d4ecf671..00000000 --- a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/CycleDetectionTraversal.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import static org.apache.commons.lang.StringUtils.join; - -import java.util.ArrayList; -import java.util.List; - -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.traverse.AbstractTraversal; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -final class CycleDetectionTraversal - extends AbstractTraversal -{ - private final List cycles = new ArrayList(); - - private final ProjectRelationship rel; - - CycleDetectionTraversal( final ProjectRelationship rel ) - { - this.rel = rel; - } - - public List getCycles() - { - return cycles; - } - - @Override - public boolean preCheck( final ProjectRelationship relationship, final List> path ) - { - if ( rel.getDeclaring() - .equals( rel.getTarget() - .asProjectVersionRef() ) ) - { - return false; - } - - final Logger logger = LoggerFactory.getLogger( getClass() ); - - logger.debug( "Checking for cycle: {}\n\nPath: {}\n\n", relationship, new JoinString( "\n", path ) ); - - final ProjectVersionRef from = rel.getDeclaring(); - if ( from.equals( relationship.getTarget() - .asProjectVersionRef() ) ) - { - final List> cycle = new ArrayList>( path ); - cycle.add( rel ); - - cycles.add( new EProjectCycle( cycle ) ); - - logger.warn( "CYCLE: {}", join( cycle, ", " ) ); - return false; - } - - return true; - } -} diff --git a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/JungGraphConnection.java b/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/JungGraphConnection.java deleted file mode 100644 index b36c5f28..00000000 --- a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/JungGraphConnection.java +++ /dev/null @@ -1,1201 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.POM_ROOT_URI; -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.UNKNOWN_SOURCE_URI; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.AnyFilter; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipComparator; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.spi.jung.model.JungGraphPath; -import org.commonjava.maven.atlas.graph.traverse.RelationshipGraphTraversal; -import org.commonjava.maven.atlas.graph.traverse.TraversalType; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import edu.uci.ics.jung.graph.DirectedGraph; -import edu.uci.ics.jung.graph.DirectedSparseMultigraph; - -public class JungGraphConnection - implements RelationshipGraphConnection -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private DirectedGraph> graph = - new DirectedSparseMultigraph>(); - - private final Map> byGA = new HashMap>(); - - private transient Set incompleteSubgraphs = new HashSet(); - - private transient Set variableSubgraphs = new HashSet(); - - private final Map> metadataOwners = new HashMap>(); - - private final Map> metadata = - new HashMap>(); - - private final Set cycles = new HashSet(); - - private final Map errors = new HashMap(); - - private final String workspaceId; - - public JungGraphConnection( final String workspaceId ) - { - this.workspaceId = workspaceId; - } - - @Override - public Collection> getRelationshipsDeclaredBy( final ViewParams params, - final ProjectVersionRef ref ) - { - return imposeSelections( params, graph.getOutEdges( ref.asProjectVersionRef() ) ); - } - - @Override - public Collection> getRelationshipsTargeting( final ViewParams params, - final ProjectVersionRef ref ) - { - return imposeSelections( params, graph.getInEdges( ref.asProjectVersionRef() ) ); - } - - @Override - public Collection> getAllRelationships( final ViewParams params ) - { - return imposeSelections( params, graph.getEdges() ); - } - - private Collection> imposeSelections( final ViewParams params, - final Collection> edges ) - { - if ( edges == null || edges.isEmpty() ) - { - return edges; - } - - final List> result = new ArrayList>( edges.size() ); - for ( final ProjectRelationship edge : edges ) - { - if ( ( edge instanceof ParentRelationship ) && ( (ParentRelationship) edge ).isTerminus() ) - { - continue; - } - - final ProjectVersionRef target = edge.getTarget() - .asProjectVersionRef(); - - final Set sources = params.getActiveSources(); - if ( sources != null && !sources.isEmpty() ) - { - if ( !sources.contains( RelationshipUtils.ANY_SOURCE_URI ) ) - { - Set s = edge.getSources(); - if ( s == null ) - { - s = Collections.singleton( UNKNOWN_SOURCE_URI ); - } - - boolean found = false; - for ( final URI uri : s ) - { - // TODO: What were the default sources?? - if ( /*sources == ViewParams.DEFAULT_SOURCES ||*/sources.contains( uri ) ) - { - found = true; - break; - } - } - - if ( !found ) - { - // log( "Found relationship in path with de-selected source-repository URI: %s", edge ); - continue; - } - } - } - - final Set pomLocations = params.getActivePomLocations(); - if ( pomLocations != null && !pomLocations.isEmpty() ) - { - URI pomLocation = edge.getPomLocation(); - if ( pomLocation == null ) - { - pomLocation = POM_ROOT_URI; - } - if ( !pomLocations.contains( pomLocation ) ) - { - // log( "Found relationship in path with de-selected pom-location URI: %s", edge ); - continue; - } - } - - final ProjectVersionRef selected = params == null ? null : params.getSelection( target ); - if ( selected != null ) - { - result.add( edge.selectTarget( selected ) ); - } - else - { - result.add( edge ); - } - } - - return result; - } - - @Override - public Set> addRelationships( final ProjectRelationship... rels ) - { - final Set> skipped = new HashSet>(); - for ( final ProjectRelationship rel : rels ) - { - if ( !graph.containsVertex( rel.getDeclaring() ) ) - { - // // logger.info( "Adding node: %s", rel.getDeclaring() ); - graph.addVertex( rel.getDeclaring() ); - addGA( rel.getDeclaring() ); - } - - final ProjectVersionRef target = rel.getTarget() - .asProjectVersionRef(); - if ( !target.getVersionSpec() - .isSingle() ) - { - // logger.info( "Adding variable target: %s", target ); - variableSubgraphs.add( target ); - } - else if ( !graph.containsVertex( target ) ) - { - // logger.info( "Adding incomplete target: %s", target ); - incompleteSubgraphs.add( target ); - } - - if ( !graph.containsVertex( target ) ) - { - // logger.info( "Adding node: %s", target ); - graph.addVertex( target.asProjectVersionRef() ); - addGA( target ); - } - - final List> edges = - new ArrayList>( graph.findEdgeSet( rel.getDeclaring(), target ) ); - if ( !edges.contains( rel ) ) - { - // logger.info( "Adding edge: %s -> %s", rel.getDeclaring(), target ); - graph.addEdge( rel, rel.getDeclaring(), target.asProjectVersionRef() ); - } - else - { - final int idx = edges.indexOf( rel ); - final ProjectRelationship existing = edges.get( idx ); - - // logger.info( "Adding sources: %s to existing edge: %s", rel.getSources(), existing ); - - existing.addSources( rel.getSources() ); - } - - // logger.info( "removing from incomplete status: %s", rel.getDeclaring() ); - incompleteSubgraphs.remove( rel.getDeclaring() ); - } - - for ( final ProjectRelationship rel : rels ) - { - if ( skipped.contains( rel ) ) - { - continue; - } - - // logger.info( "Detecting cycles introduced by: %s", rel ); - - final CycleDetectionTraversal traversal = new CycleDetectionTraversal( rel ); - - dfsTraverse( new ViewParams.Builder( workspaceId ).withActiveSources( Collections.singleton( RelationshipUtils.ANY_SOURCE_URI ) ) - .build(), traversal, rel.getTarget() - .asProjectVersionRef() ); - - final List cycles = traversal.getCycles(); - - if ( !cycles.isEmpty() ) - { - // logger.info( "CYCLE introduced by: %s", rel ); - skipped.add( rel ); - - graph.removeEdge( rel ); - this.cycles.addAll( cycles ); - } - } - - return skipped; - } - - private boolean addGA( final ProjectVersionRef ref ) - { - final ProjectRef pr = ref.asProjectRef(); - Set refs = byGA.get( pr ); - if ( refs == null ) - { - refs = new HashSet(); - byGA.put( pr, refs ); - } - - return refs.add( ref ); - } - - @Override - public Set>> getAllPathsTo( final ViewParams params, final ProjectVersionRef... refs ) - { - final PathDetectionTraversal traversal = new PathDetectionTraversal( this, params, refs ); - - final Set roots = params.getRoots(); - if ( roots == null ) - { - LoggerFactory.getLogger( getClass() ) - .warn( "Cannot retrieve paths targeting {}. No roots specified for this project network!", - new JoinString( ", ", refs ) ); - return null; - } - - for ( final ProjectVersionRef root : roots ) - { - dfsTraverse( params, traversal, root ); - } - - final Set paths = traversal.getPaths(); - final Set>> result = new HashSet>>( paths.size() ); - for ( final JungGraphPath path : paths ) - { - result.add( path.getPathElements() ); - } - - return result; - } - - @Override - public boolean introducesCycle( final ViewParams params, final ProjectRelationship rel ) - { - final CycleDetectionTraversal traversal = new CycleDetectionTraversal( rel ); - - dfsTraverse( params, traversal, rel.getTarget() - .asProjectVersionRef() ); - - return !traversal.getCycles() - .isEmpty(); - } - - @Override - public Set getAllProjects( final ViewParams params ) - { - return new HashSet( graph.getVertices() ); - } - - @Override - public void traverse( final RelationshipGraphTraversal traversal, final ProjectVersionRef root, - final RelationshipGraph graph, final TraversalType type ) - throws RelationshipGraphConnectionException - { - traversal.startTraverse( graph ); - - switch ( type ) - { - case breadth_first: - { - bfsTraverse( graph.getParams(), traversal, root ); - break; - } - case depth_first: - { - dfsTraverse( graph.getParams(), traversal, root ); - break; - } - } - - traversal.endTraverse( graph ); - } - - // TODO: Implement without recursion. - private void dfsTraverse( final ViewParams params, final RelationshipGraphTraversal traversal, - final ProjectVersionRef root ) - { - dfsIterate( params, root, traversal, new JungGraphPath( root ), new GraphPathInfo( this, params ) ); - } - - private void dfsIterate( final ViewParams params, final ProjectVersionRef node, - final RelationshipGraphTraversal traversal, final JungGraphPath path, - final GraphPathInfo pathInfo ) - { - final List> edges = getSortedOutEdges( params, node ); - if ( edges != null ) - { - for ( final ProjectRelationship edge : edges ) - { - final ProjectRelationship realEdge = pathInfo.selectRelationship( edge, path ); - if ( realEdge == null ) - { - continue; - } - - final JungGraphPath next = new JungGraphPath( path, realEdge ); - final List> pathElements = next.getPathElements(); - - if ( traversal.traverseEdge( realEdge, pathElements ) ) - { - final GraphPathInfo nextInfo = pathInfo.getChildPathInfo( realEdge ); - if ( !( edge instanceof ParentRelationship ) || !( (ParentRelationship) edge ).isTerminus() ) - { - if ( next.hasCycle() ) - { - continue; - } - - final ProjectVersionRef target = edge.getTarget() - .asProjectVersionRef(); - - dfsIterate( params, target, traversal, next, nextInfo ); - } - - traversal.edgeTraversed( realEdge, pathElements ); - } - } - } - } - - // TODO: Implement without recursion. - private void bfsTraverse( final ViewParams params, final RelationshipGraphTraversal traversal, - final ProjectVersionRef root ) - { - final GraphPathInfo pathInfo = new GraphPathInfo( this, params ); - - bfsIterate( params, Collections.singletonMap( new JungGraphPath( root ), pathInfo ), traversal ); - } - - private void bfsIterate( final ViewParams params, final Map thisLayer, - final RelationshipGraphTraversal traversal ) - { - final Map nextLayer = new LinkedHashMap(); - - for ( final Entry entry : thisLayer.entrySet() ) - { - final JungGraphPath path = entry.getKey(); - final GraphPathInfo pathInfo = entry.getValue(); - - final ProjectVersionRef node = path.getTargetGAV(); - if ( node == null ) - { - continue; - } - - final List> edges = getSortedOutEdges( params, node ); - if ( edges != null ) - { - for ( final ProjectRelationship edge : edges ) - { - final ProjectRelationship realEdge = pathInfo.selectRelationship( edge, path ); - if ( realEdge == null ) - { - continue; - } - - final List> pathElements = path.getPathElements(); - // call traverseEdge no matter what, to allow traversal to "see" all relationships. - if ( traversal.traverseEdge( realEdge, pathElements ) ) - { - final JungGraphPath next = new JungGraphPath( path, realEdge ); - final GraphPathInfo nextInfo = pathInfo.getChildPathInfo( realEdge ); - - // Don't account for terminal parent relationship. - if ( !( realEdge instanceof ParentRelationship ) - || !( (ParentRelationship) realEdge ).isTerminus() ) - { - if ( next.hasCycle() ) - { - continue; - } - - nextLayer.put( next, nextInfo ); - } - - traversal.edgeTraversed( realEdge, pathElements ); - } - } - } - } - - if ( !nextLayer.isEmpty() ) - { - bfsIterate( params, nextLayer, traversal ); - } - } - - private List> getSortedOutEdges( final ViewParams params, final ProjectVersionRef node ) - { - Collection> unsorted = graph.getOutEdges( node.asProjectVersionRef() ); - if ( unsorted == null ) - { - return null; - } - - unsorted = new ArrayList>( unsorted ); - - RelationshipUtils.filterTerminalParents( unsorted ); - - final List> sorted = - new ArrayList>( imposeSelections( params, unsorted ) ); - Collections.sort( sorted, RelationshipComparator.INSTANCE ); - - return sorted; - } - - // @Override - // public EGraphDriver newInstanceFrom( final EProjectNet net, final ProjectRelationshipFilter filter, - // final ProjectVersionRef... from ) - // throws GraphDriverException - // { - // final JungEGraphDriver neo = new JungEGraphDriver( this, filter, net, null, from ); - // neo.restrictProjectMembership( Arrays.asList( from ) ); - // - // return neo; - // } - // - // @Override - // public EGraphDriver newInstance( final EGraphSession workspace, final EProjectNet net, - // final ProjectRelationshipFilter filter, final ProjectVersionRef... from ) - // throws GraphDriverException - // { - // final JungEGraphDriver neo = new JungEGraphDriver( this, filter, net, null, from ); - // neo.restrictProjectMembership( Arrays.asList( from ) ); - // - // return neo; - // } - - @Override - public boolean containsProject( final ViewParams params, final ProjectVersionRef ref ) - { - return graph.containsVertex( ref.asProjectVersionRef() ) - && !incompleteSubgraphs.contains( ref.asProjectVersionRef() ); - } - - @Override - public boolean containsRelationship( final ViewParams params, final ProjectRelationship rel ) - { - return graph.containsEdge( rel ); - } - - public void restrictProjectMembership( final Collection refs ) - { - final Set> rels = new HashSet>(); - for ( final ProjectVersionRef ref : refs ) - { - final Collection> edges = graph.getOutEdges( ref.asProjectVersionRef() ); - if ( edges != null ) - { - rels.addAll( edges ); - } - } - - restrictRelationshipMembership( rels ); - } - - public void restrictRelationshipMembership( final Collection> rels ) - { - graph = new DirectedSparseMultigraph>(); - incompleteSubgraphs.clear(); - variableSubgraphs.clear(); - - addRelationships( rels.toArray( new ProjectRelationship[] {} ) ); - - recomputeIncompleteSubgraphs(); - } - - @Override - public void close() - { - // NOP; stored in memory. - } - - // @Override - // public boolean isDerivedFrom( final EGraphDriver driver ) - // { - // return false; - // } - - @Override - public boolean isMissing( final ViewParams params, final ProjectVersionRef project ) - { - return !graph.containsVertex( project.asProjectVersionRef() ); - } - - @Override - public boolean hasMissingProjects( final ViewParams params ) - { - return !incompleteSubgraphs.isEmpty(); - } - - @Override - public Set getMissingProjects( final ViewParams params ) - { - final Set result = new HashSet( incompleteSubgraphs ); - // logger.info( "Got %d missing projects: %s", result.size(), result ); - return result; - } - - @Override - public boolean hasVariableProjects( final ViewParams params ) - { - return !variableSubgraphs.isEmpty(); - } - - @Override - public Set getVariableProjects( final ViewParams params ) - { - return new HashSet( variableSubgraphs ); - } - - @Override - public boolean addCycle( final EProjectCycle cycle ) - { - boolean changed = false; - synchronized ( this.cycles ) - { - changed = this.cycles.add( cycle ); - } - - for ( final ProjectRelationship rel : cycle ) - { - incompleteSubgraphs.remove( rel.getDeclaring() ); - } - - return changed; - } - - // TODO: May not work with paths to the entries in the cycle...since filters are often path-sensitive - @Override - public Set getCycles( final ViewParams params ) - { - final Set result = new HashSet(); - if ( params.getFilter() == null || params.getFilter() - .equals( AnyFilter.INSTANCE ) ) - { - result.addAll( cycles ); - } - else - { - final ProjectRelationshipFilter filter = params.getFilter(); - nextCycle: for ( final EProjectCycle cycle : cycles ) - { - for ( final ProjectRelationship r : cycle ) - { - if ( !filter.accept( r ) ) - { - continue nextCycle; - } - } - - result.add( cycle ); - } - } - - return result; - } - - @Override - public boolean isCycleParticipant( final ViewParams params, final ProjectRelationship rel ) - { - for ( final EProjectCycle cycle : cycles ) - { - if ( cycle.contains( rel ) ) - { - return true; - } - } - - return false; - } - - @Override - public boolean isCycleParticipant( final ViewParams params, final ProjectVersionRef ref ) - { - for ( final EProjectCycle cycle : cycles ) - { - if ( cycle.contains( ref.asProjectVersionRef() ) ) - { - return true; - } - } - - return false; - } - - @Override - public void recomputeIncompleteSubgraphs() - { - final ViewParams params = - new ViewParams.Builder( workspaceId ).withActiveSources( Collections.singleton( RelationshipUtils.ANY_SOURCE_URI ) ) - .build(); - - for ( final ProjectVersionRef vertex : getAllProjects( params ) ) - { - final Collection> outEdges = getRelationshipsDeclaredBy( params, vertex ); - if ( outEdges != null && !outEdges.isEmpty() ) - { - incompleteSubgraphs.remove( vertex ); - } - } - } - - @Override - public Map getMetadata( final ProjectVersionRef ref ) - { - return getMetadata( ref, null ); - } - - @Override - public Map getMetadata( final ProjectVersionRef ref, final Set keys ) - { - Map metadata; - synchronized ( this ) - { - metadata = this.metadata.get( ref.asProjectVersionRef() ); - if ( metadata == null ) - { - metadata = new HashMap(); - this.metadata.put( ref.asProjectVersionRef(), metadata ); - } - } - - if ( keys != null && !keys.isEmpty() ) - { - metadata = new HashMap( metadata ); - final Set removable = new HashSet( metadata.keySet() ); - removable.removeAll( keys ); - - for ( final String remove : removable ) - { - metadata.remove( remove ); - } - } - - return metadata; - } - - @Override - public void addMetadata( final ProjectVersionRef ref, final String key, final String value ) - { - if ( StringUtils.isEmpty( key ) || StringUtils.isEmpty( value ) ) - { - return; - } - - final Map md = getMetadata( ref.asProjectVersionRef() ); - md.put( key, value ); - - addMetadataOwner( key, ref.asProjectVersionRef() ); - } - - private synchronized void addMetadataOwner( final String key, final ProjectVersionRef ref ) - { - Set owners = this.metadataOwners.get( key ); - if ( owners == null ) - { - owners = new HashSet(); - metadataOwners.put( key, owners ); - } - - owners.add( ref.asProjectVersionRef() ); - } - - @Override - public void setMetadata( final ProjectVersionRef ref, final Map metadata ) - { - if ( metadata == null || metadata.isEmpty() ) - { - return; - } - - final Map md = getMetadata( ref.asProjectVersionRef() ); - md.putAll( metadata ); - } - - @Override - public synchronized void reindex() - throws RelationshipGraphConnectionException - { - for ( final Map.Entry> refEntry : metadata.entrySet() ) - { - for ( final Map.Entry mdEntry : refEntry.getValue() - .entrySet() ) - { - addMetadataOwner( mdEntry.getKey(), refEntry.getKey() - .asProjectVersionRef() ); - } - } - } - - @Override - public synchronized void reindex( final ProjectVersionRef ref ) - { - if ( ref == null ) - { - return; - } - - final Map map = metadata.get( ref ); - if ( map != null ) - { - for ( final Map.Entry mdEntry : map.entrySet() ) - { - addMetadataOwner( mdEntry.getKey(), ref ); - } - } - } - - @Override - public Set getProjectsWithMetadata( final ViewParams params, final String key ) - { - return metadataOwners.get( key ); - } - - // public void selectVersionFor( final ProjectVersionRef variable, final ProjectVersionRef select ) - // throws GraphDriverException - // { - // if ( !select.isSpecificVersion() ) - // { - // throw new GraphDriverException( "Cannot select non-concrete version! Attempted to select: %s", select ); - // } - // - // if ( variable.isSpecificVersion() ) - // { - // throw new GraphDriverException( - // "Cannot select version if target is already a concrete version! Attempted to select for: %s", - // variable ); - // } - // - // selected.put( variable, select ); - // - // // Don't worry about selecting for outbound edges, as those subgraphs are supposed to be the same... - // final Collection> rels = graph.getInEdges( variable ); - // for ( final ProjectRelationship rel : rels ) - // { - // - // ProjectRelationship repl; - // if ( rel.getTarget() - // .asProjectVersionRef() - // .equals( variable ) ) - // { - // repl = rel.selectTarget( (SingleVersion) select.getVersionSpec() ); - // } - // else - // { - // continue; - // } - // - // graph.removeEdge( rel ); - // graph.addEdge( repl, repl.getDeclaring(), repl.getTarget() - // .asProjectVersionRef() ); - // - // replaced.put( rel, repl ); - // } - // } - // - // public Map clearSelectedVersions() - // { - // final Map selected = - // new HashMap( this.selected ); - // - // selected.clear(); - // - // for ( final Map.Entry, ProjectRelationship> entry : replaced.entrySet() ) - // { - // final ProjectRelationship rel = entry.getKey(); - // final ProjectRelationship repl = entry.getValue(); - // - // graph.removeEdge( repl ); - // graph.addEdge( rel, rel.getDeclaring(), rel.getTarget() - // .asProjectVersionRef() ); - // } - // - // for ( final ProjectVersionRef select : new HashSet( selected.values() ) ) - // { - // final Collection> edges = graph.getInEdges( select ); - // if ( edges.isEmpty() ) - // { - // graph.removeVertex( select ); - // } - // } - // - // return selected; - // } - // - // public Map getSelectedVersions() - // { - // return selected; - // } - - @Override - public void addDisconnectedProject( final ProjectVersionRef ref ) - { - if ( !graph.containsVertex( ref.asProjectVersionRef() ) ) - { - graph.addVertex( ref.asProjectVersionRef() ); - } - } - - /** - * @deprecated Use {@link #getDirectRelationshipsFrom(GraphView,ProjectVersionRef,boolean,boolean,RelationshipType...)} instead - */ - @Deprecated - @Override - public Set> getDirectRelationshipsFrom( final ViewParams params, - final ProjectVersionRef from, - final boolean includeManagedInfo, - final RelationshipType... types ) - { - return getDirectRelationshipsFrom( params, from, includeManagedInfo, true, types ); - } - - @Override - public Set> getDirectRelationshipsFrom( final ViewParams params, - final ProjectVersionRef from, - final boolean includeManagedInfo, - final boolean includeConcreteInfo, - final RelationshipType... types ) - { - return getMatchingRelationships( graph.getOutEdges( from.asProjectVersionRef() ), params, includeManagedInfo, - includeConcreteInfo, types ); - } - - private Set> getMatchingRelationships( final Collection> edges, - final ViewParams params, - final boolean includeManagedInfo, - final boolean includeConcreteInfo, - final RelationshipType... types ) - { - if ( edges == null ) - { - // logger.info( "No edges found. Nothing to filter!" ); - return null; - } - - // logger.info( "Filtering %d edges...", edges.size() ); - final Set> rels = new HashSet>( edges.size() ); - - final List typeList = Arrays.asList( types ); - Collections.sort( typeList ); - - for ( final ProjectRelationship rel : edges ) - { - if ( !typeList.isEmpty() && !typeList.contains( rel.getType() ) ) - { - // logger.info( "-= %s (wrong type)", rel ); - continue; - } - - if ( params.getFilter() != null && !params.getFilter() - .accept( rel ) ) - { - // logger.info( "-= %s (rejected by filter)", rel ); - continue; - } - - if ( !includeManagedInfo && rel.isManaged() ) - { - // logger.info( "-= %s (wrong managed status)", rel ); - continue; - } - - if ( !includeConcreteInfo && !rel.isManaged() ) - { - // logger.info( "-= %s (wrong managed status)", rel ); - continue; - } - - // logger.info( "+= %s", rel ); - rels.add( rel ); - } - - return rels; - } - - /** - * @deprecated Use {@link #getDirectRelationshipsTo(GraphView,ProjectVersionRef,boolean,boolean,RelationshipType...)} instead - */ - @Deprecated - @Override - public Set> getDirectRelationshipsTo( final ViewParams params, final ProjectVersionRef to, - final boolean includeManagedInfo, - final RelationshipType... types ) - { - return getDirectRelationshipsTo( params, to, includeManagedInfo, true, types ); - } - - @Override - public Set> getDirectRelationshipsTo( final ViewParams params, final ProjectVersionRef to, - final boolean includeManagedInfo, - final boolean includeConcreteInfo, - final RelationshipType... types ) - { - // logger.info( "Getting relationships targeting: %s (types: %s)", to, join( types, ", " ) ); - return getMatchingRelationships( graph.getInEdges( to.asProjectVersionRef() ), params, includeManagedInfo, - includeConcreteInfo, types ); - } - - @Override - public Set getProjectsMatching( final ViewParams params, final ProjectRef projectRef ) - { - return byGA.containsKey( projectRef.asProjectRef() ) ? byGA.get( projectRef.asProjectRef() ) - : Collections. emptySet(); - } - - @Override - public void deleteRelationshipsDeclaredBy( final ProjectVersionRef ref ) - throws RelationshipGraphConnectionException - { - final Collection> edges = graph.getOutEdges( ref.asProjectVersionRef() ); - if ( edges != null ) - { - for ( final ProjectRelationship rel : edges ) - { - graph.removeEdge( rel ); - } - } - - incompleteSubgraphs.add( ref ); - } - - @Override - public void printStats() - { - logger.info( "Graph contains {} nodes.", graph.getVertexCount() ); - logger.info( "Graph contains {} relationships.", graph.getEdgeCount() ); - } - - @Override - public ProjectVersionRef getManagedTargetFor( final ProjectVersionRef target, final GraphPath path, - final RelationshipType type ) - { - if ( path == null ) - { - return null; - } - - if ( !( path instanceof JungGraphPath ) ) - { - throw new IllegalArgumentException( - "Cannot process GraphPath's from other implementations. (Non-Jung GraphPath detected: " - + path + ")" ); - } - - final ProjectRef targetGA = target.asProjectRef(); - - final JungGraphPath jungpath = (JungGraphPath) path; - for ( final ProjectRelationship ref : jungpath ) - { - final Collection> outEdges = graph.getOutEdges( ref.getDeclaring() ); - for ( final ProjectRelationship edge : outEdges ) - { - if ( edge.isManaged() && type == edge.getType() && targetGA.equals( edge.getTarget() ) ) - { - return edge.getTarget() - .asProjectVersionRef(); - } - } - } - - return null; - } - - @Override - public GraphPath createPath( final ProjectRelationship... rels ) - { - if ( rels.length > 0 ) - { - try - { - rels[rels.length - 1].getTarget() - .getVersionSpec(); - } - catch ( final InvalidVersionSpecificationException e ) - { - return null; - } - } - - return new JungGraphPath( rels ); - } - - @Override - public GraphPath createPath( final GraphPath parent, final ProjectRelationship child ) - { - try - { - child.getTarget() - .getVersionSpec(); - } - catch ( final InvalidVersionSpecificationException e ) - { - return null; - } - - if ( parent != null && !( parent instanceof JungGraphPath ) ) - { - throw new IllegalArgumentException( "Cannot get child path for: " + parent - + ". This is not a JungGraphPath instance!" ); - } - - return new JungGraphPath( (JungGraphPath) parent, child ); - } - - @Override - public boolean registerView( final ViewParams params ) - { - // TODO Tracking for the new params... - return false; - } - - @Override - public void registerViewSelection( final ViewParams params, final ProjectRef ref, - final ProjectVersionRef projectVersionRef ) - { - // NOP - } - - @Override - public Map, GraphPathInfo> getPathMapTargeting( final ViewParams params, - final Set refs ) - { - final PathDetectionTraversal traversal = new PathDetectionTraversal( this, params, refs ); - - final Set roots = params.getRoots(); - if ( roots == null ) - { - LoggerFactory.getLogger( getClass() ) - .warn( "Cannot retrieve paths targeting {}. No roots specified for this project network!", - new JoinString( ", ", refs ) ); - return null; - } - - for ( final ProjectVersionRef root : roots ) - { - dfsTraverse( params, traversal, root ); - } - - final Map allPathsMap = traversal.getPathMap(); - final Set paths = traversal.getPaths(); - - final Map, GraphPathInfo> result = new HashMap, GraphPathInfo>(); - for ( final JungGraphPath path : paths ) - { - result.put( path, allPathsMap.get( path ) ); - } - - return result; - } - - @Override - public ProjectVersionRef getPathTargetRef( final GraphPath path ) - { - if ( path != null && !( path instanceof JungGraphPath ) ) - { - throw new IllegalArgumentException( "Cannot get target GAV for: " + path - + ". This is not a JungGraphPath instance!" ); - } - - return ( (JungGraphPath) path ).getTargetGAV(); - } - - @Override - public List getPathRefs( final ViewParams params, final GraphPath path ) - { - if ( path != null && !( path instanceof JungGraphPath ) ) - { - throw new IllegalArgumentException( "Cannot get target GAV for: " + path - + ". This is not a JungGraphPath instance!" ); - } - - final JungGraphPath gp = (JungGraphPath) path; - final List refs = new ArrayList(); - for ( final ProjectRelationship rel : gp ) - { - if ( refs.isEmpty() ) - { - refs.add( rel.getDeclaring() ); - } - - refs.add( rel.getTarget() - .asProjectVersionRef() ); - } - - return refs; - } - - @Override - public String getWorkspaceId() - { - return workspaceId; - } - - @Override - public void addProjectError( final ProjectVersionRef ref, final Throwable error ) - throws RelationshipGraphConnectionException - { - errors.put( ref, error ); - } - - @Override - public Throwable getProjectError( final ProjectVersionRef ref ) - { - return errors.get( ref ); - } - - @Override - public boolean hasProjectError( final ProjectVersionRef ref ) - { - return errors.containsKey( ref ); - } - - @Override - public void clearProjectError( final ProjectVersionRef ref ) - throws RelationshipGraphConnectionException - { - errors.remove( ref ); - } - -} diff --git a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/JungGraphConnectionFactory.java b/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/JungGraphConnectionFactory.java deleted file mode 100644 index 885f08a2..00000000 --- a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/JungGraphConnectionFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.commonjava.maven.atlas.graph.spi.jung; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; - -public class JungGraphConnectionFactory - implements RelationshipGraphConnectionFactory -{ - - private final Map connections = new HashMap(); - - @Override - public RelationshipGraphConnection openConnection( final String workspaceId, final boolean create ) - throws RelationshipGraphConnectionException - { - JungGraphConnection connection = connections.get( workspaceId ); - if ( connection == null && create ) - { - connection = new JungGraphConnection( workspaceId ); - connections.put( workspaceId, connection ); - } - - return connection; - } - - @Override - public Set listWorkspaces() - { - return connections.keySet(); - } - - @Override - public void flush( final RelationshipGraphConnection connection ) - throws RelationshipGraphConnectionException - { - } - - @Override - public boolean delete( final String workspaceId ) - throws RelationshipGraphConnectionException - { - return connections.remove( workspaceId ) != null; - } - - @Override - public void close() - throws RelationshipGraphConnectionException - { - } - - @Override - public boolean exists( final String workspaceId ) - { - return connections.containsKey( workspaceId ); - } - -} diff --git a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/PathDetectionTraversal.java b/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/PathDetectionTraversal.java deleted file mode 100644 index fae9c23e..00000000 --- a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/PathDetectionTraversal.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.jung.model.JungGraphPath; -import org.commonjava.maven.atlas.graph.traverse.AbstractTraversal; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -final class PathDetectionTraversal - extends AbstractTraversal -{ - // private final Logger logger = new Logger( getClass() ); - - private final Set to; - - private final Map pathMap = new HashMap(); - - private final Set paths = new HashSet(); - - private final ViewParams params; - - private final RelationshipGraphConnection connection; - - PathDetectionTraversal( final RelationshipGraphConnection connection, final ViewParams params, - final ProjectVersionRef[] refs ) - { - this.connection = connection; - this.params = params; - this.to = new HashSet( Arrays.asList( refs ) ); - } - - public PathDetectionTraversal( final RelationshipGraphConnection connection, final ViewParams params, - final Set refs ) - { - this.connection = connection; - this.params = params; - this.to = refs; - } - - public Map getPathMap() - { - return pathMap; - } - - public Set getPaths() - { - return paths; - } - - @Override - public boolean preCheck( final ProjectRelationship relationship, final List> path ) - { - JungGraphPath jpath; - GraphPathInfo pathInfo; - if ( path.isEmpty() ) - { - jpath = new JungGraphPath( relationship.getDeclaring() ); - pathInfo = new GraphPathInfo( connection, params ); - } - else - { - jpath = new JungGraphPath( path ); - pathInfo = pathMap.get( jpath ); - } - - if ( pathInfo == null ) - { - return false; - } - - final ProjectRelationship selected = pathInfo.selectRelationship( relationship, jpath ); - if ( selected == null ) - { - return false; - } - - jpath = new JungGraphPath( jpath, selected ); - pathInfo = pathInfo.getChildPathInfo( relationship ); - - pathMap.put( jpath, pathInfo ); - - final ProjectVersionRef target = selected.getTarget() - .asProjectVersionRef(); - - // logger.info( "Checking path: %s to see if target: %s is in endpoints: %s", join( path, "," ), target, join( to, ", " ) ); - boolean found = false; - for ( final ProjectVersionRef t : to ) - { - if ( t.equals( target ) ) - { - paths.add( jpath ); - // logger.info( "+= %s", join( path, ", " ) ); - found = true; - } - } - - return !found; - } -} diff --git a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/model/JungGraphPath.java b/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/model/JungGraphPath.java deleted file mode 100644 index fd954139..00000000 --- a/drivers/jung/src/main/java/org/commonjava/maven/atlas/graph/spi/jung/model/JungGraphPath.java +++ /dev/null @@ -1,174 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung.model; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang.StringUtils; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class JungGraphPath - implements GraphPath> -{ - - private final ProjectRelationship[] rels; - - private final ProjectVersionRef root; - - public JungGraphPath( final ProjectVersionRef root ) - { - this.root = root; - this.rels = new ProjectRelationship[] {}; - } - - public JungGraphPath( final ProjectRelationship... rels ) - { - this.root = null; - this.rels = rels; - } - - public JungGraphPath( final JungGraphPath parent, final ProjectRelationship child ) - { - this.root = null; - if ( parent == null ) - { - rels = new ProjectRelationship[] { child }; - } - else - { - final int parentLen = parent.rels.length; - this.rels = new ProjectRelationship[parentLen + 1]; - System.arraycopy( parent.rels, 0, this.rels, 0, parentLen ); - this.rels[parentLen] = child; - } - } - - public JungGraphPath( final List> path ) - { - this.root = null; - this.rels = path.toArray( new ProjectRelationship[path.size()] ); - } - - public ProjectVersionRef getTargetGAV() - { - if ( root != null ) - { - return root; - } - else if ( rels.length > 0 ) - { - return rels[rels.length - 1].getTarget() - .asProjectVersionRef(); - } - - return null; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode( rels ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final JungGraphPath other = (JungGraphPath) obj; - if ( !Arrays.equals( rels, other.rels ) ) - { - return false; - } - return true; - } - - @Override - public Iterator> iterator() - { - return new Iterator>() - { - private int next = 0; - - @Override - public boolean hasNext() - { - return rels.length > next; - } - - @Override - public ProjectRelationship next() - { - return rels[next++]; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException( "Immutable array of GAV's. Remove not supported." ); - } - }; - } - - public List> getPathElements() - { - return rels.length == 0 ? Collections.> emptyList() : Arrays.asList( rels ); - } - - public boolean hasCycle() - { - if ( rels.length < 1 ) - { - return false; - } - - final Set declared = new HashSet( rels.length ); - for ( final ProjectRelationship item : rels ) - { - // NOTE: order is important here, in case it's a terminal parent relationship. - if ( declared.contains( item.getTarget() - .asProjectVersionRef() ) || !declared.add( item.getDeclaring() ) ) - { - return true; - } - } - - return false; - } - - @Override - public String getKey() - { - return DigestUtils.shaHex( StringUtils.join( rels, "," ) ); - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/CycleDetectionTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/CycleDetectionTest.java deleted file mode 100644 index d5112bb2..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/CycleDetectionTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.CycleDetectionTCK; - -public class CycleDetectionTest - extends CycleDetectionTCK -{ - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/RelationshipGraphConnectionTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/RelationshipGraphConnectionTest.java deleted file mode 100644 index be1dab3f..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/RelationshipGraphConnectionTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.RelationshipGraphConnection_TCK; - -public class RelationshipGraphConnectionTest - extends RelationshipGraphConnection_TCK -{ - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/RelationshipGraphTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/RelationshipGraphTest.java deleted file mode 100644 index 712f196f..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/RelationshipGraphTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.RelationshipGraphTCK; - -public class RelationshipGraphTest - extends RelationshipGraphTCK -{ - - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/SubGraphSelectionTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/SubGraphSelectionTest.java deleted file mode 100644 index a0b3a642..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/SubGraphSelectionTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.RelationshipGraphTCK; - -public class SubGraphSelectionTest - extends RelationshipGraphTCK -{ - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/AncestryTraversalTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/AncestryTraversalTest.java deleted file mode 100644 index 37e87654..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/AncestryTraversalTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung.traverse; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.jung.JungGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.traverse.AncestryTraversalTCK; - -public class AncestryTraversalTest - extends AncestryTraversalTCK -{ - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/BuildOrderTraversalTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/BuildOrderTraversalTest.java deleted file mode 100644 index 872b5fb7..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/BuildOrderTraversalTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung.traverse; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.jung.JungGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.traverse.BuildOrderTraversalTCK; - -public class BuildOrderTraversalTest - extends BuildOrderTraversalTCK -{ - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/TransitiveDependencyTraversalTest.java b/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/TransitiveDependencyTraversalTest.java deleted file mode 100644 index e3d1d6e3..00000000 --- a/drivers/jung/src/test/java/org/commonjava/maven/atlas/graph/spi/jung/traverse/TransitiveDependencyTraversalTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.jung.traverse; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.jung.JungGraphConnectionFactory; -import org.commonjava.maven.atlas.tck.graph.traverse.TransitiveDependencyTraversalTCK; - -public class TransitiveDependencyTraversalTest - extends TransitiveDependencyTraversalTCK -{ - private final JungGraphConnectionFactory connFac = new JungGraphConnectionFactory(); - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return connFac; - } - -} diff --git a/drivers/jung/src/test/resources/logback-test.xml b/drivers/jung/src/test/resources/logback-test.xml deleted file mode 100644 index 37e09750..00000000 --- a/drivers/jung/src/test/resources/logback-test.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - diff --git a/drivers/neo4j-embedded/LICENSE.txt b/drivers/neo4j-embedded/LICENSE.txt deleted file mode 100644 index 82ad83d5..00000000 --- a/drivers/neo4j-embedded/LICENSE.txt +++ /dev/null @@ -1,684 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2014 Red Hat, Inc.. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the GNU Public License v3.0 -# which accompanies this distribution, and is available at -# http://www.gnu.org/licenses/gpl.html -# -# Contributors: -# Red Hat, Inc. - initial API and implementation -#------------------------------------------------------------------------------- - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/drivers/neo4j-embedded/performance-todo.txt b/drivers/neo4j-embedded/performance-todo.txt deleted file mode 100644 index 07c63ea2..00000000 --- a/drivers/neo4j-embedded/performance-todo.txt +++ /dev/null @@ -1,30 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2014 Red Hat, Inc.. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the GNU Public License v3.0 -# which accompanies this distribution, and is available at -# http://www.gnu.org/licenses/gpl.html -# -# Contributors: -# Red Hat, Inc. - initial API and implementation -#------------------------------------------------------------------------------- -0. Cycle detection still entering infinite loop, somehow!! - - Need to track that down. - -1. Lazy cycle detection with dirty flag on view. - - When updating the db, simply mark cycle detection as pending on all view nodes, instead of incurring cycle detection expense up front. Cycles are only queried in certain use cases, so this expense is best delayed. - -2. Store selections in view-specific index, managed by AtlasCollector instance. - - Selections driven by view-managed versions or mutations should NOT pollute other views' traverses. To avoid this, need to store selection in an index specific to the view, and hand this to the AtlasCollector on ctor. - -3. Store seen paths in view-specific index, managed by visitor. - - Storing in memory will lead to inevitable memory problems for really large traverses. We can page out older seen results by using an index, then delete the index when the traverse completes. - -4. Add traverseFinished() to visitor. - - Clean up seen index in this method, which MUST be called before collectAtlasRelationships(..) returns. - diff --git a/drivers/neo4j-embedded/pom.xml b/drivers/neo4j-embedded/pom.xml deleted file mode 100644 index b0c0784e..00000000 --- a/drivers/neo4j-embedded/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - 4.0.0 - - - org.commonjava.maven.atlas - atlas-drivers-parent - 0.12.0-EXP-SNAPSHOT - - - atlas-driver-neo4j-embedded - - Atlas :: Maven Project-Graph :: Embedded Neo4J API - - - - org.neo4j - neo4j - - - commons-codec - commons-codec - - - org.commonjava.web - json-serialization - - - com.google.code.gson - gson - - - org.slf4j - log4j-over-slf4j - - - - diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileNeo4JGraphConnection.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileNeo4JGraphConnection.java deleted file mode 100644 index c9e794be..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileNeo4JGraphConnection.java +++ /dev/null @@ -1,2438 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.CONFIG_ID; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.GA; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.GAV; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.NID; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.RELATIONSHIP_ID; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.RID; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.SOURCE_URI; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.VIEW_ID; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.addToURISetProperty; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.convertToProjects; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.convertToRelationships; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.getMetadataMap; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.getStringProperty; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.id; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.isConnected; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.markConnected; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toNodeProperties; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toProjectRelationship; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toProjectVersionRef; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toRelationshipProperties; -import static org.commonjava.maven.atlas.graph.spi.neo4j.traverse.TraversalUtils.getGraphRelTypes; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipComparator; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.AtlasCollector; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.MembershipWrappedTraversalEvaluator; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.PathCollectingVisitor; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.PathExistenceVisitor; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.SubPathsCollectingVisitor; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.TraversalUtils; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.TraverseVisitor; -import org.commonjava.maven.atlas.graph.spi.neo4j.update.CycleCacheUpdater; -import org.commonjava.maven.atlas.graph.spi.neo4j.update.ViewUpdater; -import org.commonjava.maven.atlas.graph.traverse.RelationshipGraphTraversal; -import org.commonjava.maven.atlas.graph.traverse.TraversalType; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.neo4j.cypher.javacompat.ExecutionEngine; -import org.neo4j.cypher.javacompat.ExecutionResult; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.GraphDatabaseService; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; -import org.neo4j.graphdb.Transaction; -import org.neo4j.graphdb.factory.GraphDatabaseFactory; -import org.neo4j.graphdb.index.Index; -import org.neo4j.graphdb.index.IndexHits; -import org.neo4j.graphdb.index.RelationshipIndex; -import org.neo4j.graphdb.traversal.TraversalDescription; -import org.neo4j.graphdb.traversal.Traverser; -import org.neo4j.kernel.Traversal; -import org.neo4j.kernel.Uniqueness; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FileNeo4JGraphConnection - implements Runnable, Neo4JGraphConnection -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - // private static final int ADD_BATCHSIZE = 50; - - private static final String ALL_RELATIONSHIPS = "all_relationships"; - - private static final String BY_GAV_IDX = "by_gav"; - - private static final String BY_GA_IDX = "by_ga"; - - private static final String CONFIG_NODES_IDX = "config_nodes"; - - private static final String VARIABLE_NODES_IDX = "variable_nodes"; - - private static final String MISSING_NODES_IDX = "missing_nodes"; - - private static final String METADATA_INDEX_PREFIX = "has_metadata_"; - - private static final String MANAGED_GA = "managed-ga"; - - private static final String MANAGED_KEY = "mkey"; - - private static final String BASE_CONFIG_NODE = "_base"; - - private static final String MKEY_FORMAT = "%d/%s/%s:%s"; - - // private static final String GRAPH_ATLAS_TYPES_CLAUSE = join( GraphRelType.atlasRelationshipTypes(), "|" ); - - /* @formatter:off */ -// private static final String CYPHER_SELECTION_RETRIEVAL = String.format( -// "CYPHER 1.8 START a=node({roots}) " -// + "\nMATCH p1=(a)-[:{}*1..]->(s), " -// + "\n p2=(a)-[:{}*1..]->(v) " -// + "\nWITH v, s, last(relationships(p1)) as r1, last(relationships(p2)) as r2 " -// + "\nWHERE v.{} = s.{} " -// + "\n AND v.{} = s.{} " -// + "\n AND has(r1.{}) " -// + "\n AND any(x in r1.{} " -// + "\n WHERE x IN {roots}) " -// + "\n AND has(r2.{}) " -// + "\n AND any(x in r2.{} " -// + "\n WHERE x IN {roots}) " -// + "\nRETURN r1,r2,v,s", -// GRAPH_ATLAS_TYPES_CLAUSE, GRAPH_ATLAS_TYPES_CLAUSE, -// Conversions.GROUP_ID, Conversions.GROUP_ID, -// Conversions.ARTIFACT_ID, Conversions.ARTIFACT_ID, -// Conversions.SELECTED_FOR, Conversions.SELECTED_FOR, -// Conversions.DESELECTED_FOR, Conversions.DESELECTED_FOR -// ); - - /* @formatter:on */ - - private GraphDatabaseService graph; - - private final boolean useShutdownHook; - - private ExecutionEngine queryEngine; - - private Node configNode; - - private final GraphAdminImpl adminAccess; - - private final String workspaceId; - - private final FileNeo4jConnectionFactory factory; - - FileNeo4JGraphConnection( final String workspaceId, final File dbDir, final boolean useShutdownHook, - final FileNeo4jConnectionFactory factory ) - { - this.workspaceId = workspaceId; - this.factory = factory; - this.adminAccess = new GraphAdminImpl( this ); - - this.graph = new GraphDatabaseFactory().newEmbeddedDatabase( dbDir.getAbsolutePath() ); - this.useShutdownHook = useShutdownHook; - - printStats(); - - if ( useShutdownHook ) - { - Runtime.getRuntime() - .addShutdownHook( new Thread( this ) ); - } - - final Transaction tx = graph.beginTx(); - try - { - graph.createNode(); - - long id = -1; - final IndexHits hits = graph.index() - .forNodes( CONFIG_NODES_IDX ) - .get( CONFIG_ID, BASE_CONFIG_NODE ); - if ( hits.hasNext() ) - { - configNode = hits.next(); - id = configNode.getId(); - } - - if ( id < 0 ) - { - configNode = graph.createNode(); - id = configNode.getId(); - - graph.index() - .forNodes( CONFIG_NODES_IDX ) - .add( configNode, CONFIG_ID, BASE_CONFIG_NODE ); - - } - - tx.success(); - } - finally - { - tx.finish(); - } - } - - protected GraphDatabaseService getGraph() - { - return graph; - } - - protected boolean isUseShutdownHook() - { - return useShutdownHook; - } - - @Override - public void printStats() - { - logger.info( "Graph contains {} nodes.", graph.index() - .forNodes( BY_GAV_IDX ) - .query( GAV, "*" ) - .size() ); - - logger.info( "Graph contains {} relationships.", graph.index() - .forRelationships( ALL_RELATIONSHIPS ) - .query( RELATIONSHIP_ID, "*" ) - .size() ); - } - - @Override - public Collection> getRelationshipsDeclaredBy( final ViewParams params, - final ProjectVersionRef ref ) - { - checkClosed(); - - if ( ref == null ) - { - return null; - } - - final Index index = graph.index() - .forNodes( BY_GAV_IDX ); - final IndexHits hits = index.get( GAV, ref.asProjectVersionRef() - .toString() ); - - if ( hits.hasNext() ) - { - final Node node = hits.next(); - final Iterable relationships = node.getRelationships( Direction.OUTGOING ); - return convertToRelationships( relationships, new ConversionCache() ); - } - - return null; - } - - private void checkClosed() - { - if ( graph == null ) - { - throw new IllegalStateException( "Graph database has been closed!" ); - } - } - - @Override - public Collection> getRelationshipsTargeting( final ViewParams params, - final ProjectVersionRef ref ) - { - checkClosed(); - - final ConversionCache cache = new ConversionCache(); - if ( registerView( params ) ) - { - final Node node = getNode( ref ); - - final Iterable relationships = node.getRelationships( Direction.INCOMING ); - final StringBuilder sb = new StringBuilder(); - for ( final Relationship r : relationships ) - { - if ( sb.length() > 0 ) - { - sb.append( ' ' ); - } - - sb.append( r.getId() ); - } - - final RelationshipIndex cachedRels = new ViewIndexes( graph.index(), params ).getCachedRelationships(); - final IndexHits hits = cachedRels.query( RID, sb.toString() ); - - final Set> result = new HashSet>(); - - while ( hits.hasNext() ) - { - final Relationship r = hits.next(); - final ProjectRelationship rel = toProjectRelationship( r, cache ); - result.add( rel ); - } - - return result; - } - - final Index index = graph.index() - .forNodes( BY_GAV_IDX ); - final IndexHits hits = index.get( GAV, ref.asProjectVersionRef() - .toString() ); - - if ( hits.hasNext() ) - { - final Node node = hits.next(); - // FIXME: What if this params has a filter or mutator?? Without a root, that would be very strange... - final Iterable relationships = node.getRelationships( Direction.INCOMING ); - return convertToRelationships( relationships, cache ); - } - - return null; - } - - @Override - public Set getAllProjects( final ViewParams params ) - { - checkClosed(); - - logger.debug( "Getting all-projects for: {}", params ); - final ConversionCache cache = new ConversionCache(); - if ( registerView( params ) ) - { - final Index cachedNodes = new ViewIndexes( graph.index(), params ).getCachedNodes(); - - final IndexHits nodeHits = cachedNodes.query( NID, "*" ); - final Set nodes = new HashSet(); - while ( nodeHits.hasNext() ) - { - nodes.add( toProjectVersionRef( nodeHits.next(), cache ) ); - } - - return nodes; - } - - // FIXME: What if this params has a filter or mutator?? Without a root, that would be very strange... - return new HashSet( convertToProjects( graph.index() - .forNodes( BY_GAV_IDX ) - .query( GAV, "*" ), cache ) ); - } - - private void updateView( final ViewParams params, final ConversionCache cache ) - { - if ( params.getRoots() == null || params.getRoots() - .isEmpty() ) - { - logger.debug( "paramss without roots are never updated." ); - return; - } - - final Node paramsNode = getViewNode( params ); - - logger.debug( "Checking whether {} ({} / {}) is in need of update.", params.getShortId(), paramsNode, params ); - final ViewIndexes indexes = new ViewIndexes( graph.index(), params ); - - if ( Conversions.isMembershipDetectionPending( paramsNode ) ) - { - logger.debug( "Traversing graph to update params membership: {} ({})", params.getShortId(), params ); - final Set roots = getRoots( params ); - if ( roots.isEmpty() ) - { - logger.debug( "{}: No root nodes found.", params.getShortId() ); - return; - } - - final ViewUpdater updater = new ViewUpdater( params, paramsNode, indexes, cache, adminAccess ); - collectAtlasRelationships( params, updater, roots, false, Uniqueness.RELATIONSHIP_GLOBAL ); - - logger.debug( "Traverse complete for update of params: {}", params.getShortId() ); - } - else - { - logger.debug( "{}: no update pending.", params.getShortId() ); - } - } - - @Override - public Collection> getAllRelationships( final ViewParams params ) - { - checkClosed(); - - final ConversionCache cache = new ConversionCache(); - if ( registerView( params ) ) - { - final RelationshipIndex cachedRels = new ViewIndexes( graph.index(), params ).getCachedRelationships(); - - final IndexHits relHits = cachedRels.query( RID, "*" ); - final Set> rels = new HashSet>(); - while ( relHits.hasNext() ) - { - rels.add( toProjectRelationship( relHits.next(), cache ) ); - } - - return rels; - } - - final IndexHits hits = graph.index() - .forRelationships( ALL_RELATIONSHIPS ) - .query( RELATIONSHIP_ID, "*" ); - return convertToRelationships( hits, cache ); - } - - @Override - public Map, GraphPathInfo> getPathMapTargeting( final ViewParams params, - final Set refs ) - { - checkClosed(); - if ( !registerView( params ) ) - { - throw new IllegalArgumentException( - "You must specify at least one root GAV in order to retrieve path-related info." ); - } - - final Set endNodes = getNodes( refs ); - - final ConversionCache cache = new ConversionCache(); - final PathCollectingVisitor visitor = new PathCollectingVisitor( endNodes, cache ); - collectAtlasRelationships( params, visitor, getRoots( params ), false, Uniqueness.RELATIONSHIP_GLOBAL ); - - final Map, GraphPathInfo> result = new HashMap, GraphPathInfo>(); - for ( final Neo4jGraphPath path : visitor ) - { - GraphPathInfo info = new GraphPathInfo( this, params ); - for ( final Long rid : path ) - { - final Relationship r = graph.getRelationshipById( rid ); - info = info.getChildPathInfo( toProjectRelationship( r, cache ) ); - } - - result.put( path, info ); - } - - return result; - } - - @Override - public ProjectVersionRef getPathTargetRef( final GraphPath path ) - { - if ( path == null ) - { - return null; - } - - if ( !( path instanceof Neo4jGraphPath ) ) - { - throw new IllegalArgumentException( "GraphPath instances must be of type Neo4jGraphPath. Was: " - + path.getClass() - .getName() ); - } - - final long rid = ( (Neo4jGraphPath) path ).getLastRelationshipId(); - if ( rid < 0 ) - { - return null; - } - - final Relationship rel = graph.getRelationshipById( rid ); - final Node target = rel.getEndNode(); - - return toProjectVersionRef( target, null ); - } - - @Override - public Set>> getAllPathsTo( final ViewParams params, final ProjectVersionRef... refs ) - { - checkClosed(); - if ( !registerView( params ) ) - { - throw new IllegalArgumentException( - "You must specify at least one root GAV in order to retrieve path-related info." ); - } - - final Set endNodes = getNodes( refs ); - - final ConversionCache cache = new ConversionCache(); - final PathCollectingVisitor visitor = new PathCollectingVisitor( endNodes, cache ); - collectAtlasRelationships( params, visitor, getRoots( params ), false, Uniqueness.RELATIONSHIP_GLOBAL ); - - final Set>> result = new HashSet>>(); - for ( final Neo4jGraphPath path : visitor ) - { - result.add( convertToRelationships( path, adminAccess, cache ) ); - } - - return result; - } - - @Override - public synchronized Set> addRelationships( final ProjectRelationship... rels ) - { - final Map> createdRelationshipsMap = addRelationshipsInternal( rels ); - - logger.info( "Updating all-projects caches with {} new entries", createdRelationshipsMap.size() ); - updateCaches( createdRelationshipsMap ); - - // FIXME: We're delaying cycle detection, so there will NEVER be rejected relationships... - final Set> skipped = Collections.emptySet(); - logger.debug( "Cycle injection detected for: {}", skipped ); - logger.info( "Returning {} rejected relationships.", skipped.size() ); - - // printGraphStats(); - - return skipped; - } - - private Map> addRelationshipsInternal( final ProjectRelationship... rels ) - { - checkClosed(); - - final ConversionCache cache = new ConversionCache(); - final Map> createdRelationshipsMap = new HashMap>(); - - final List> sorted = new ArrayList>( Arrays.asList( rels ) ); - Collections.sort( sorted, RelationshipComparator.INSTANCE ); - - final Transaction tx = graph.beginTx(); - try - { - // int txBatchCount = 0; - nextRel: for ( final ProjectRelationship rel : sorted ) - { - logger.debug( "Checking relationship: {}", rel ); - - final Index index = graph.index() - .forNodes( BY_GAV_IDX ); - - final ProjectVersionRef declaring = rel.getDeclaring(); - final ProjectVersionRef target = rel.getTarget() - .asProjectVersionRef(); - - final Node[] nodes = new Node[2]; - int i = 0; - for ( final ProjectVersionRef ref : new ProjectVersionRef[] { declaring, target } ) - { - final IndexHits hits = index.get( GAV, ref.asProjectVersionRef() - .toString() ); - if ( !hits.hasNext() ) - { - logger.debug( "Creating new node for: {} to support addition of relationship: {}", ref, rel ); - try - { - final Node node = newProjectNode( ref ); - logger.debug( "Node: {} created for: {}", node, ref ); - nodes[i] = node; - } - catch ( final InvalidVersionSpecificationException e ) - { - // FIXME: This means we're discarding a rejected relationship without passing it back...NOT GOOD - // However, some code assumes rejects are cycles...also not good. - logger.error( String.format( "Failed to create node for project ref: %s. Reason: %s", ref, - e.getMessage() ), e ); - continue nextRel; - } - } - else - { - nodes[i] = hits.next(); - - logger.debug( "Using existing project node: {} for: {}", nodes[i], ref.asProjectVersionRef() ); - } - - i++; - } - - final RelationshipIndex relIdx = graph.index() - .forRelationships( ALL_RELATIONSHIPS ); - - final String relId = id( rel ); - final IndexHits relHits = relIdx.get( RELATIONSHIP_ID, relId ); - - Relationship relationship; - if ( relHits.size() < 1 ) - { - final Node from = nodes[0]; - - logger.debug( "Removing missing/incomplete flag from: {} ({})", from, declaring ); - graph.index() - .forNodes( MISSING_NODES_IDX ) - .remove( from ); - - markConnected( from, true ); - - if ( from.getId() != nodes[1].getId() ) - { - final Node to = nodes[1]; - - logger.debug( "Creating graph relationship for: {} between node: {} and node: {}", rel, from, - to ); - - final GraphRelType grt = GraphRelType.map( rel.getType(), rel.isManaged() ); - - relationship = from.createRelationshipTo( to, grt ); - - // now, we set an index on the relationship of where it is in the range of ALL atlas relationships - // for this node. ProjectRelationship.getIndex() only gives the index for that TYPE, so we can't - // use it. The next value will be stored on the from node for the next go. - int nodeRelIdx = Conversions.getIntegerProperty( Conversions.ATLAS_RELATIONSHIP_COUNT, from, 0 ); - - relationship.setProperty( Conversions.ATLAS_RELATIONSHIP_INDEX, nodeRelIdx ); - from.setProperty( Conversions.ATLAS_RELATIONSHIP_COUNT, ++nodeRelIdx ); - - logger.debug( "New relationship is: {} with type: {}", relationship, grt ); - - toRelationshipProperties( rel, relationship ); - relIdx.add( relationship, RELATIONSHIP_ID, relId ); - - if ( rel.isManaged() ) - { - graph.index() - .forRelationships( MANAGED_GA ) - .add( relationship, - MANAGED_KEY, - String.format( MKEY_FORMAT, relationship.getStartNode() - .getId(), rel.getType() - .name(), rel.getTarget() - .getGroupId(), - rel.getTarget() - .getArtifactId() ) ); - } - - logger.debug( "+= {} ({})", relationship, rel ); - } - else - { - logger.info( "Self-referential relationship: {}. Skipping", rel ); - continue; - } - - if ( !( rel instanceof ParentRelationship ) || !( (ParentRelationship) rel ).isTerminus() ) - { - createdRelationshipsMap.put( relationship.getId(), rel ); - } - } - else - { - relationship = relHits.next(); - logger.debug( "== {} ({})", relationship, toProjectRelationship( relationship, cache ) ); - - addToURISetProperty( rel.getSources(), SOURCE_URI, relationship ); - } - - // We don't really need transaction here, I don't think... - // but we're forced to use one to update the graph. - // So, to find a balance between memory consumed by a transaction - // and speed (creating/committing txns takes time), we'll batch them. - // txBatchCount++; - // if ( txBatchCount >= ADD_BATCHSIZE ) - // { - // logger.info( "Storing batch of {} relationships.", txBatchCount + 1 ); - // tx.success(); - // tx = graph.beginTx(); - // txBatchCount = 0; - // } - } - - // logger.info( "Storing final batch of {} relationships.", txBatchCount + 1 ); - tx.success(); - } - finally - { - tx.finish(); - } - - return createdRelationshipsMap; - } - - @Override - public boolean introducesCycle( final ViewParams params, final ProjectRelationship rel ) - { - checkClosed(); - - final ProjectVersionRef to = rel.getDeclaring(); - final ProjectVersionRef from = rel.getTarget() - .asProjectVersionRef(); - - final Node toNode = getNode( to ); - final Node fromNode = getNode( from ); - - if ( toNode == null || fromNode == null ) - { - return false; - } - - logger.debug( "Checking for existence of path from: {} to: {} in global database", fromNode, toNode ); - final PathExistenceVisitor collector = new PathExistenceVisitor( toNode ); - collectAtlasRelationships( params, collector, Collections.singleton( fromNode ), false, - Uniqueness.RELATIONSHIP_GLOBAL ); - - return collector.isFound(); - } - - private Node newProjectNode( final ProjectVersionRef ref ) - { - final Node node = graph.createNode(); - - toNodeProperties( ref, node, false ); - - final String gav = ref.asProjectVersionRef() - .toString(); - - graph.index() - .forNodes( BY_GAV_IDX ) - .add( node, GAV, gav ); - - graph.index() - .forNodes( BY_GA_IDX ) - .add( node, GA, ref.asProjectRef() - .toString() ); - - graph.index() - .forNodes( MISSING_NODES_IDX ) - .add( node, GAV, gav ); - - if ( ref.isVariableVersion() ) - { - // logger.info( "Adding {} to variable-nodes index.", ref ); - graph.index() - .forNodes( VARIABLE_NODES_IDX ) - .add( node, GAV, gav ); - } - - // logger.info( "Created project node: {} with id: {}", ref, node.getId() ); - return node; - } - - private Relationship select( final Relationship old, final ViewParams params, final Node paramsNode, - final GraphPathInfo pathInfo, final Neo4jGraphPath path ) - { - final ViewIndexes indexes = new ViewIndexes( graph.index(), params ); - - final long targetRid = Conversions.getDeselectionTarget( old.getId(), paramsNode ); - if ( targetRid > -1 ) - { - return graph.getRelationshipById( targetRid ); - } - - final ProjectRelationship oldRel = toProjectRelationship( old, null ); - if ( oldRel == null ) - { - return null; - } - - logger.debug( "Selecting mutated relationship for: {} with pathInfo: {}", oldRel, pathInfo ); - final ProjectRelationship selected = pathInfo == null ? oldRel : pathInfo.selectRelationship( oldRel, path ); - - if ( selected == null ) - { - return null; - } - - if ( selected != oldRel ) - { - final RelationshipIndex relIdx = graph.index() - .forRelationships( ALL_RELATIONSHIPS ); - - // logger.info( "Checking for existing DB relationship for: {}", selected ); - final String selId = id( selected ); - IndexHits hits = relIdx.get( RELATIONSHIP_ID, selId ); - if ( hits.hasNext() ) - { - return hits.next(); - } - - logger.info( "Creating ad-hoc db relationship for selection: {} (replacing: {})", selected, oldRel ); - - @SuppressWarnings( "unused" ) - final Map> added = addRelationshipsInternal( selected ); - - final Transaction tx = graph.beginTx(); - try - { - Relationship result = null; - hits = relIdx.get( RELATIONSHIP_ID, selId ); - if ( hits.hasNext() ) - { - result = hits.next(); - - logger.debug( "Adding relationship {} to selections index", result ); - Conversions.setSelection( old.getId(), result.getId(), paramsNode ); - - // Does this imply that a whole subgraph from oldRel needs to be removed from the cache?? - // No, because that would only happen if a new selection were added to the params, which would trigger a registerViewSelection() call... - logger.debug( "Adding node {} to membership cache for {}", result.getEndNode() - .getId(), params.getShortId() ); - indexes.getCachedNodes() - .add( result.getEndNode(), NID, result.getEndNode() - .getId() ); - } - - tx.success(); - - return result; - } - finally - { - tx.finish(); - } - } - - return old; - } - - // private Set getProjectsRootedAt( final ViewParams params, final Set roots ) - // { - // Iterable nodes = null; - // if ( roots != null && !roots.isEmpty() ) - // { - // final RootedNodesCollector agg = new RootedNodesCollector( roots, params, false ); - // collectAtlasRelationships( params, agg, roots, false ); - // nodes = agg; - // } - // else - // { - // final IndexHits hits = graph.index() - // .forNodes( BY_GAV_IDX ) - // .query( GAV, "*" ); - // nodes = hits; - // } - // - // return new HashSet( convertToProjects( nodes ) ); - // } - - @Override - public void traverse( final RelationshipGraphTraversal traversal, final ProjectVersionRef root, - final RelationshipGraph graph, final TraversalType type ) - throws RelationshipGraphConnectionException - { - final Node rootNode = getNode( root ); - if ( rootNode == null ) - { - // logger.debug( "Root node not found! (root: {})", root ); - return; - } - - // logger.debug( "PASS: {}", i ); - - // NOTE: Changing this means some cases of morphing filters/mutators may NOT report correct results. - // TraversalDescription description = Traversal.traversal( Uniqueness.RELATIONSHIP_PATH ) - TraversalDescription description = Traversal.traversal( Uniqueness.RELATIONSHIP_GLOBAL ) - .sort( PathComparator.INSTANCE ); - - final ViewParams params = graph.getParams(); - final GraphRelType[] relTypes = getGraphRelTypes( params.getFilter() ); - for ( final GraphRelType grt : relTypes ) - { - description.relationships( grt, Direction.OUTGOING ); - } - - if ( type == TraversalType.breadth_first ) - { - description = description.breadthFirst(); - } - else - { - description = description.depthFirst(); - } - - // logger.debug( "starting traverse of: {}", net ); - traversal.startTraverse( graph ); - - final ConversionCache cache = new ConversionCache(); - - final Node paramsNode = getViewNode( params ); - - @SuppressWarnings( { "rawtypes", "unchecked" } ) - final MembershipWrappedTraversalEvaluator checker = - new MembershipWrappedTraversalEvaluator( Collections.singleton( rootNode.getId() ), traversal, this, - params, paramsNode, adminAccess, relTypes ); - - checker.setConversionCache( cache ); - - description = description.expand( checker ) - .evaluator( checker ); - - final Traverser traverser = description.traverse( rootNode ); - for ( final Path path : traverser ) - { - if ( path.lastRelationship() == null ) - { - continue; - } - - final List> rels = convertToRelationships( path.relationships(), cache ); - logger.debug( "traversing path: {}", rels ); - for ( final ProjectRelationship rel : rels ) - { - logger.debug( "traverse: {}", rel ); - if ( traversal.traverseEdge( rel, rels ) ) - { - logger.debug( "traversed: {}", rel ); - traversal.edgeTraversed( rel, rels ); - } - } - } - - traversal.endTraverse( graph ); - } - - @Override - public boolean containsProject( final ViewParams params, final ProjectVersionRef ref ) - { - checkClosed(); - - final IndexHits missing = graph.index() - .forNodes( MISSING_NODES_IDX ) - .get( GAV, ref.asProjectVersionRef() - .toString() ); - if ( missing.size() > 0 ) - { - return false; - } - - final Node node = getNode( ref ); - if ( node == null ) - { - return false; - } - - if ( registerView( params ) ) - { - final Index cachedNodes = new ViewIndexes( graph.index(), params ).getCachedNodes(); - - final IndexHits nodeHits = cachedNodes.get( NID, node.getId() ); - return nodeHits.hasNext(); - } - else - { - return getNode( ref ) != null; - } - } - - @Override - public boolean containsRelationship( final ViewParams params, final ProjectRelationship rel ) - { - checkClosed(); - - final Relationship relationship = getRelationship( rel ); - if ( relationship == null ) - { - return false; - } - - if ( registerView( params ) ) - { - return new ViewIndexes( graph.index(), params ).getCachedRelationships() - .get( RID, relationship.getId() ) - .hasNext(); - } - else - { - return true; - } - } - - private Set getNodes( final Set refs ) - { - final Set nodes = new HashSet( refs.size() ); - for ( final ProjectVersionRef ref : refs ) - { - final Node node = getNode( ref ); - if ( node != null ) - { - nodes.add( node ); - } - } - - return nodes; - } - - private Set getNodes( final ProjectVersionRef... refs ) - { - final Set nodes = new HashSet( refs.length ); - for ( final ProjectVersionRef ref : refs ) - { - final Node node = getNode( ref ); - if ( node != null ) - { - nodes.add( node ); - } - } - - return nodes; - } - - protected Node getNode( final ProjectVersionRef ref ) - { - checkClosed(); - - final Index idx = graph.index() - .forNodes( BY_GAV_IDX ); - - final IndexHits hits = idx.get( GAV, ref.asProjectVersionRef() - .toString() ); - - if ( hits.size() < 1 ) - { - return null; - } - - final Node node = hits.next(); - - return node; - } - - protected Relationship getRelationship( final ProjectRelationship rel ) - { - return getRelationship( id( rel ) ); - } - - Relationship getRelationship( final String relId ) - { - checkClosed(); - - final RelationshipIndex idx = graph.index() - .forRelationships( ALL_RELATIONSHIPS ); - - final IndexHits hits = idx.get( RELATIONSHIP_ID, relId ); - - return hits.hasNext() ? hits.next() : null; - } - - @Override - public synchronized void close() - throws RelationshipGraphConnectionException - { - if ( graph != null ) - { - try - { - graph.shutdown(); - factory.connectionClosed( workspaceId ); - - graph = null; - } - catch ( final Exception e ) - { - throw new RelationshipGraphConnectionException( "Failed to shutdown: " + e.getMessage(), e ); - } - } - - } - - @Override - public void run() - { - try - { - close(); - } - catch ( final RelationshipGraphConnectionException e ) - { - // new Logger( getClass() ).debug( "Failed to shutdown graph database. Reason: {}", e, e.getMessage() ); - } - } - - @SuppressWarnings( "unused" ) - private boolean isMissing( final Node node ) - { - return !isConnected( node ); - } - - @Override - public boolean isMissing( final ViewParams params, final ProjectVersionRef ref ) - { - final IndexHits hits = graph.index() - .forNodes( MISSING_NODES_IDX ) - .get( GAV, ref.asProjectVersionRef() - .toString() ); - - return hits.size() > 0; - // final IndexHits hits = graph.index() - // .forNodes( BY_GAV_IDX ) - // .get( GAV, ref.asProjectVersionRef().toString() ); - // - // if ( hits.size() > 0 ) - // { - // return !isConnected( hits.next() ); - // } - // - // return false; - } - - @Override - public boolean hasMissingProjects( final ViewParams params ) - { - return hasIndexedProjects( params, MISSING_NODES_IDX ); - } - - @Override - public Set getMissingProjects( final ViewParams params ) - { - logger.debug( "Getting missing projects for: {}", params.getShortId() ); - return getIndexedProjects( params, MISSING_NODES_IDX ); - } - - private Set getIndexedProjects( final ViewParams params, final String indexName ) - { - checkClosed(); - - final IndexHits hits = graph.index() - .forNodes( indexName ) - .query( GAV, "*" ); - - final Set result = new HashSet(); - - final ConversionCache cache = new ConversionCache(); - if ( registerView( params ) ) - { - final Index cachedNodes = new ViewIndexes( graph.index(), params ).getCachedNodes(); - - for ( final Node node : hits ) - { - logger.debug( "Checking for membership: {} ({})", node, node.getProperty( GAV ) ); - final IndexHits cacheHits = cachedNodes.get( NID, node.getId() ); - if ( cacheHits.hasNext() ) - { - logger.debug( "Including: {}", node ); - result.add( toProjectVersionRef( node, cache ) ); - } - } - } - else - { - for ( final Node node : hits ) - { - logger.debug( "Including: {}", node ); - result.add( toProjectVersionRef( node, cache ) ); - } - } - - return result; - } - - private boolean hasIndexedProjects( final ViewParams params, final String indexName ) - { - checkClosed(); - - final IndexHits hits = graph.index() - .forNodes( indexName ) - .query( GAV, "*" ); - - if ( registerView( params ) ) - { - final Index cachedNodes = new ViewIndexes( graph.index(), params ).getCachedNodes(); - - for ( final Node node : hits ) - { - final IndexHits cacheHits = cachedNodes.get( NID, node.getId() ); - if ( cacheHits.hasNext() ) - { - return true; - } - } - } - else - { - if ( hits.hasNext() ) - { - return true; - } - } - - return false; - } - - private Set getRoots( final ViewParams params ) - { - return getRoots( params, true ); - } - - private Set getRoots( final ViewParams params, final boolean defaultToAll ) - { - final Set rootRefs = params.getRoots(); - if ( ( rootRefs == null || rootRefs.isEmpty() ) && defaultToAll ) - { - return Collections.emptySet(); - // final Set connectedNodes = Conversions.toSet( graph.index() - // .forNodes( BY_GAV_IDX ) - // .query( GAV, "*" ) ); - // connectedNodes.removeAll( Conversions.toSet( graph.index() - // .forNodes( MISSING_NODES_IDX ) - // .query( GAV, "*" ) ) ); - // connectedNodes.removeAll( Conversions.toSet( graph.index() - // .forNodes( VARIABLE_NODES_IDX ) - // .query( GAV, "*" ) ) ); - // - // return connectedNodes; - } - - final Set nodes = new HashSet( rootRefs.size() ); - for ( final ProjectVersionRef ref : rootRefs ) - { - final Node n = getNode( ref ); - if ( n != null ) - { - nodes.add( n ); - } - } - - return nodes; - } - - private void collectAtlasRelationships( final ViewParams params, final TraverseVisitor visitor, - final Set start, final boolean sorted, final Uniqueness uniqueness ) - { - if ( start == null || start.isEmpty() ) - { - throw new UnsupportedOperationException( - "Cannot collect atlas nodes/relationships via traversal without at least one 'from' node!" ); - } - - // logger.info( "Traversing for aggregation using: {} from roots: {}", checker.getClass() - // .getName(), from ); - - TraversalDescription description = Traversal.traversal( uniqueness ); - if ( sorted ) - { - description = description.sort( PathComparator.INSTANCE ); - } - - final GraphRelType[] relTypes = getGraphRelTypes( params.getFilter() ); - for ( final GraphRelType grt : relTypes ) - { - description.relationships( grt, Direction.OUTGOING ); - } - - description = description.breadthFirst(); - - final Node paramsNode = getViewNode( params ); - - final AtlasCollector checker = - new AtlasCollector( visitor, start, this, params, paramsNode, adminAccess, relTypes ); - - description = description.expand( checker ) - .evaluator( checker ); - - try - { - final Traverser traverser = description.traverse( start.toArray( new Node[] {} ) ); - for ( @SuppressWarnings( "unused" ) - final Path path : traverser ) - { - // logger.info( "Aggregating path: {}", path ); - // Don't need this, but we need to iterate the traverser. - } - } - finally - { - visitor.traverseComplete( checker ); - } - } - - @Override - public boolean hasVariableProjects( final ViewParams params ) - { - return hasIndexedProjects( params, VARIABLE_NODES_IDX ); - } - - @Override - public Set getVariableProjects( final ViewParams params ) - { - logger.debug( "Getting variable projects for: {}", params.getShortId() ); - return getIndexedProjects( params, VARIABLE_NODES_IDX ); - } - - @Override - public boolean addCycle( final EProjectCycle cycle ) - { - // NOP, auto-detected. - return false; - } - - @Override - public Set getCycles( final ViewParams params ) - { - checkClosed(); - - final ViewIndexes indexes = new ViewIndexes( graph.index(), params ); - - if ( !registerView( params ) ) - { - logger.warn( "Skipping cycle detection on {}. View doesn't declare a root GAV, and this is prohibitively expensive! (params info: {})", - params.getShortId(), params ); - return null; - } - - final ConversionCache cache = new ConversionCache(); - - final Transaction tx = graph.beginTx(); - Node paramsNode; - try - { - paramsNode = getViewNode( params ); - - if ( Conversions.isCycleDetectionPending( paramsNode ) ) - { - logger.debug( "Cycle-detection is pending for: {}", params.getShortId() ); - - Set nodes; - // if ( global ) - // { - // // FIXME: This seems to be VERY expensive - // nodes = Conversions.toSet( graph.index() - // .forNodes( BY_GAV_IDX ) - // .query( GAV, "*" ) ); - // } - // else - // { - nodes = Conversions.toSet( indexes.getCachedNodes() - .query( NID, "*" ) ); - // } - - logger.info( "Traversing graph to find cycles for params {}", params.getShortId() ); - final CycleCacheUpdater cycleUpdater = new CycleCacheUpdater( params, paramsNode, adminAccess, cache ); - // NOTE: Changing this means some cases of morphing filters/mutators may NOT report correct results. - // collectAtlasRelationships( params, cycleUpdater, nodes, false, global ? Uniqueness.RELATIONSHIP_GLOBAL : Uniqueness.RELATIONSHIP_PATH ); - collectAtlasRelationships( params, cycleUpdater, nodes, false, Uniqueness.RELATIONSHIP_GLOBAL ); - - final int cycleCount = cycleUpdater.getCycleCount(); - logger.info( "Registered {} cycles in params {}'s cycle cache.", cycleCount, params.getShortId() ); - - return cycleUpdater.getCycles(); - } - - tx.success(); - } - finally - { - tx.finish(); - } - - final Set cyclePaths = Conversions.getCachedCyclePaths( paramsNode ); - logger.debug( "Retrieved the following cached cycle paths:\n {}", new JoinString( "\n ", cyclePaths ) ); - - // final IndexHits hits = graph.index() - // .forRelationships( CYCLE_INJECTION_IDX ) - // .query( RELATIONSHIP_ID, "*" ); - // - // final Map targetNodes = new HashMap(); - // for ( final Relationship hit : hits ) - // { - // targetNodes.put( hit.getStartNode(), hit ); - // } - // - // final Set paths = getPathsTo( params, targetNodes.keySet() ); - - final Set cycles = new HashSet(); - for ( final CyclePath cyclicPath : cyclePaths ) - { - final List> cycle = new ArrayList>( cyclicPath.length() + 1 ); - for ( final long id : cyclicPath.getRelationshipIds() ) - { - ProjectRelationship rel = cache.getRelationship( id ); - if ( rel == null ) - { - final Relationship r = graph.getRelationshipById( id ); - rel = toProjectRelationship( r, cache ); - } - cycle.add( rel ); - } - - logger.debug( "[cache] CYCLES += {}", cycle ); - cycles.add( new EProjectCycle( cycle ) ); - } - - return cycles; - } - - @Override - public boolean isCycleParticipant( final ViewParams params, final ProjectRelationship rel ) - { - for ( final EProjectCycle cycle : getCycles( params ) ) - { - if ( cycle.contains( rel ) ) - { - return true; - } - } - - return false; - } - - @Override - public boolean isCycleParticipant( final ViewParams params, final ProjectVersionRef ref ) - { - for ( final EProjectCycle cycle : getCycles( params ) ) - { - if ( cycle.contains( ref ) ) - { - return true; - } - } - - return false; - } - - @Override - public void recomputeIncompleteSubgraphs() - { - // NOP, handled automatically. - } - - @Override - public Map getMetadata( final ProjectVersionRef ref ) - { - final Node node = getNode( ref ); - if ( node == null ) - { - return null; - } - - return getMetadataMap( node ); - } - - @Override - public Map getMetadata( final ProjectVersionRef ref, final Set keys ) - { - final Node node = getNode( ref ); - if ( node == null ) - { - return null; - } - - return getMetadataMap( node, keys ); - } - - @Override - public void addMetadata( final ProjectVersionRef ref, final String key, final String value ) - { - final Transaction tx = graph.beginTx(); - try - { - final Node node = getNode( ref ); - if ( node == null ) - { - tx.failure(); - return; - } - - Conversions.setMetadata( key, value, node ); - tx.success(); - } - finally - { - tx.finish(); - } - } - - @Override - public void setMetadata( final ProjectVersionRef ref, final Map metadata ) - { - final Transaction tx = graph.beginTx(); - try - { - final Node node = getNode( ref ); - if ( node == null ) - { - tx.failure(); - return; - } - - Conversions.setMetadata( metadata, node ); - tx.success(); - } - finally - { - tx.finish(); - } - } - - @Override - public ExecutionResult executeFrom( final String cypher, final ProjectVersionRef... roots ) - throws RelationshipGraphConnectionException - { - return executeFrom( cypher, null, roots ); - } - - @Override - public ExecutionResult executeFrom( final String cypher, final Map params, - final ProjectVersionRef... roots ) - throws RelationshipGraphConnectionException - { - if ( cypher.startsWith( "START" ) ) - { - throw new RelationshipGraphConnectionException( - "Leave off the START clause when supplying ProjectVersionRef instances as query roots:\n'{}'", - cypher ); - } - - final StringBuilder sb = new StringBuilder(); - for ( final ProjectVersionRef root : roots ) - { - final Node node = getNode( root ); - if ( node != null ) - { - if ( sb.length() > 0 ) - { - sb.append( ", " ); - } - sb.append( node.getId() ); - } - } - - if ( sb.length() < 1 ) - { - sb.append( "*" ); - } - - return execute( String.format( "START n=node(%s) %s", sb, cypher ), params ); - } - - @Override - public ExecutionResult executeFrom( final String cypher, final ProjectRelationship rootRel ) - throws RelationshipGraphConnectionException - { - return executeFrom( cypher, null, rootRel ); - } - - @Override - public ExecutionResult executeFrom( final String cypher, final Map params, - final ProjectRelationship rootRel ) - throws RelationshipGraphConnectionException - { - if ( cypher.startsWith( "START" ) ) - { - throw new RelationshipGraphConnectionException( - "Leave off the START clause when supplying ProjectRelationship instances as query roots:\n'{}'", - cypher ); - } - - String id = "*"; - if ( rootRel != null ) - { - final Relationship r = getRelationship( rootRel ); - if ( r != null ) - { - id = Long.toString( r.getId() ); - } - } - - return execute( String.format( "START r=relationship(%s) %s", id, cypher ), params ); - } - - @Override - public ExecutionResult execute( final String cypher ) - { - return execute( cypher, null ); - } - - @Override - public ExecutionResult execute( final String cypher, final Map params ) - { - checkExecutionEngine(); - - logger.debug( "Running query:\n\n{}\n\nWith params:\n\n{}\n\n", cypher, params ); - - final String query = cypher.replaceAll( "(\\s)\\s+", "$1" ); - - final ExecutionResult result = - params == null ? queryEngine.execute( query ) : queryEngine.execute( query, params ); - - // logger.info( "Execution plan:\n{}", result.executionPlanDescription() ); - - return result; - } - - private void checkExecutionEngine() - { - if ( queryEngine == null ) - { - queryEngine = new ExecutionEngine( graph ); - } - } - - @Override - public void reindex() - throws RelationshipGraphConnectionException - { - final Transaction tx = graph.beginTx(); - try - { - final IndexHits nodes = graph.index() - .forNodes( BY_GAV_IDX ) - .query( GAV, "*" ); - for ( final Node node : nodes ) - { - reindexNode( node ); - } - - tx.success(); - } - finally - { - tx.finish(); - } - } - - @Override - public void reindex( final ProjectVersionRef ref ) - { - final Node node = getNode( ref ); - if ( node == null ) - { - return; - } - - final Transaction tx = graph.beginTx(); - try - { - reindexNode( node ); - tx.success(); - } - finally - { - tx.finish(); - } - } - - private void reindexNode( final Node node ) - { - final String gav = getStringProperty( GAV, node ); - if ( gav == null ) - { - return; - } - - final Map md = getMetadataMap( node ); - if ( md == null || md.isEmpty() ) - { - return; - } - - for ( final String key : md.keySet() ) - { - graph.index() - .forNodes( METADATA_INDEX_PREFIX + key ) - .add( node, GAV, gav ); - } - } - - @Override - public Set getProjectsWithMetadata( final ViewParams params, final String key ) - { - checkClosed(); - - final IndexHits nodes = graph.index() - .forNodes( METADATA_INDEX_PREFIX + key ) - .query( GAV, "*" ); - - final ConversionCache cache = new ConversionCache(); - if ( registerView( params ) ) - { - final Index cachedNodes = new ViewIndexes( graph.index(), params ).getCachedNodes(); - - final Set result = new HashSet(); - for ( final Node node : nodes ) - { - if ( cachedNodes.get( NID, node.getId() ) - .hasNext() ) - { - result.add( toProjectVersionRef( node, cache ) ); - } - } - - return result; - } - else - { - return new HashSet( convertToProjects( nodes, cache ) ); - } - } - - @Override - public void addDisconnectedProject( final ProjectVersionRef ref ) - { - if ( !containsProject( null, ref ) ) - { - final Transaction tx = graph.beginTx(); - try - { - logger.debug( "Creating new node to account for disconnected project: {}", ref ); - newProjectNode( ref ); - - tx.success(); - } - finally - { - tx.finish(); - } - } - } - - /** - * @deprecated Use {@link #getDirectRelationshipsFrom(GraphView,ProjectVersionRef,boolean,boolean,RelationshipType...)} instead - */ - @Deprecated - @Override - public Set> getDirectRelationshipsFrom( final ViewParams params, - final ProjectVersionRef from, - final boolean includeManagedInfo, - final RelationshipType... types ) - { - return getDirectRelationshipsFrom( params, from, includeManagedInfo, true, types ); - } - - @Override - public Set> getDirectRelationshipsFrom( final ViewParams params, - final ProjectVersionRef from, - final boolean includeManagedInfo, - final boolean includeConcreteInfo, - final RelationshipType... types ) - { - final Node node = getNode( from ); - if ( node == null ) - { - return null; - } - - final Set grts = new HashSet( types.length * 2 ); - for ( final RelationshipType relType : types ) - { - if ( includeConcreteInfo ) - { - grts.add( GraphRelType.map( relType, false ) ); - } - - if ( includeManagedInfo ) - { - grts.add( GraphRelType.map( relType, true ) ); - } - } - - final Iterable relationships = - node.getRelationships( Direction.OUTGOING, grts.toArray( new GraphRelType[grts.size()] ) ); - - if ( relationships != null ) - { - final Set> result = new HashSet>(); - - final ConversionCache cache = new ConversionCache(); - for ( final Relationship r : relationships ) - { - if ( TraversalUtils.acceptedInView( r, params, cache ) ) - { - final ProjectRelationship rel = toProjectRelationship( r, cache ); - if ( rel != null ) - { - result.add( rel ); - } - } - } - - return result; - } - - return null; - } - - @Override - public Set> getDirectRelationshipsTo( final ViewParams params, final ProjectVersionRef to, - final boolean includeManagedInfo, - final boolean includeConcreteInfo, - final RelationshipType... types ) - { - logger.debug( "Finding relationships targeting: {} (filter: {}, managed: {}, types: {})", to, - params.getFilter(), includeManagedInfo, Arrays.asList( types ) ); - final Node node = getNode( to ); - if ( node == null ) - { - return null; - } - - final Set grts = new HashSet( types.length * 2 ); - for ( final RelationshipType relType : types ) - { - if ( includeConcreteInfo ) - { - final GraphRelType graphType = GraphRelType.map( relType, false ); - if ( graphType != null ) - { - grts.add( graphType ); - } - } - - if ( includeManagedInfo ) - { - final GraphRelType graphType = GraphRelType.map( relType, true ); - if ( graphType != null ) - { - grts.add( graphType ); - } - } - } - - logger.debug( "Using graph-relationship types: {}", grts ); - - final Iterable relationships = - node.getRelationships( Direction.INCOMING, grts.toArray( new GraphRelType[grts.size()] ) ); - - final ConversionCache cache = new ConversionCache(); - if ( relationships != null ) - { - final Set> result = new HashSet>(); - for ( final Relationship r : relationships ) - { - logger.debug( "Examining relationship: {}", r ); - if ( TraversalUtils.acceptedInView( r, params, cache ) ) - { - final ProjectRelationship rel = toProjectRelationship( r, cache ); - if ( rel != null ) - { - result.add( rel ); - } - } - } - - return result; - } - - return null; - } - - @Override - public Set getProjectsMatching( final ViewParams params, final ProjectRef projectRef ) - { - final IndexHits hits = graph.index() - .forNodes( BY_GA_IDX ) - .query( GA, projectRef.asProjectRef() - .toString() ); - return new HashSet( convertToProjects( hits, new ConversionCache() ) ); - } - - @Override - public void deleteRelationshipsDeclaredBy( final ProjectVersionRef ref ) - throws RelationshipGraphConnectionException - { - checkClosed(); - - if ( ref == null ) - { - return; - } - - final Index index = graph.index() - .forNodes( BY_GAV_IDX ); - - final String gav = ref.asProjectVersionRef() - .toString(); - - final IndexHits hits = index.get( GAV, gav ); - - if ( hits.hasNext() ) - { - final Transaction tx = graph.beginTx(); - try - { - final Node node = hits.next(); - final Iterable relationships = node.getRelationships( Direction.OUTGOING ); - if ( relationships != null ) - { - for ( final Relationship r : relationships ) - { - r.delete(); - } - } - - graph.index() - .forNodes( MISSING_NODES_IDX ) - .add( node, GAV, gav ); - - tx.success(); - } - finally - { - tx.finish(); - } - } - } - - @Override - public ProjectVersionRef getManagedTargetFor( final ProjectVersionRef target, final GraphPath path, - final RelationshipType type ) - { - if ( path == null ) - { - return null; - } - - if ( !( path instanceof Neo4jGraphPath ) ) - { - throw new IllegalArgumentException( "GraphPath instances must be of type Neo4jGraphPath. Was: " - + path.getClass() - .getName() ); - } - - final RelationshipIndex idx = graph.index() - .forRelationships( MANAGED_GA ); - - // logger.info( "Searching for managed override of: {} in: {}", target, path ); - final Neo4jGraphPath neopath = (Neo4jGraphPath) path; - - final ConversionCache cache = new ConversionCache(); - for ( final Long id : neopath ) - { - final Relationship r = graph.getRelationshipById( id ); - - final String mkey = - String.format( MKEY_FORMAT, r.getStartNode() - .getId(), type.name(), target.getGroupId(), target.getArtifactId() ); - - // logger.info( "Searching for m-key: {}", mkey ); - - final IndexHits hits = idx.get( MANAGED_KEY, mkey ); - if ( hits != null && hits.hasNext() ) - { - final Relationship hit = hits.next(); - final ProjectVersionRef ref = toProjectVersionRef( hit.getEndNode(), cache ); - - final ProjectRelationship rel = Conversions.toProjectRelationship( hit, cache ); - logger.info( "[MUTATION] {} => {} (via: {})", target, ref, rel ); - - return ref; - } - - // final Node node = graph.getNodeById( id ); - // final Iterable relationships = node.getRelationships( Direction.OUTGOING, GraphRelType.map( type, true ) ); - // if ( relationships != null ) - // { - // for ( final Relationship r : relationships ) - // { - // if ( r.hasProperty( GROUP_ID ) && r.getProperty( GROUP_ID ) - // .equals( target.getGroupId() ) && r.hasProperty( ARTIFACT_ID ) - // && r.getProperty( ARTIFACT_ID ) - // .equals( target.getArtifactId() ) ) - // { - // return toProjectVersionRef( r.getEndNode() ); - // } - // } - // } - } - - return null; - } - - @Override - public List getPathRefs( final ViewParams params, final GraphPath path ) - { - if ( path != null && !( path instanceof Neo4jGraphPath ) ) - { - throw new IllegalArgumentException( "Cannot get refs for: " + path - + ". This is not a Neo4jGraphPathKey instance!" ); - } - - final ConversionCache cache = new ConversionCache(); - - final Neo4jGraphPath gp = (Neo4jGraphPath) path; - final List> rels = convertToRelationships( gp, adminAccess, cache ); - final List refs = new ArrayList( rels.size() + 2 ); - for ( final ProjectRelationship rel : rels ) - { - if ( refs.isEmpty() ) - { - refs.add( rel.getDeclaring() ); - } - - refs.add( rel.getTarget() - .asProjectVersionRef() ); - } - - if ( refs.isEmpty() ) - { - final Node node = graph.getNodeById( gp.getStartNodeId() ); - final ProjectVersionRef ref = toProjectVersionRef( node, cache ); - if ( ref != null ) - { - refs.add( ref ); - } - } - - return refs; - } - - @Override - public GraphPath createPath( final ProjectRelationship... rels ) - { - if ( rels.length < 1 ) - { - return null; - } - - final Relationship[] rs = new Relationship[rels.length]; - for ( int i = 0; i < rels.length; i++ ) - { - final Relationship r = getRelationship( rels[i] ); - if ( r == null ) - { - return null; - } - - rs[i] = r; - } - - return new Neo4jGraphPath( rs ); - } - - @Override - public GraphPath createPath( final GraphPath parent, final ProjectRelationship rel ) - { - if ( parent != null && !( parent instanceof Neo4jGraphPath ) ) - { - throw new IllegalArgumentException( "Cannot get child path-key for: " + parent - + ". This is not a Neo4jGraphPathKey instance!" ); - } - - Relationship r = getRelationship( rel ); - if ( r == null ) - { - final Transaction tx = graph.beginTx(); - try - { - logger.debug( "Creating new node to account for missing project referenced in path: {}", r ); - - addRelationshipsInternal( rel ); - - // FIXME: Restore cycle detection somehow... - // if ( rejected != null && !rejected.isEmpty() ) - // { - // tx.failure(); - // throw new IllegalArgumentException( "Cannot create missing relationship for: " + rel + ". It creates a relationship cycle." ); - // } - - r = getRelationship( rel ); - - tx.success(); - if ( r == null ) - { - return null; - } - } - finally - { - tx.finish(); - } - } - - return new Neo4jGraphPath( (Neo4jGraphPath) parent, r ); - } - - @Override - public boolean registerView( final ViewParams params ) - { - if ( params == null ) - { - return false; - } - - if ( params.getRoots() == null || params.getRoots() - .isEmpty() ) - { - logger.info( "Cannot track membership in params! It has no root GAVs.\nView: {} (short id: {})", - params.getLongId(), params.getShortId() ); - return false; - } - - updateView( params, new ConversionCache() ); - - return true; - } - - private Node getViewNode( final ViewParams params ) - { - // if ( params.equals( globalView ) ) - // { - // return configNode; - // } - - final Index confIdx = graph.index() - .forNodes( CONFIG_NODES_IDX ); - - final IndexHits hits = confIdx.get( VIEW_ID, params.getShortId() ); - if ( hits.hasNext() ) - { - logger.debug( "View already registered: {} (short id: {})", params.getLongId(), params.getShortId() ); - return hits.next(); - } - else - { - logger.debug( "Registering new params: {} (short id: {})", params.getLongId(), params.getShortId() ); - - final Transaction tx = graph.beginTx(); - try - { - final Node paramsNode; - paramsNode = graph.createNode(); - Conversions.storeView( params, paramsNode ); - - confIdx.add( paramsNode, VIEW_ID, params.getShortId() ); - - logger.debug( "Setting cycle-detection PENDING for new paramsNode: {} of: {}", paramsNode, - params.getShortId() ); - Conversions.setCycleDetectionPending( paramsNode, true ); - Conversions.setMembershipDetectionPending( paramsNode, true ); - - final ViewIndexes indexes = new ViewIndexes( graph.index(), params ); - final Index cachedNodes = indexes.getCachedNodes(); - - for ( final ProjectVersionRef rootRef : params.getRoots() ) - { - Node rootNode = getNode( rootRef ); - if ( rootNode == null ) - { - logger.info( "Creating node for root: {}", rootRef ); - rootNode = newProjectNode( rootRef ); - } - - cachedNodes.add( rootNode, NID, rootNode.getId() ); - } - - tx.success(); - - return paramsNode; - } - finally - { - tx.finish(); - } - } - } - - @Override - public void registerViewSelection( final ViewParams params, final ProjectRef ref, - final ProjectVersionRef projectVersionRef ) - { - checkClosed(); - if ( !registerView( params ) ) - { - return; - } - - IndexHits nodeHits; - if ( ref instanceof ProjectVersionRef ) - { - nodeHits = graph.index() - .forNodes( BY_GAV_IDX ) - .get( GAV, ( (ProjectVersionRef) ref ).asProjectVersionRef() - .toString() ); - } - else - { - nodeHits = graph.index() - .forNodes( BY_GA_IDX ) - .get( GA, ref.asProjectRef() ); - } - - final Set viaNodes = new HashSet(); - for ( final Node node : nodeHits ) - { - viaNodes.add( node.getId() ); - } - - logger.debug( "Searching for sub-paths to de-select (via): {}", viaNodes ); - - final Set toUncacheNode = new HashSet(); - final Set toUncache = new HashSet(); - final Set toUnselect = new HashSet(); - - final Transaction tx = graph.beginTx(); - try - { - final SubPathsCollectingVisitor visitor = new SubPathsCollectingVisitor( viaNodes, adminAccess ); - collectAtlasRelationships( params, visitor, getRoots( params ), false, Uniqueness.RELATIONSHIP_GLOBAL ); - - for ( final Neo4jGraphPath path : visitor ) - { - boolean uncache = false; - for ( final Long id : path ) - { - final Relationship r = graph.getRelationshipById( id ); - - // first relationship in the sub-path. - if ( !uncache ) - { - logger.debug( "Uncaching subgraph: {}", r.getEndNode() ); - logger.debug( "Uncaching: {}", r ); - toUncache.add( r ); - uncache = true; - continue; - } - else - { - logger.debug( "Uncaching: {}", r ); - toUncacheNode.add( r.getStartNode() ); - toUncacheNode.add( r.getEndNode() ); - toUncache.add( r ); - continue; - } - } - } - - final ViewIndexes indexes = new ViewIndexes( graph.index(), params ); - final Index nodes = indexes.getCachedNodes(); - for ( final Node uncache : toUncacheNode ) - { - logger.debug( "Uncache: {}", uncache ); - nodes.remove( uncache ); - } - - final RelationshipIndex rels = indexes.getCachedRelationships(); - for ( final Relationship uncache : toUncache ) - { - logger.debug( "Uncache: {}", uncache ); - rels.remove( uncache ); - } - - final Node paramsNode = getViewNode( params ); - for ( final Relationship unsel : toUnselect ) - { - Conversions.removeSelectionByTarget( unsel.getId(), paramsNode ); - } - - Conversions.setMembershipDetectionPending( paramsNode, true ); - Conversions.setCycleDetectionPending( paramsNode, true ); - - tx.success(); - } - finally - { - tx.finish(); - } - } - - private void updateCaches( final Map> newRelationships ) - { - if ( newRelationships.isEmpty() ) - { - return; - } - - final Index confIdx = graph.index() - .forNodes( CONFIG_NODES_IDX ); - - final IndexHits hits = confIdx.query( VIEW_ID, "*" ); - - final ConversionCache cache = new ConversionCache(); - - Transaction tx = graph.beginTx(); - try - { - logger.debug( "Setting global cycle-detection as PENDING" ); - Conversions.setCycleDetectionPending( configNode, true ); - - tx.success(); - } - finally - { - tx.finish(); - } - - for ( final Node paramsNode : hits ) - { - final ViewParams params = Conversions.retrieveView( paramsNode, cache, adminAccess ); - logger.debug( "Updating params: {} ({})", params.getShortId(), paramsNode ); - - // if ( params == null || params.getShortId() - // .equals( globalView.getShortId() ) || params.getRoots() == null - // || params.getRoots() - // .isEmpty() ) - // { - // logger.debug( "nevermind; it's the global params." ); - // continue; - // } - - if ( getRoots( params, false ).isEmpty() ) - { - tx = graph.beginTx(); - try - { - Conversions.setCycleDetectionPending( paramsNode, true ); - // Conversions.setMembershipDetectionPending( paramsNode, true ); - tx.success(); - continue; - } - finally - { - tx.finish(); - } - } - - final ViewIndexes vi = new ViewIndexes( graph.index(), params ); - final ViewUpdater vu = new ViewUpdater( params, paramsNode, vi, cache, adminAccess ); - vu.cacheRoots( getRoots( params, false ) ); - if ( vu.processAddedRelationships( newRelationships ) ) - { - logger.debug( "{} ({}) marked for update.", params.getShortId(), paramsNode ); - } - else - { - logger.debug( "{} ({}) NOT marked for update.", params.getShortId(), paramsNode ); - } - } - } - - private static class GraphAdminImpl - implements GraphAdmin - { - - private final FileNeo4JGraphConnection driver; - - GraphAdminImpl( final FileNeo4JGraphConnection driver ) - { - this.driver = driver; - } - - @Override - public FileNeo4JGraphConnection getDriver() - { - return driver; - } - - @Override - public Relationship getRelationship( final long rid ) - { - return driver.graph.getRelationshipById( rid ); - } - - @Override - public Relationship select( final Relationship r, final ViewParams params, final Node paramsNode, - final GraphPathInfo paramsPathInfo, final Neo4jGraphPath paramsPath ) - { - return driver.select( r, params, paramsNode, paramsPathInfo, paramsPath ); - } - - @Override - public RelationshipIndex getRelationshipIndex( final String name ) - { - return driver.graph.index() - .forRelationships( name ); - } - - @Override - public Index getNodeIndex( final String name ) - { - return driver.graph.index() - .forNodes( name ); - } - - @Override - public Transaction beginTransaction() - { - return driver.graph.beginTx(); - } - - @Override - public boolean isSelection( final Relationship r, final Node paramsNode ) - { - return Conversions.getDeselectionTarget( r.getId(), paramsNode ) > -1; - } - - } - - @Override - public String getWorkspaceId() - { - return workspaceId; - } - - @Override - public void addProjectError( final ProjectVersionRef ref, final Throwable error ) - throws RelationshipGraphConnectionException - { - Node node = getNode( ref ); - if ( node == null ) - { - node = newProjectNode( ref ); - } - - Conversions.storeError( node, error ); - } - - @Override - public Throwable getProjectError( final ProjectVersionRef ref ) - { - final Node node = getNode( ref ); - if ( node == null ) - { - return null; - } - - return Conversions.getError( node ); - } - - @Override - public boolean hasProjectError( final ProjectVersionRef ref ) - { - final Node node = getNode( ref ); - if ( node == null ) - { - return false; - } - - return node.hasProperty( Conversions.PROJECT_ERROR ); - } - - @Override - public void clearProjectError( final ProjectVersionRef ref ) - throws RelationshipGraphConnectionException - { - final Node node = getNode( ref ); - if ( node == null || !node.hasProperty( Conversions.PROJECT_ERROR ) ) - { - return; - } - - node.removeProperty( Conversions.PROJECT_ERROR ); - } - - @Override - public Set> getDirectRelationshipsTo( final ViewParams params, final ProjectVersionRef to, - final boolean includeManagedInfo, - final RelationshipType... types ) - { - return getDirectRelationshipsFrom( params, to, includeManagedInfo, true, types ); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileNeo4jConnectionFactory.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileNeo4jConnectionFactory.java deleted file mode 100644 index c86beaf4..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileNeo4jConnectionFactory.java +++ /dev/null @@ -1,151 +0,0 @@ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.io.FileUtils; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FileNeo4jConnectionFactory - implements RelationshipGraphConnectionFactory -{ - - private final Map openConnections = - new HashMap(); - - private final File dbBaseDirectory; - - private final boolean useShutdownHook; - - public FileNeo4jConnectionFactory( final File dbBaseDirectory, final boolean useShutdownHook ) - { - this.dbBaseDirectory = dbBaseDirectory; - this.useShutdownHook = useShutdownHook; - } - - @Override - public synchronized RelationshipGraphConnection openConnection( final String workspaceId, final boolean create ) - throws RelationshipGraphConnectionException - { - final File db = new File( dbBaseDirectory, workspaceId ); - if ( !db.exists() ) - { - if ( !create ) - { - throw new RelationshipGraphConnectionException( "Workspace does not exist: {}.", workspaceId ); - } - else if ( !db.mkdirs() ) - { - throw new RelationshipGraphConnectionException( - "Failed to create workspace directory for: {}. (dir: {})", - workspaceId, db ); - } - // - // try - // { - // Thread.sleep( 20 ); - // } - // catch ( final InterruptedException e ) - // { - // Thread.currentThread() - // .interrupt(); - // return null; - // } - } - - FileNeo4JGraphConnection conn = openConnections.get( workspaceId ); - if ( conn == null ) - { - conn = new FileNeo4JGraphConnection( workspaceId, db, useShutdownHook, this ); - openConnections.put( workspaceId, conn ); - } - - return conn; - } - - @Override - public Set listWorkspaces() - { - return new HashSet( Arrays.asList( dbBaseDirectory.list() ) ); - } - - @Override - public void flush( final RelationshipGraphConnection connection ) - throws RelationshipGraphConnectionException - { - // TODO How do I flush the graph to disk while other views may be modifying it?? - } - - @Override - public boolean delete( final String workspaceId ) - throws RelationshipGraphConnectionException - { - final File db = new File( dbBaseDirectory, workspaceId ); - if ( !db.exists() || !db.isDirectory() ) - { - return false; - } - - boolean result = false; - try - { - FileUtils.forceDelete( db ); - result = db.exists(); - } - catch ( final IOException e ) - { - throw new RelationshipGraphConnectionException( "Failed to delete: %s. Reason: %s", e, db, e.getMessage() ); - } - - return result; - } - - @Override - public void close() - throws RelationshipGraphConnectionException - { - final Logger logger = LoggerFactory.getLogger( getClass() ); - - final Set failedClose = new HashSet(); - for ( final FileNeo4JGraphConnection conn : new HashSet( openConnections.values() ) ) - { - try - { - conn.close(); - } - catch ( final RelationshipGraphConnectionException e ) - { - failedClose.add( conn.getWorkspaceId() ); - logger.error( "Failed to close: " + conn.getWorkspaceId() + ".", e ); - } - } - - if ( !failedClose.isEmpty() ) - { - throw new RelationshipGraphConnectionException( "Failed to close: {}", new JoinString( ", ", failedClose ) ); - } - } - - public synchronized void connectionClosed( final String workspaceId ) - { - openConnections.remove( workspaceId ); - } - - @Override - public boolean exists( final String workspaceId ) - { - final File db = new File( dbBaseDirectory, workspaceId ); - return db.exists() && db.isDirectory(); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/GraphAdmin.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/GraphAdmin.java deleted file mode 100644 index d98deaeb..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/GraphAdmin.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Relationship; -import org.neo4j.graphdb.Transaction; -import org.neo4j.graphdb.index.Index; -import org.neo4j.graphdb.index.RelationshipIndex; - -public interface GraphAdmin -{ - - FileNeo4JGraphConnection getDriver(); - - Relationship getRelationship( long rid ); - - Relationship select( Relationship r, ViewParams view, Node viewNode, GraphPathInfo viewPathInfo, - Neo4jGraphPath viewPath ); - - RelationshipIndex getRelationshipIndex( String name ); - - Index getNodeIndex( String name ); - - Transaction beginTransaction(); - - boolean isSelection( Relationship r, Node viewNode ); - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/GraphRelType.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/GraphRelType.java deleted file mode 100644 index c0bc07d6..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/GraphRelType.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import java.util.HashSet; -import java.util.Set; - -import org.neo4j.graphdb.RelationshipType; - -public enum GraphRelType - implements RelationshipType -{ - PARENT( org.commonjava.maven.atlas.graph.rel.RelationshipType.PARENT ), - BOM( org.commonjava.maven.atlas.graph.rel.RelationshipType.BOM ), - C_DEPENDENCY( org.commonjava.maven.atlas.graph.rel.RelationshipType.DEPENDENCY ), - C_PLUGIN( org.commonjava.maven.atlas.graph.rel.RelationshipType.PLUGIN ), - C_PLUGIN_DEP( org.commonjava.maven.atlas.graph.rel.RelationshipType.PLUGIN_DEP ), - M_DEPENDENCY( org.commonjava.maven.atlas.graph.rel.RelationshipType.DEPENDENCY, true ), - M_PLUGIN( org.commonjava.maven.atlas.graph.rel.RelationshipType.PLUGIN, true ), - M_PLUGIN_DEP( org.commonjava.maven.atlas.graph.rel.RelationshipType.PLUGIN_DEP, true ), - EXTENSION( org.commonjava.maven.atlas.graph.rel.RelationshipType.EXTENSION ), - CYCLE, - CACHED_PATH_RELATIONSHIP, - CACHED_CYCLE_RELATIONSHIP; - - private org.commonjava.maven.atlas.graph.rel.RelationshipType atlasType; - - private boolean managed = false; - - private GraphRelType() - { - } - - private GraphRelType( final org.commonjava.maven.atlas.graph.rel.RelationshipType atlasType ) - { - this.atlasType = atlasType; - } - - private GraphRelType( final org.commonjava.maven.atlas.graph.rel.RelationshipType atlasType, final boolean managed ) - { - this.atlasType = atlasType; - this.managed = managed; - } - - public boolean isManaged() - { - return managed; - } - - public boolean isAtlasRelationship() - { - return atlasType != null; - } - - public org.commonjava.maven.atlas.graph.rel.RelationshipType atlasType() - { - return atlasType; - } - - public static GraphRelType map( final org.commonjava.maven.atlas.graph.rel.RelationshipType type, final boolean managed ) - { - for ( final GraphRelType mapper : values() ) - { - if ( mapper.atlasType == type && managed == mapper.managed ) - { - return mapper; - } - } - - return null; - } - - public static GraphRelType[] atlasRelationshipTypes() - { - final Set types = new HashSet(); - for ( final GraphRelType type : values() ) - { - if ( type.isAtlasRelationship() ) - { - types.add( type ); - } - } - - return types.toArray( new GraphRelType[types.size()] ); - } - - public static GraphRelType[] concreteAtlasRelationshipTypes() - { - final Set types = new HashSet(); - for ( final GraphRelType type : values() ) - { - if ( type.isAtlasRelationship() && !type.managed ) - { - types.add( type ); - } - } - - return types.toArray( new GraphRelType[types.size()] ); - } - - public static GraphRelType[] managedAtlasRelationshipTypes() - { - final Set types = new HashSet(); - for ( final GraphRelType type : values() ) - { - if ( type.isAtlasRelationship() && type.managed ) - { - types.add( type ); - } - } - - return types.toArray( new GraphRelType[types.size()] ); - } -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/Neo4JGraphConnection.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/Neo4JGraphConnection.java deleted file mode 100644 index 51cf5ede..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/Neo4JGraphConnection.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import java.util.Map; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.neo4j.cypher.javacompat.ExecutionResult; - -public interface Neo4JGraphConnection - extends RelationshipGraphConnection -{ - - ExecutionResult executeFrom( String cypher, ProjectVersionRef... roots ) - throws RelationshipGraphConnectionException; - - ExecutionResult executeFrom( String cypher, ProjectRelationship rootRel ) - throws RelationshipGraphConnectionException; - - ExecutionResult execute( String cypher ) - throws RelationshipGraphConnectionException; - - ExecutionResult executeFrom( String cypher, Map params, ProjectVersionRef... roots ) - throws RelationshipGraphConnectionException; - - ExecutionResult executeFrom( String cypher, Map params, ProjectRelationship rootRel ) - throws RelationshipGraphConnectionException; - - ExecutionResult execute( String cypher, Map params ) - throws RelationshipGraphConnectionException; - - // Node getNode( ProjectVersionRef ref ) - // throws GraphDriverException; - // - // Relationship getRelationship( ProjectRelationship rel ) - // throws GraphDriverException; - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/NodeType.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/NodeType.java deleted file mode 100644 index 4b18ccdc..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/NodeType.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -public enum NodeType -{ - - PROJECT, CYCLE; - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/PathComparator.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/PathComparator.java deleted file mode 100644 index f7eaf40f..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/PathComparator.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import java.util.Comparator; -import java.util.List; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipPathComparator; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.neo4j.graphdb.Path; - -public final class PathComparator - implements Comparator -{ - - public static final PathComparator INSTANCE = new PathComparator(); - - private final RelationshipPathComparator pathComparator = RelationshipPathComparator.INSTANCE; - - private final ConversionCache cache = new ConversionCache(); - - private PathComparator() - { - } - - @Override - public int compare( final Path first, final Path second ) - { - final List> firstRels = Conversions.convertToRelationships( first.relationships(), cache ); - final List> secondRels = Conversions.convertToRelationships( second.relationships(), cache ); - - return pathComparator.compare( firstRels, secondRels ); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/ViewIndexes.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/ViewIndexes.java deleted file mode 100644 index 8f600c7b..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/ViewIndexes.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.index.Index; -import org.neo4j.graphdb.index.IndexManager; -import org.neo4j.graphdb.index.RelationshipIndex; - -public class ViewIndexes -{ - - private static final String REL_CACHE_PREFIX = "rel_cache_for_"; - - private static final String NODE_CACHE_PREFIX = "node_cache_for_"; - - // private static final String SELECTION_CACHE_PREFIX = "selection_cache_for_"; - - private final IndexManager indexMgr; - - private final ViewParams view; - - public ViewIndexes( final IndexManager indexMgr, final ViewParams view ) - { - this.indexMgr = indexMgr; - this.view = view; - } - - public RelationshipIndex getCachedRelationships() - { - return indexMgr.forRelationships( REL_CACHE_PREFIX + view.getShortId() ); - } - - // public RelationshipIndex getSelections() - // { - // return indexMgr.forRelationships( SELECTION_CACHE_PREFIX + view.getShortId() ); - // } - - public Index getCachedNodes() - { - return indexMgr.forNodes( NODE_CACHE_PREFIX + view.getShortId() ); - } - - public void delete() - { - getCachedRelationships().delete(); - // getSelections().delete(); - getCachedNodes().delete(); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/ConversionCache.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/ConversionCache.java deleted file mode 100644 index 5f95de02..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/ConversionCache.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.io; - -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.codec.digest.DigestUtils; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Relationship; - -public class ConversionCache -{ - - private Map>> relationships; - - private Map> gavs; - - private Map> serializedObjects; - - public ProjectRelationship getRelationship( final Relationship rel ) - { - return getRelationship( rel.getId() ); - } - - public ProjectRelationship getRelationship( final long rid ) - { - if ( relationships == null ) - { - return null; - } - - final WeakReference> reference = relationships.get( rid ); - if ( reference == null ) - { - return null; - } - - return reference.get(); - } - - public void cache( final Relationship rel, final ProjectRelationship r ) - { - if ( relationships == null ) - { - relationships = new HashMap>>(); - } - - relationships.put( rel.getId(), new WeakReference>( r ) ); - } - - public ProjectVersionRef getProjectVersionRef( final Node node ) - { - return getProjectVersionRef( node.getId() ); - } - - public ProjectVersionRef getProjectVersionRef( final long nid ) - { - if ( gavs == null ) - { - return null; - } - - final WeakReference reference = gavs.get( nid ); - if ( reference == null ) - { - return null; - } - - return reference.get(); - } - - public void cache( final Node node, final ProjectVersionRef ref ) - { - if ( gavs == null ) - { - gavs = new HashMap>(); - } - - gavs.put( node.getId(), new WeakReference( ref ) ); - } - - public T getSerializedObject( final byte[] data, final Class type ) - { - if ( serializedObjects != null ) - { - final String key = DigestUtils.shaHex( data ); - final WeakReference reference = serializedObjects.get( key ); - if ( reference == null ) - { - return null; - } - - final Object value = reference.get(); - if ( value != null ) - { - return type.cast( value ); - } - } - - return null; - } - - public void cache( final byte[] data, final Object value ) - { - if ( serializedObjects == null ) - { - serializedObjects = new HashMap>(); - } - - final String key = DigestUtils.shaHex( data ); - serializedObjects.put( key, new WeakReference( value ) ); - } -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/Conversions.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/Conversions.java deleted file mode 100644 index b65c5e62..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/Conversions.java +++ /dev/null @@ -1,1175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.io; - -import static org.apache.commons.lang.StringUtils.join; -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.POM_ROOT_URI; -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.UNKNOWN_SOURCE_URI; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.output.ByteArrayOutputStream; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.rel.BomRelationship; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ExtensionRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginDependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphRelType; -import org.commonjava.maven.atlas.graph.spi.neo4j.NodeType; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.PropertyContainer; -import org.neo4j.graphdb.Relationship; - -public final class Conversions -{ - - public static final String RELATIONSHIP_ID = "relationship_id"; - - public static final String GROUP_ID = "groupId"; - - public static final String ARTIFACT_ID = "artifactId"; - - public static final String VERSION = "version"; - - public static final String GAV = "gav"; - - public static final String GA = "ga"; - - public static final String INDEX = "index"; - - public static final String IS_REPORTING_PLUGIN = "reporting"; - - public static final String IS_MANAGED = "managed"; - - public static final String PLUGIN_GROUP_ID = "plugin_groupId"; - - public static final String PLUGIN_ARTIFACT_ID = "plugin_artifactId"; - - public static final String TYPE = "type"; - - public static final String CLASSIFIER = "classifier"; - - public static final String SCOPE = "scope"; - - public static final String OPTIONAL = "optional"; - - public static final String EXCLUDES = "excludes"; - - public static final String CYCLE_ID = "cycle_id"; - - public static final String CYCLE_RELATIONSHIPS = "relationship_participants"; - - public static final String CYCLE_PROJECTS = "project_participants"; - - public static final String PROJECT_ERROR = "_error"; - - private static final String METADATA_PREFIX = "_metadata_"; - - public static final String NODE_TYPE = "_node_type"; - - public static final String CYCLE_MEMBERSHIP = "cycle_membership"; - - public static final String VARIABLE = "_variable"; - - public static final String CONNECTED = "_connected"; - - public static final String CYCLE_INJECTION = "_cycle_injection"; - - public static final String CYCLES_INJECTED = "_cycles"; - - public static final String SOURCE_URI = "source_uri"; - - public static final String POM_LOCATION_URI = "pom_location_uri"; - - public static final String LAST_ACCESS_DATE = "last_access"; - - // graph-level configuration. - - public static final String LAST_ACCESS = "last_access"; - - public static final String ACTIVE_POM_LOCATIONS = "active-pom-locations"; - - public static final String ACTIVE_SOURCES = "active-pom-sources"; - - public static final String CONFIG_PROPERTY_PREFIX = "_p_"; - - public static final String VIEW_SHORT_ID = "view_sid"; - - private static final String VIEW_DATA = "view_data"; - - // cached path tracking...ONLY handled by Conversions, since the info is inlined. - - private static final String CYCLE_PATH_PREFIX = "cached_cycle_"; - - // handled by other things, like updaters. - - public static final String RID = "rel_id"; - - public static final String NID = "node_id"; - - public static final String CONFIG_ID = "config_id"; - - public static final String VIEW_ID = "view_id"; - - public static final String CYCLE_DETECTION_PENDING = "cycle_detect_pending"; - - private static final String MEMBERSHIP_DETECTION_PENDING = "member_detect_pending"; - - private Conversions() - { - } - - public static int countArrayElements( final String property, final PropertyContainer container ) - { - if ( !container.hasProperty( property ) ) - { - return -1; - } - - final Object value = container.getProperty( property ); - if ( value.getClass() - .isArray() ) - { - final Object[] elements = (Object[]) value; - return elements.length; - } - - return 1; - } - - public static List convertToProjects( final Iterable nodes, final ConversionCache cache ) - { - final List refs = new ArrayList(); - for ( final Node node : nodes ) - { - if ( node.getId() == 0 ) - { - continue; - } - - if ( !Conversions.isType( node, NodeType.PROJECT ) ) - { - continue; - } - - refs.add( Conversions.toProjectVersionRef( node, cache ) ); - } - - return refs; - } - - public static List> convertToRelationships( final Iterable relationships, final ConversionCache cache ) - { - final List> rels = new ArrayList>(); - for ( final Relationship relationship : relationships ) - { - final ProjectRelationship rel = Conversions.toProjectRelationship( relationship, cache ); - if ( rel != null ) - { - rels.add( rel ); - } - } - - return rels; - } - - public static List> convertToRelationships( final Iterable relationships, final GraphAdmin admin, - final ConversionCache cache ) - { - final List> rels = new ArrayList>(); - for ( final Long rid : relationships ) - { - final Relationship relationship = admin.getRelationship( rid ); - final ProjectRelationship rel = Conversions.toProjectRelationship( relationship, cache ); - if ( rel != null ) - { - rels.add( rel ); - } - } - - return rels; - } - - public static void toNodeProperties( final ProjectVersionRef ref, final Node node, final boolean connected ) - { - final String g = ref.getGroupId(); - final String a = ref.getArtifactId(); - final String v = ref.getVersionString(); - - if ( empty( g ) || empty( a ) || empty( v ) ) - { - throw new IllegalArgumentException( String.format( "GAV cannot contain nulls: %s:%s:%s", g, a, v ) ); - } - - node.setProperty( NODE_TYPE, NodeType.PROJECT.name() ); - node.setProperty( ARTIFACT_ID, a ); - node.setProperty( GROUP_ID, g ); - node.setProperty( VERSION, v ); - node.setProperty( GAV, ref.toString() ); - - if ( ref.isVariableVersion() ) - { - node.setProperty( VARIABLE, true ); - } - - markConnected( node, connected ); - } - - public static boolean isAtlasType( final Relationship rel ) - { - return GraphRelType.valueOf( rel.getType() - .name() ) - .isAtlasRelationship(); - } - - public static boolean isType( final Node node, final NodeType type ) - { - final String nt = getStringProperty( NODE_TYPE, node ); - return nt != null && type == NodeType.valueOf( nt ); - } - - // public static ProjectVersionRef toProjectVersionRef( final Node node ) - // { - // return toProjectVersionRef( node, null ); - // } - - public static ProjectVersionRef toProjectVersionRef( final Node node, final ConversionCache cache ) - { - if ( node == null ) - { - return null; - } - - if ( cache != null ) - { - final ProjectVersionRef ref = cache.getProjectVersionRef( node ); - if ( ref != null ) - { - return ref; - } - } - - if ( !isType( node, NodeType.PROJECT ) ) - { - throw new IllegalArgumentException( "Node " + node.getId() + " is not a project reference." ); - } - - final String g = getStringProperty( GROUP_ID, node ); - final String a = getStringProperty( ARTIFACT_ID, node ); - final String v = getStringProperty( VERSION, node ); - - if ( empty( g ) || empty( a ) || empty( v ) ) - { - throw new IllegalArgumentException( String.format( "GAV cannot contain nulls: %s:%s:%s", g, a, v ) ); - } - - final ProjectVersionRef result = new ProjectVersionRef( g, a, v ); - if ( cache != null ) - { - cache.cache( node, result ); - } - - return result; - } - - private static boolean empty( final String val ) - { - return val == null || val.trim() - .length() < 1; - } - - @SuppressWarnings( "incomplete-switch" ) - public static void toRelationshipProperties( final ProjectRelationship rel, final Relationship relationship ) - { - relationship.setProperty( INDEX, rel.getIndex() ); - relationship.setProperty( SOURCE_URI, toStringArray( rel.getSources() ) ); - relationship.setProperty( POM_LOCATION_URI, rel.getPomLocation() - .toString() ); - - switch ( rel.getType() ) - { - case DEPENDENCY: - { - final DependencyRelationship specificRel = (DependencyRelationship) rel; - toRelationshipProperties( (ArtifactRef) rel.getTarget(), relationship ); - relationship.setProperty( IS_MANAGED, specificRel.isManaged() ); - relationship.setProperty( SCOPE, specificRel.getScope() - .realName() ); - - final Set excludes = specificRel.getExcludes(); - if ( excludes != null && !excludes.isEmpty() ) - { - final StringBuilder sb = new StringBuilder(); - for ( final ProjectRef exclude : excludes ) - { - if ( sb.length() > 0 ) - { - sb.append( "," ); - } - - sb.append( exclude.getGroupId() ) - .append( ":" ) - .append( exclude.getArtifactId() ); - } - - relationship.setProperty( EXCLUDES, sb.toString() ); - } - - break; - } - case PLUGIN_DEP: - { - toRelationshipProperties( (ArtifactRef) rel.getTarget(), relationship ); - - final PluginDependencyRelationship specificRel = (PluginDependencyRelationship) rel; - - final ProjectRef plugin = specificRel.getPlugin(); - relationship.setProperty( PLUGIN_ARTIFACT_ID, plugin.getArtifactId() ); - relationship.setProperty( PLUGIN_GROUP_ID, plugin.getGroupId() ); - relationship.setProperty( IS_MANAGED, specificRel.isManaged() ); - - break; - } - case PLUGIN: - { - final PluginRelationship specificRel = (PluginRelationship) rel; - relationship.setProperty( IS_MANAGED, specificRel.isManaged() ); - relationship.setProperty( IS_REPORTING_PLUGIN, specificRel.isReporting() ); - - break; - } - } - } - - public static String[] toStringArray( final Collection sources ) - { - final Set result = new LinkedHashSet( sources.size() ); - for ( final Object object : sources ) - { - if ( object == null ) - { - continue; - } - - result.add( object.toString() ); - } - - return result.toArray( new String[result.size()] ); - } - - // public static ProjectRelationship toProjectRelationship( final Relationship rel ) - // { - // return toProjectRelationship( rel, null ); - // } - - public static ProjectRelationship toProjectRelationship( final Relationship rel, final ConversionCache cache ) - { - if ( rel == null ) - { - return null; - } - - if ( cache != null ) - { - final ProjectRelationship r = cache.getRelationship( rel ); - if ( r != null ) - { - return r; - } - } - - final GraphRelType mapper = GraphRelType.valueOf( rel.getType() - .name() ); - - // LOGGER.debug( "Converting relationship of type: {} (atlas type: {})", mapper, - // mapper.atlasType() ); - - if ( !mapper.isAtlasRelationship() ) - { - return null; - } - - if ( rel.getStartNode() == null || rel.getEndNode() == null || !isType( rel.getStartNode(), NodeType.PROJECT ) - || !isType( rel.getEndNode(), NodeType.PROJECT ) ) - { - return null; - } - - final ProjectVersionRef from = toProjectVersionRef( rel.getStartNode(), cache ); - final ProjectVersionRef to = toProjectVersionRef( rel.getEndNode(), cache ); - final int index = getIntegerProperty( INDEX, rel ); - final Set source = getURISetProperty( SOURCE_URI, rel, UNKNOWN_SOURCE_URI ); - final URI pomLocation = getURIProperty( POM_LOCATION_URI, rel, POM_ROOT_URI ); - - ProjectRelationship result = null; - switch ( mapper.atlasType() ) - { - case DEPENDENCY: - { - final ArtifactRef artifact = toArtifactRef( to, rel ); - final boolean managed = getBooleanProperty( IS_MANAGED, rel ); - final String scopeStr = getStringProperty( SCOPE, rel ); - final DependencyScope scope = DependencyScope.getScope( scopeStr ); - - final String excludeStr = getStringProperty( EXCLUDES, rel ); - final Set excludes = new HashSet(); - if ( excludeStr != null ) - { - final String[] e = excludeStr.split( "\\s*,\\s*" ); - for ( final String ex : e ) - { - final String[] parts = ex.split( ":" ); - if ( parts.length != 2 ) - { - // LOGGER.error( "In: {} -> {} skipping invalid exclude specification: '{}'", from, artifact, ex ); - } - else - { - excludes.add( new ProjectRef( parts[0], parts[1] ) ); - } - } - } - - result = - new DependencyRelationship( source, pomLocation, from, artifact, scope, index, managed, excludes.toArray( new ProjectRef[] {} ) ); - break; - } - case PLUGIN_DEP: - { - final ArtifactRef artifact = toArtifactRef( to, rel ); - final String pa = getStringProperty( PLUGIN_ARTIFACT_ID, rel ); - final String pg = getStringProperty( PLUGIN_GROUP_ID, rel ); - final boolean managed = getBooleanProperty( IS_MANAGED, rel ); - - result = new PluginDependencyRelationship( source, pomLocation, from, new ProjectRef( pg, pa ), artifact, index, managed ); - break; - } - case PLUGIN: - { - final boolean managed = getBooleanProperty( IS_MANAGED, rel ); - final boolean reporting = getBooleanProperty( IS_REPORTING_PLUGIN, rel ); - - result = new PluginRelationship( source, pomLocation, from, to, index, managed, reporting ); - break; - } - case EXTENSION: - { - result = new ExtensionRelationship( source, from, to, index ); - break; - } - case BOM: - { - result = new BomRelationship( source, from, to, index ); - break; - } - case PARENT: - { - result = new ParentRelationship( source, from, to ); - break; - } - default: - { - throw new IllegalArgumentException( "I don't know how to construct the atlas relationship for type: " - + mapper.atlasType() ); - } - } - - if ( result != null && cache != null ) - { - cache.cache( rel, result ); - } - - // LOGGER.debug( "Returning project relationship: {}", result ); - return result; - } - - public static String id( final ProjectRelationship rel ) - { - return DigestUtils.shaHex( rel.toString() ); - } - - private static ArtifactRef toArtifactRef( final ProjectVersionRef ref, final Relationship rel ) - { - if ( ref == null ) - { - return null; - } - - final String type = getStringProperty( TYPE, rel ); - final String classifier = getStringProperty( CLASSIFIER, rel ); - final boolean optional = getBooleanProperty( OPTIONAL, rel ); - - return new ArtifactRef( ref, type, classifier, optional ); - } - - private static void toRelationshipProperties( final ArtifactRef target, final Relationship relationship ) - { - relationship.setProperty( OPTIONAL, target.isOptional() ); - relationship.setProperty( TYPE, target.getType() ); - if ( target.getClassifier() != null ) - { - relationship.setProperty( CLASSIFIER, target.getClassifier() ); - } - } - - public static String getStringProperty( final String prop, final PropertyContainer container ) - { - if ( container.hasProperty( prop ) ) - { - return (String) container.getProperty( prop ); - } - return null; - } - - public static Set getURISetProperty( final String prop, final PropertyContainer container, final URI defaultValue ) - { - final Set result = new HashSet(); - - if ( container.hasProperty( prop ) ) - { - final String[] uris = (String[]) container.getProperty( prop ); - for ( final String uri : uris ) - { - try - { - final URI u = new URI( uri ); - if ( !result.contains( u ) ) - { - result.add( u ); - } - } - catch ( final URISyntaxException e ) - { - } - } - } - - if ( defaultValue != null && result.isEmpty() ) - { - result.add( defaultValue ); - } - - return result; - } - - public static void addToURISetProperty( final Collection uris, final String prop, final PropertyContainer container ) - { - if ( uris == null || uris.isEmpty() ) - { - return; - } - - final Set existing = getURISetProperty( prop, container, null ); - for ( final URI uri : uris ) - { - existing.add( uri ); - } - - container.setProperty( prop, toStringArray( existing ) ); - } - - public static void removeFromURISetProperty( final Collection uris, final String prop, final PropertyContainer container ) - { - if ( uris == null || uris.isEmpty() || !container.hasProperty( prop ) ) - { - return; - } - - final Set existing = getURISetProperty( prop, container, null ); - for ( final URI uri : uris ) - { - existing.remove( uri ); - } - - if ( existing.isEmpty() ) - { - container.removeProperty( prop ); - } - else - { - container.setProperty( prop, toStringArray( existing ) ); - } - } - - public static URI getURIProperty( final String prop, final PropertyContainer container, final URI defaultValue ) - { - URI result = defaultValue; - - if ( container.hasProperty( prop ) ) - { - try - { - result = new URI( (String) container.getProperty( prop ) ); - } - catch ( final URISyntaxException e ) - { - } - } - - return result; - } - - public static Boolean getBooleanProperty( final String prop, final PropertyContainer container ) - { - if ( container.hasProperty( prop ) ) - { - return (Boolean) container.getProperty( prop ); - } - return null; - } - - public static Boolean getBooleanProperty( final String prop, final PropertyContainer container, final Boolean defaultValue ) - { - if ( container.hasProperty( prop ) ) - { - return (Boolean) container.getProperty( prop ); - } - - return defaultValue; - } - - public static Integer getIntegerProperty( final String prop, final PropertyContainer container ) - { - if ( container.hasProperty( prop ) ) - { - return (Integer) container.getProperty( prop ); - } - return null; - } - - public static Integer getIntegerProperty( final String prop, final PropertyContainer container, - final int defaultValue ) - { - if ( container.hasProperty( prop ) ) - { - return (Integer) container.getProperty( prop ); - } - - return defaultValue; - } - - public static Long getLongProperty( final String prop, final PropertyContainer container, final long defaultValue ) - { - if ( container.hasProperty( prop ) ) - { - return (Long) container.getProperty( prop ); - } - - return defaultValue; - } - - public static String setConfigProperty( final String key, final String value, final PropertyContainer container ) - { - final String pkey = CONFIG_PROPERTY_PREFIX + key; - final String old = container.hasProperty( pkey ) ? (String) container.getProperty( pkey ) : null; - - container.setProperty( pkey, value ); - - return old; - } - - public static String removeConfigProperty( final String key, final PropertyContainer container ) - { - final String pkey = CONFIG_PROPERTY_PREFIX + key; - String old = null; - if ( container.hasProperty( pkey ) ) - { - old = (String) container.getProperty( pkey ); - - container.removeProperty( pkey ); - } - - return old; - } - - public static String getConfigProperty( final String key, final PropertyContainer container, final String defaultValue ) - { - final String result = getStringProperty( CONFIG_PROPERTY_PREFIX + key, container ); - - return result == null ? defaultValue : result; - } - - public static void setMetadata( final String key, final String value, final PropertyContainer container ) - { - container.setProperty( METADATA_PREFIX + key, value ); - } - - public static void setMetadata( final Map metadata, final PropertyContainer container ) - { - final Map metadataMap = getMetadataMap( container ); - - if ( metadataMap != null ) - { - for ( final String key : metadataMap.keySet() ) - { - container.removeProperty( key ); - } - } - - for ( final Map.Entry entry : metadata.entrySet() ) - { - container.setProperty( METADATA_PREFIX + entry.getKey(), entry.getValue() ); - } - } - - public static Map getMetadataMap( final PropertyContainer container ) - { - return getMetadataMap( container, null ); - } - - public static Map getMetadataMap( final PropertyContainer container, final Set matching ) - { - final Iterable keys = container.getPropertyKeys(); - final Map md = new HashMap(); - for ( final String key : keys ) - { - if ( !key.startsWith( METADATA_PREFIX ) ) - { - continue; - } - - final String k = key.substring( METADATA_PREFIX.length() ); - if ( matching != null && !matching.contains( k ) ) - { - continue; - } - - final String value = getStringProperty( key, container ); - - md.put( k, value ); - } - - return md.isEmpty() ? null : md; - } - - public static String getMetadata( final String key, final PropertyContainer container ) - { - return getStringProperty( METADATA_PREFIX + key, container ); - } - - public static void toNodeProperties( final String cycleId, final String rawCycleId, final Set refs, final Node node ) - { - node.setProperty( NODE_TYPE, NodeType.CYCLE.name() ); - node.setProperty( CYCLE_ID, cycleId ); - node.setProperty( CYCLE_RELATIONSHIPS, rawCycleId ); - node.setProperty( CYCLE_PROJECTS, join( refs, "," ) ); - } - - public static boolean isConnected( final Node node ) - { - return getBooleanProperty( CONNECTED, node ); - } - - public static void markConnected( final Node node, final boolean connected ) - { - // LOGGER.info( "Marking as connected (non-missing): {}", node.getProperty( GAV ) ); - node.setProperty( CONNECTED, connected ); - } - - public static void markCycleInjection( final Relationship relationship, final Set> cycles ) - { - relationship.setProperty( CYCLE_INJECTION, true ); - final List collapsed = new ArrayList(); - final Set> existing = getInjectedCycles( relationship ); - if ( existing != null && !existing.isEmpty() ) - { - for ( final List cycle : existing ) - { - if ( !collapsed.isEmpty() ) - { - collapsed.add( -1L ); - } - - collapsed.addAll( cycle ); - } - } - - for ( final List cycle : cycles ) - { - if ( existing.contains( cycle ) ) - { - continue; - } - - if ( !collapsed.isEmpty() ) - { - collapsed.add( -1L ); - } - - boolean containsGivenRelationship = false; - for ( final Relationship r : cycle ) - { - final long rid = r.getId(); - - collapsed.add( rid ); - if ( rid == relationship.getId() ) - { - containsGivenRelationship = true; - } - } - - if ( !containsGivenRelationship ) - { - collapsed.add( relationship.getId() ); - } - } - - final long[] arry = new long[collapsed.size()]; - int i = 0; - for ( final Long l : collapsed ) - { - arry[i] = l; - i++; - } - - relationship.setProperty( CYCLES_INJECTED, arry ); - } - - public static Set> getInjectedCycles( final Relationship relationship ) - { - final Set> cycles = new HashSet>(); - - if ( relationship.hasProperty( CYCLES_INJECTED ) ) - { - final long[] collapsed = (long[]) relationship.getProperty( CYCLES_INJECTED ); - - List currentCycle = new ArrayList(); - for ( final long id : collapsed ) - { - if ( id == -1 ) - { - if ( !currentCycle.isEmpty() ) - { - cycles.add( currentCycle ); - currentCycle = new ArrayList(); - } - } - else - { - currentCycle.add( id ); - } - } - - if ( !currentCycle.isEmpty() ) - { - cycles.add( currentCycle ); - } - } - - return cycles; - } - - public static void removeProperty( final String key, final PropertyContainer container ) - { - if ( container.hasProperty( key ) ) - { - container.removeProperty( key ); - } - } - - public static Set

toProjectedSet( final Iterable src, final Projector projector ) - { - final Set

set = new HashSet

(); - for ( final T t : src ) - { - set.add( projector.project( t ) ); - } - - return set; - } - - public static Set toSet( final Iterable src ) - { - final Set set = new HashSet(); - for ( final T t : src ) - { - set.add( t ); - } - - return set; - } - - public static List toList( final Iterable src ) - { - final List set = new ArrayList(); - for ( final T t : src ) - { - set.add( t ); - } - - return set; - } - - public static void cloneRelationshipProperties( final Relationship from, final Relationship to ) - { - final Iterable keys = from.getPropertyKeys(); - for ( final String key : keys ) - { - to.setProperty( key, from.getProperty( key ) ); - } - } - - public static void storeCachedCyclePath( final CyclePath path, final Node viewNode ) - { - viewNode.setProperty( CYCLE_PATH_PREFIX + path.getKey(), path.getRelationshipIds() ); - } - - public static Set getCachedCyclePaths( final Node viewNode ) - { - final Set cycles = new HashSet(); - for ( final String key : viewNode.getPropertyKeys() ) - { - if ( key.startsWith( CYCLE_PATH_PREFIX ) ) - { - final long[] ids = (long[]) viewNode.getProperty( key ); - cycles.add( new CyclePath( ids ) ); - } - } - - return cycles; - } - - public static void storeView( final ViewParams params, final Node viewNode ) - { - viewNode.setProperty( Conversions.VIEW_SHORT_ID, params.getShortId() ); - - ObjectOutputStream oos = null; - try - { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - oos = new ObjectOutputStream( baos ); - oos.writeObject( params ); - - viewNode.setProperty( VIEW_DATA, baos.toByteArray() ); - } - catch ( final IOException e ) - { - throw new IllegalStateException( "Cannot construct ObjectOutputStream to wrap ByteArrayOutputStream!", e ); - } - finally - { - IOUtils.closeQuietly( oos ); - } - } - - // public static GraphView retrieveView( final Node viewNode, final AbstractNeo4JEGraphDriver driver ) - // { - // return retrieveView( viewNode, null, driver ); - // } - - public static ViewParams retrieveView( final Node viewNode, final ConversionCache cache, final GraphAdmin maint ) - { - if ( !viewNode.hasProperty( VIEW_DATA ) ) - { - return null; - } - - final byte[] data = (byte[]) viewNode.getProperty( VIEW_DATA ); - - if ( cache != null ) - { - final ViewParams view = cache.getSerializedObject( data, ViewParams.class ); - if ( view != null ) - { - return view; - } - } - - ObjectInputStream ois = null; - try - { - ois = new ObjectInputStream( new ByteArrayInputStream( data ) ); - final ViewParams view = (ViewParams) ois.readObject(); - - if ( cache != null ) - { - cache.cache( data, view ); - } - - return view; - } - catch ( final IOException e ) - { - throw new IllegalStateException( "Cannot construct ObjectInputStream to wrap ByteArrayInputStream containing " + data.length + " bytes!", - e ); - } - catch ( final ClassNotFoundException e ) - { - throw new IllegalStateException( "Cannot read ViewParams. A class was missing: " + e.getMessage(), e ); - } - finally - { - IOUtils.closeQuietly( ois ); - } - } - - public static boolean isCycleDetectionPending( final Node viewNode ) - { - return getBooleanProperty( CYCLE_DETECTION_PENDING, viewNode, Boolean.FALSE ); - } - - public static void setCycleDetectionPending( final Node viewNode, final boolean pending ) - { - viewNode.setProperty( CYCLE_DETECTION_PENDING, pending ); - } - - public static boolean isMembershipDetectionPending( final Node viewNode ) - { - return getBooleanProperty( MEMBERSHIP_DETECTION_PENDING, viewNode, Boolean.FALSE ); - } - - public static void setMembershipDetectionPending( final Node viewNode, final boolean pending ) - { - viewNode.setProperty( MEMBERSHIP_DETECTION_PENDING, pending ); - } - - private static final String SELECTION_ORIGIN_PREFIX = "_selection_origin_"; - - private static final String DESELECTION_TARGET_PREFIX = "_deselection_target_"; - - public static final String ATLAS_RELATIONSHIP_COUNT = "_atlas_relationship_count"; - - public static final String ATLAS_RELATIONSHIP_INDEX = "_atlas_relationship_index"; - - public static long getDeselectionTarget( final long originRid, final Node viewNode ) - { - return getLongProperty( DESELECTION_TARGET_PREFIX + originRid, viewNode, -1 ); - } - - public static long getSelectionOrigin( final long targetRid, final Node viewNode ) - { - return getLongProperty( SELECTION_ORIGIN_PREFIX + targetRid, viewNode, -1 ); - } - - public static void setSelection( final long originRid, final long targetRid, final Node viewNode ) - { - viewNode.setProperty( DESELECTION_TARGET_PREFIX + originRid, targetRid ); - viewNode.setProperty( SELECTION_ORIGIN_PREFIX + targetRid, originRid ); - } - - public static void removeSelectionByTarget( final long targetRid, final Node viewNode ) - { - final String selKey = SELECTION_ORIGIN_PREFIX + targetRid; - final long originRid = getLongProperty( selKey, viewNode, -1 ); - - if ( originRid > -1 ) - { - viewNode.removeProperty( selKey ); - } - else - { - return; - } - - final String deKey = DESELECTION_TARGET_PREFIX + originRid; - if ( viewNode.hasProperty( deKey ) ) - { - viewNode.removeProperty( deKey ); - } - } - - public static void removeSelectionByOrigin( final long originRid, final Node viewNode ) - { - final String deKey = DESELECTION_TARGET_PREFIX + originRid; - final long targetRid = getLongProperty( deKey, viewNode, -1 ); - if ( targetRid > -1 ) - { - viewNode.removeProperty( deKey ); - } - else - { - return; - } - - final String selKey = SELECTION_ORIGIN_PREFIX + targetRid; - if ( viewNode.hasProperty( selKey ) ) - { - viewNode.removeProperty( selKey ); - } - } - - public static void storeError( final Node node, final Throwable error ) - { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = null; - try - { - oos = new ObjectOutputStream( baos ); - oos.writeObject( error ); - - node.setProperty( PROJECT_ERROR, baos.toByteArray() ); - } - catch ( final IOException e ) - { - throw new IllegalStateException( "Cannot construct ObjectOutputStream to wrap ByteArrayOutputStream!", e ); - } - finally - { - IOUtils.closeQuietly( oos ); - } - } - - public static Throwable getError( final Node node ) - { - if ( !node.hasProperty( PROJECT_ERROR ) ) - { - return null; - } - - final byte[] data = (byte[]) node.getProperty( PROJECT_ERROR ); - ObjectInputStream ois = null; - try - { - ois = new ObjectInputStream( new ByteArrayInputStream( data ) ); - return (Throwable) ois.readObject(); - } - catch ( final IOException e ) - { - throw new IllegalStateException( - "Cannot construct ObjectInputStream to wrap ByteArrayInputStream containing " - + data.length + " bytes!", e ); - } - catch ( final ClassNotFoundException e ) - { - throw new IllegalStateException( "Cannot read Throwable. A class was missing: " + e.getMessage(), e ); - } - finally - { - IOUtils.closeQuietly( ois ); - } - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/NodeIdProjector.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/NodeIdProjector.java deleted file mode 100644 index 3078eeda..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/NodeIdProjector.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.io; - -import org.neo4j.graphdb.Node; - -public class NodeIdProjector - implements Projector -{ - - public Long project( final Node item ) - { - return item.getId(); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/Projector.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/Projector.java deleted file mode 100644 index 59bc2cb8..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/Projector.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.io; - -public interface Projector -{ - - P project( T item ); - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/RelationshipIdProjector.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/RelationshipIdProjector.java deleted file mode 100644 index 004b393d..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/io/RelationshipIdProjector.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.io; - -import org.neo4j.graphdb.Relationship; - -public class RelationshipIdProjector - implements Projector -{ - - public Long project( final Relationship item ) - { - return item.getId(); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/model/CyclePath.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/model/CyclePath.java deleted file mode 100644 index a270a0c9..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/model/CyclePath.java +++ /dev/null @@ -1,328 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.model; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; - -public class CyclePath - implements Iterable -{ - - public static final class CycleIterator - implements Iterator - { - - private final long[] ids; - - private int next; - - private final int start; - - public CycleIterator( final long[] ids, final int entryPoint ) - { - this.ids = ids; - start = entryPoint; - next = entryPoint; - } - - @Override - public boolean hasNext() - { - if ( next >= ids.length ) - { - if ( start > 0 ) - { - next = 0; - return true; - } - - return false; - } - else if ( next == -1 ) - { - return false; - } - - return true; - } - - @Override - public Long next() - { - if ( hasNext() ) - { - final long id = ids[next++]; - if ( next == start ) - { - next = -1; - } - - return id; - } - else if ( next == start ) - { - throw new IndexOutOfBoundsException( next + " is the starting point for this iteration!" ); - } - - throw new IndexOutOfBoundsException( next + " is the next index, but the array has only " + ids.length - + " items!" ); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException( "Cannot remove id; CyclePath is immutable." ); - } - - } - - private int entryPoint = 0; - - private final long[] ids; - - public CyclePath( final long[] ids ) - { - this.ids = ids; - } - - public CyclePath( final List ids ) - { - this.ids = new long[ids.size()]; - for ( int i = 0; i < ids.size(); i++ ) - { - this.ids[i] = ids.get( i ); - } - } - - public CyclePath( final Path path ) - { - final List ids = new ArrayList(); - for ( final Relationship r : path.relationships() ) - { - ids.add( r.getId() ); - } - - this.ids = new long[ids.size()]; - for ( int i = 0; i < ids.size(); i++ ) - { - this.ids[i] = ids.get( i ); - } - } - - public void setEntryPoint( final long entryPoint ) - { - for ( int i = 0; i < ids.length; i++ ) - { - if ( ids[i] == entryPoint ) - { - this.entryPoint = i; - return; - } - } - } - - public void clearEntryPoint() - { - entryPoint = 0; - } - - @Override - public Iterator iterator() - { - return new CycleIterator( ids, entryPoint ); - } - - public long getLastRelationshipId() - { - final int last = entryPoint > 0 ? entryPoint - 1 : ids.length - 1; - - return ids[last]; - } - - public long getFirstRelationshipId() - { - return ids[entryPoint]; - } - - public long[] getRelationshipIds() - { - // if ( entryPoint == 0 ) - // { - // return getRawRelationshipIds(); - // } - - final long[] ids = new long[this.ids.length]; - final Iterator iterator = iterator(); - - int i = 0; - while ( iterator.hasNext() ) - { - ids[i++] = iterator.next(); - } - - return ids; - } - - @Override - public int hashCode() - { - final int prime = 37; - - if ( ids.length == 0 ) - { - return prime; - } - - final CycleIterator it = identityIterator(); - - int result = prime; - - int i = 0; - while ( it.hasNext() ) - { - if ( i % 2 == 1 ) - { - result += Long.valueOf( it.next() ) - .hashCode(); - } - else - { - result -= Long.valueOf( it.next() ) - .hashCode(); - } - - i++; - } - - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final CyclePath other = (CyclePath) obj; - - if ( ids.length != other.ids.length ) - { - return false; - } - else if ( ids.length == 0 ) - { - return true; - } - - final CycleIterator it = identityIterator(); - final CycleIterator oit = other.identityIterator(); - - while ( it.hasNext() ) - { - if ( it.next() != oit.next() ) - { - return false; - } - } - - return true; - } - - public CycleIterator identityIterator() - { - final long[] sorted = new long[ids.length]; - - System.arraycopy( ids, 0, sorted, 0, ids.length ); - Arrays.sort( sorted ); - - int entry = 0; - for ( int i = 0; i < ids.length; i++ ) - { - if ( ids[i] == sorted[0] ) - { - entry = i; - break; - } - } - - return new CycleIterator( ids, entry ); - } - - private long[] getRawRelationshipIds() - { - return ids; - } - - public CyclePath reorientToEntryPoint() - { - if ( entryPoint == 0 ) - { - return this; - } - - final long[] ids = getRawRelationshipIds(); - final long[] reoriented = new long[ids.length]; - - final CycleIterator it = new CycleIterator( ids, entryPoint ); - int i = 0; - while ( it.hasNext() ) - { - reoriented[i++] = it.next(); - } - - return new CyclePath( reoriented ); - } - - public String getKey() - { - final StringBuilder sb = new StringBuilder(); - - final CycleIterator it = identityIterator(); - while ( it.hasNext() ) - { - if ( sb.length() > 0 ) - { - sb.append( ',' ); - } - - sb.append( it.next() ); - } - - return sb.toString(); - } - - @Override - public String toString() - { - return "CyclePath [" + getKey() + "]"; - } - - public int length() - { - return ids.length; - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/model/Neo4jGraphPath.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/model/Neo4jGraphPath.java deleted file mode 100644 index a8b72ad6..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/model/Neo4jGraphPath.java +++ /dev/null @@ -1,288 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.model; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.codec.digest.DigestUtils; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; - -public class Neo4jGraphPath - implements GraphPath -{ - - private final long[] relationships; - - private final long startNode; - - private final long endNode; - - public Neo4jGraphPath( final Neo4jGraphPath parent, final Relationship... relationships ) - { - if ( parent == null ) - { - throw new NullPointerException( "Parent path cannot be null" ); - } - - this.startNode = parent.startNode; - if ( relationships.length > 0 ) - { - this.endNode = relationships[relationships.length - 1].getEndNode() - .getId(); - } - else - { - this.endNode = parent.endNode; - } - - final int parentLen = parent.relationships.length; - - this.relationships = new long[parentLen + relationships.length]; - - if ( parentLen > 0 ) - { - System.arraycopy( parent.relationships, 0, this.relationships, 0, parent.relationships.length ); - } - - if ( this.relationships.length > 0 ) - { - for ( int i = parentLen; i < this.relationships.length; i++ ) - { - this.relationships[i] = relationships[i - parentLen].getId(); - } - } - } - - public Neo4jGraphPath( final Path path ) - { - this.startNode = path.startNode() - .getId(); - this.endNode = path.endNode() - .getId(); - - final List ids = new ArrayList(); - for ( final Relationship r : path.relationships() ) - { - ids.add( r.getId() ); - } - - this.relationships = new long[ids.size()]; - for ( int i = 0; i < ids.size(); i++ ) - { - this.relationships[i] = ids.get( i ); - } - } - - public Neo4jGraphPath( final Node start, final Node end, final long[] rids ) - { - this.startNode = start.getId(); - this.endNode = end.getId(); - this.relationships = rids; - } - - public Neo4jGraphPath( final Relationship[] relationships ) - { - if ( relationships.length > 0 ) - { - this.startNode = relationships[0].getStartNode() - .getId(); - - this.endNode = relationships[relationships.length - 1].getEndNode() - .getId(); - } - else - { - throw new IllegalArgumentException( - "Cannot initialize path with zero relationships and no explicit start node!" ); - } - - this.relationships = new long[relationships.length]; - - final int i = 0; - for ( final Relationship relationship : relationships ) - { - this.relationships[i] = relationship.getId(); - } - } - - private Neo4jGraphPath( final Neo4jGraphPath parent, final long endNode, final long[] newRelationships ) - { - this.startNode = parent.startNode; - this.endNode = endNode; - - final int parentLen = parent.relationships.length; - - this.relationships = new long[parentLen + newRelationships.length]; - - System.arraycopy( parent.relationships, 0, this.relationships, 0, parentLen ); - System.arraycopy( newRelationships, 0, this.relationships, parentLen, newRelationships.length ); - } - - public Neo4jGraphPath append( final Neo4jGraphPath childPath ) - { - if ( length() > 0 && getLastRelationshipId() != childPath.getFirstRelationshipId() ) - { - throw new IllegalArgumentException( "Cannot splice " + childPath + " onto " + this - + ". They don't overlap on last/first relationshipId!" ); - } - - if ( childPath.length() < 2 ) - { - return this; - } - - final long[] ids = new long[childPath.length() - 1]; - System.arraycopy( childPath.getRelationshipIds(), 1, ids, 0, ids.length ); - - return new Neo4jGraphPath( this, childPath.endNode, ids ); - } - - public long getStartNodeId() - { - return startNode; - } - - public long getEndNodeId() - { - return endNode; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode( relationships ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final Neo4jGraphPath other = (Neo4jGraphPath) obj; - if ( !Arrays.equals( relationships, other.relationships ) ) - { - return false; - } - return true; - } - - @Override - public Iterator iterator() - { - return new Iterator() - { - private int next = 0; - - @Override - public boolean hasNext() - { - return relationships.length > next; - } - - @Override - public Long next() - { - return relationships[next++]; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException( "Immutable array of relationship ID's. Remove not supported." ); - } - }; - } - - @Override - public String toString() - { - return String.format( "%s [relationships=%s, from=%s, to=%s]", getClass().getSimpleName(), - Arrays.toString( relationships ), startNode, endNode ); - } - - @Override - public String getKey() - { - final StringBuilder sb = new StringBuilder(); - for ( final long id : relationships ) - { - if ( sb.length() > 0 ) - { - sb.append( ',' ); - } - sb.append( id ); - } - - return DigestUtils.shaHex( sb.toString() ); - } - - public long getLastRelationshipId() - { - if ( relationships.length < 1 ) - { - return -1; - } - - return relationships[relationships.length - 1]; - } - - public long getFirstRelationshipId() - { - if ( relationships.length < 1 ) - { - return -1; - } - - return relationships[0]; - } - - public long[] getRelationshipIds() - { - return relationships; - } - - public int length() - { - return relationships.length; - } - - public boolean contains( final long id ) - { - for ( final long rid : relationships ) - { - if ( rid == id ) - { - return true; - } - } - return false; - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AbstractTraverseVisitor.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AbstractTraverseVisitor.java deleted file mode 100644 index 81750f08..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AbstractTraverseVisitor.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; - -public abstract class AbstractTraverseVisitor - implements TraverseVisitor -{ - - private ConversionCache conversionCache; - - public void setConversionCache( final ConversionCache conversionCache ) - { - this.conversionCache = conversionCache; - } - - public ConversionCache getConversionCache() - { - return conversionCache; - } - - @Override - public void configure( final AtlasCollector collector ) - { - } - - @Override - public boolean isEnabledFor( final Path path ) - { - return true; - } - - @Override - public void cycleDetected( final CyclePath path, final Relationship injector ) - { - } - - @Override - public boolean includeChildren( final Path path, final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - return true; - } - - @Override - public void includingChild( final Relationship child, final Neo4jGraphPath childPath, final GraphPathInfo childPathInfo, final Path parentPath ) - { - } - - @Override - public void traverseComplete( final AtlasCollector collector ) - { - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AtlasCollector.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AtlasCollector.java deleted file mode 100644 index 5be25953..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AtlasCollector.java +++ /dev/null @@ -1,289 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.GAV; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toProjectRelationship; -import static org.commonjava.maven.atlas.graph.spi.neo4j.traverse.TraversalUtils.accepted; - -import java.util.Collections; -import java.util.Set; -import java.util.TreeSet; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphRelType; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.spi.neo4j.update.CycleCacheUpdater; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.PathExpander; -import org.neo4j.graphdb.Relationship; -import org.neo4j.graphdb.traversal.BranchState; -import org.neo4j.graphdb.traversal.Evaluation; -import org.neo4j.graphdb.traversal.Evaluator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class AtlasCollector - implements Evaluator, PathExpander -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private Direction direction = Direction.OUTGOING; - - private final Set startNodes; - - private ViewParams view; - - private ConversionCache cache = new ConversionCache(); - - private TraverseVisitor visitor; - - private GraphAdmin admin; - - private boolean useSelections = true; - - private Node viewNode; - - private GraphRelType[] types; - - private RelationshipGraphConnection connection; - - public AtlasCollector( final TraverseVisitor visitor, final Node start, - final RelationshipGraphConnection connection, final ViewParams view, final Node viewNode, - final GraphAdmin admin, final GraphRelType... types ) - { - this( visitor, Collections.singleton( start ), connection, view, viewNode, admin ); - this.types = types; - } - - public AtlasCollector( final TraverseVisitor visitor, final Set startNodes, - final RelationshipGraphConnection connection, final ViewParams view, final Node viewNode, - final GraphAdmin admin, final GraphRelType... types ) - { - this.visitor = visitor; - this.connection = connection; - this.viewNode = viewNode; - this.admin = admin; - this.types = types; - visitor.configure( this ); - - this.startNodes = startNodes; - - this.view = view; - } - - public AtlasCollector( final TraverseVisitor visitor, final Set startNodes, - final RelationshipGraphConnection connection, final ViewParams view, final Node viewNode, - final GraphAdmin admin, final GraphRelType[] types, final Direction direction ) - { - this( visitor, startNodes, connection, view, viewNode, admin, types ); - this.direction = direction; - } - - public void setUseSelections( final boolean useSelections ) - { - this.useSelections = useSelections; - } - - public void setConversionCache( final ConversionCache cache ) - { - this.cache = cache; - } - - @Override - @SuppressWarnings( "rawtypes" ) - public final Iterable expand( final Path path, final BranchState state ) - { - if ( !visitor.isEnabledFor( path ) ) - { - logger.debug( "Disabled, NOT expanding: {}", path ); - return Collections.emptySet(); - } - - if ( !startNodes.isEmpty() ) - { - final Node startNode = path.startNode(); - if ( !startNodes.contains( startNode ) ) - { - logger.debug( "Rejecting path; it does not start with one of our roots:\n\t{}", path ); - return Collections.emptySet(); - } - } - - final Neo4jGraphPath graphPath = new Neo4jGraphPath( path ); - - GraphPathInfo pathInfo = new GraphPathInfo( connection, view ); - // if we're here, we're pre-cleared to blindly construct this pathInfo (see child iteration below) - for ( final Long rid : graphPath ) - { - final Relationship r = admin.getRelationship( rid ); - pathInfo = pathInfo.getChildPathInfo( toProjectRelationship( r, cache ) ); - } - - logger.debug( "For {}, using pathInfo: {}", graphPath, pathInfo ); - - final CyclePath cyclePath = CycleCacheUpdater.getTerminatingCycle( path ); - if ( cyclePath != null ) - { - final Relationship injector = path.lastRelationship(); - logger.debug( "Detected cycle in progress for path: {} at relationship: {}\n Cycle path is: {}", path, - injector, cyclePath ); - - visitor.cycleDetected( cyclePath, injector ); - } - - // logger.debug( "Checking hasSeen for graphPath: {} with pathInfo: {} (actual path: {})", graphPath, pathInfo, path ); - // if ( visitor.hasSeen( graphPath, pathInfo ) ) - // { - // logger.debug( "Already seen: {} (path: {})", graphPath, path ); - // return Collections.emptySet(); - // } - // split this so we register both the seen and the cycle. - /*else*/if ( cyclePath != null ) - { - return Collections.emptySet(); - } - - if ( returnChildren( path, graphPath, pathInfo ) ) - { - - // final ProjectRelationshipFilter nextFilter = pathInfo.getFilter(); - // log( "Implementation says return the children of: {}\n lastRel={}\n nextFilter={}\n\n", - // path.endNode() - // .hasProperty( GAV ) ? path.endNode() - // .getProperty( GAV ) : "Unknown", path.lastRelationship(), nextFilter ); - - final Set nextRelationships = new TreeSet( new AtlasRelIndexComparator() ); - - GraphRelType[] childTypes = types; - final ProjectRelationshipFilter filter = pathInfo.getFilter(); - if ( filter != null ) - { - childTypes = TraversalUtils.getGraphRelTypes( filter ); - } - - logger.debug( "Getting relationships from node: {} ({}) with type in [{}] and direction: {} (path: {})", - path.endNode(), path.endNode() - .getProperty( GAV ), new JoinString( ", ", childTypes ), direction, path ); - - final Iterable relationships = path.endNode() - .getRelationships( direction, childTypes ); - - // logger.info( "{} Determining which of {} child relationships to expand traversal into for: {}\n{}", getClass().getName(), path.length(), - // path.endNode() - // .hasProperty( GAV ) ? path.endNode() - // .getProperty( GAV ) : "Unknown", new JoinString( "\n ", Thread.currentThread() - // .getStackTrace() ) ); - - for ( Relationship r : relationships ) - { - logger.debug( "Analyzing child relationship for traversal potential: {}", r ); - - if ( useSelections ) - { - final Relationship selected = admin.select( r, view, viewNode, pathInfo, graphPath ); - if ( selected == null ) - { - logger.debug( "selection failed for: {} at {}. Likely, this is filter rejection from: {}", r, - graphPath, pathInfo ); - continue; - } - - // if no selection happened and r is a selection-only relationship, skip it. - if ( selected == r && admin.isSelection( r, viewNode ) ) - { - logger.debug( "{} is NOT the result of selection, yet it is marked as a selection relationship. Path: {}", - r, path ); - continue; - } - - if ( !accepted( selected, view, cache ) ) - { - logger.debug( "{} NOT accepted, likely due to incompatible POM location or source URI. Path: {}", - r, path ); - continue; - } - - if ( selected != null ) - { - r = selected; - } - - logger.debug( "After selection, using child relationship: {}", r ); - } - - final ProjectRelationship rel = toProjectRelationship( r, cache ); - - final Neo4jGraphPath nextPath = new Neo4jGraphPath( graphPath, r ); - final GraphPathInfo nextPathInfo = pathInfo.getChildPathInfo( rel ); - - logger.debug( "Including child: {} with next-path: {} and childPathInfo: {} from parent path: {}", r, - nextPath, nextPathInfo, path ); - visitor.includingChild( r, nextPath, nextPathInfo, path ); - - logger.debug( "+= {}", wrap( r ) ); - nextRelationships.add( r ); - } - - return nextRelationships; - } - - logger.debug( "children not being returned for: {}", path ); - return Collections.emptySet(); - } - - public boolean returnChildren( final Path path, final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - // if there's a GraphPathInfo mapped for this path, then it was accepted during expansion. - return visitor.includeChildren( path, graphPath, pathInfo ); - } - - private Object wrap( final Relationship r ) - { - return new Object() - { - @Override - public String toString() - { - return r + " " + String.valueOf( toProjectRelationship( r, cache ) ); - } - }; - } - - @Override - public final Evaluation evaluate( final Path path ) - { - return Evaluation.INCLUDE_AND_CONTINUE; - } - - @Override - public PathExpander reverse() - { - final AtlasCollector collector = - new AtlasCollector( visitor, startNodes, connection, view, viewNode, admin, types, - direction.reverse() ); - collector.setConversionCache( cache ); - collector.setUseSelections( useSelections ); - - return collector; - } -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AtlasRelIndexComparator.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AtlasRelIndexComparator.java deleted file mode 100644 index 1553f9e8..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/AtlasRelIndexComparator.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import java.util.Comparator; - -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.neo4j.graphdb.Relationship; - -public class AtlasRelIndexComparator - implements Comparator -{ - - @Override - public int compare( final Relationship f, final Relationship s ) - { - final int fidx = Conversions.getIntegerProperty( Conversions.ATLAS_RELATIONSHIP_INDEX, f, 0 ); - final int sidx = Conversions.getIntegerProperty( Conversions.ATLAS_RELATIONSHIP_INDEX, s, 0 ); - - final int comp = fidx - sidx; - if ( comp < 0 ) - { - return -1; - } - else if ( comp > 0 ) - { - return 1; - } - - return comp; - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/MembershipWrappedTraversalEvaluator.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/MembershipWrappedTraversalEvaluator.java deleted file mode 100644 index e8b8d513..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/MembershipWrappedTraversalEvaluator.java +++ /dev/null @@ -1,255 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toProjectRelationship; - -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphRelType; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.traverse.RelationshipGraphTraversal; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.PathExpander; -import org.neo4j.graphdb.Relationship; -import org.neo4j.graphdb.traversal.BranchState; -import org.neo4j.graphdb.traversal.Evaluation; -import org.neo4j.graphdb.traversal.Evaluator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MembershipWrappedTraversalEvaluator - implements Evaluator, PathExpander -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final Set rootIds; - - private final RelationshipGraphTraversal traversal; - - private boolean reversedExpander; - - private final ViewParams view; - - private ConversionCache cache = new ConversionCache(); - - private final GraphAdmin admin; - - private final Node viewNode; - - private final GraphRelType[] types; - - private final RelationshipGraphConnection connection; - - public MembershipWrappedTraversalEvaluator( final Set rootIds, final RelationshipGraphTraversal traversal, - final RelationshipGraphConnection connection, final ViewParams view, - final Node viewNode, final GraphAdmin admin, - final GraphRelType... types ) - { - this.rootIds = rootIds; - this.traversal = traversal; - this.connection = connection; - this.view = view; - this.viewNode = viewNode; - this.admin = admin; - this.types = types; - } - - private MembershipWrappedTraversalEvaluator( final MembershipWrappedTraversalEvaluator ev, final boolean reversedExpander ) - { - this.rootIds = ev.rootIds; - this.traversal = ev.traversal; - this.connection = ev.connection; - this.view = ev.view; - this.admin = ev.admin; - this.viewNode = ev.viewNode; - this.types = ev.types; - this.reversedExpander = reversedExpander; - } - - public void setConversionCache( final ConversionCache cache ) - { - this.cache = cache; - } - - @Override - public Evaluation evaluate( final Path path ) - { - final Relationship rel = path.lastRelationship(); - if ( rel == null ) - { - // logger.info( "MISSING last-relationship: {}. exclude and continue", rel ); - return Evaluation.EXCLUDE_AND_CONTINUE; - } - - final Set roots = rootIds; - if ( roots == null || roots.isEmpty() || roots.contains( path.startNode() - .getId() ) ) - { - final ProjectRelationship lastRel = Conversions.toProjectRelationship( rel, cache ); - - final List> relPath = Conversions.convertToRelationships( path.relationships(), cache ); - if ( relPath.indexOf( lastRel ) == relPath.size() - 1 ) - { - // logger.warn( "\n\n\n\n\nREMOVING last-relationship: {} from path!\n\n\n\n\n" ); - relPath.remove( relPath.size() - 1 ); - } - - if ( traversal.preCheck( lastRel, relPath ) ) - { - logger.debug( "Include-and-continue: {}, {}", relPath, lastRel ); - return Evaluation.INCLUDE_AND_CONTINUE; - } - else - { - logger.debug( "exclude-and-prune: {}, {}", relPath, lastRel ); - } - } - - // logger.info( "exclude and prune" ); - return Evaluation.EXCLUDE_AND_PRUNE; - } - - @Override - public Iterable expand( final Path path, final BranchState state ) - { - final Node node = path.endNode(); - // logger.info( "START expansion for: {}", path ); - - // TODO: Is node(0) appropriate to see?? - final Set roots = rootIds; - if ( node.getId() != 0 && roots != null && roots.isEmpty() && !roots.contains( path.startNode() - .getId() ) ) - { - // logger.info( "{} not in membership. Skipping expansion.", node ); - return Collections.emptySet(); - } - - final Neo4jGraphPath graphPath = new Neo4jGraphPath( path ); - GraphPathInfo pathInfo = new GraphPathInfo( connection, view ); - for ( final Long rid : graphPath ) - { - final Relationship r = admin.getRelationship( rid ); - pathInfo = pathInfo.getChildPathInfo( toProjectRelationship( r, cache ) ); - } - - GraphRelType[] childTypes = types; - final ProjectRelationshipFilter filter = pathInfo.getFilter(); - if ( filter != null ) - { - childTypes = TraversalUtils.getGraphRelTypes( filter ); - } - - final Iterable rs = - node.getRelationships( reversedExpander ? Direction.INCOMING : Direction.OUTGOING, childTypes ); - - if ( rs == null ) - { - // logger.info( "No relationships from end-node: {}", node ); - return Collections.emptySet(); - } - - // sort the child relationships to make the traversal deterministic - final Set result = new TreeSet( new AtlasRelIndexComparator() ); - - final List> rels = getPathRelationships( path ); - - // logger.info( "For: {} Determining which of {} child relationships to expand traversal into for: {}\n{}", traversal.getClass() - // .getName(), path.length(), - // path.endNode() - // .hasProperty( GAV ) ? path.endNode() - // .getProperty( GAV ) : "Unknown", new JoinString( "\n ", Thread.currentThread() - // .getStackTrace() ) ); - - for ( Relationship r : rs ) - { - if ( Conversions.getBooleanProperty( Conversions.CYCLES_INJECTED, r, false ) ) - { - continue; - } - - final Relationship selected = admin.select( r, view, viewNode, pathInfo, graphPath ); - - // if no selection happened and r is a selection-only relationship, skip it. - if ( ( selected == null || selected == r ) && admin.isSelection( r, viewNode ) ) - { - continue; - } - - if ( selected != null ) - { - r = selected; - } - // logger.info( "Attempting to expand: {}", r ); - - final ProjectRelationship projectRel = Conversions.toProjectRelationship( r, cache ); - - logger.debug( "Pre-checking relationship {} for expansion using filter: {}", projectRel, traversal ); - if ( traversal.preCheck( projectRel, rels ) ) - { - logger.debug( "Adding for expansion: {}", projectRel ); - result.add( r ); - } - else - { - logger.debug( "Skipping for expansion: {}", projectRel ); - } - } - - logger.debug( "Expanding for {} relationships.", result.size() ); - return result; - } - - private List> getPathRelationships( final Path path ) - { - List> rels; - final Iterable rs = path.relationships(); - if ( rs == null ) - { - // logger.info( "Constructing empty relationship list for filter." ); - rels = Collections.emptyList(); - } - else - { - rels = Conversions.convertToRelationships( rs, cache ); - // logger.info( "Got relationship list {} entries long for filter", rels.size() ); - } - - if ( reversedExpander ) - { - // logger.info( "Reversing relationship list for filter." ); - Collections.reverse( rels ); - } - - return rels; - } - - @Override - public PathExpander reverse() - { - return new MembershipWrappedTraversalEvaluator( this, true ); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/NodePair.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/NodePair.java deleted file mode 100644 index 67a12e67..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/NodePair.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.neo4j.graphdb.Node; - -public final class NodePair -{ - private final long from; - - private final long to; - - public NodePair( final Node from, final Node to ) - { - this.from = from.getId(); - this.to = to.getId(); - } - - public long getFrom() - { - return from; - } - - public long getTo() - { - return to; - } - - @Override - public boolean equals( final Object other ) - { - if ( other == this ) - { - return true; - } - if ( !( other instanceof NodePair ) ) - { - return false; - } - final NodePair o = (NodePair) other; - - return o.from == from && o.to == to; - } - - @Override - public int hashCode() - { - final int result = (int) ( 1337133713 * from / to ); - - return result; - } - - @Override - public String toString() - { - return String.format( "NodePair %d -> %d (%d)", from, to, hashCode() ); - } -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/PathCollectingVisitor.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/PathCollectingVisitor.java deleted file mode 100644 index 8f23cebb..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/PathCollectingVisitor.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; - -public class PathCollectingVisitor - extends AbstractTraverseVisitor - implements Iterable -{ - - private final Set ends; - - private final Set paths = new HashSet(); - - private final ConversionCache cache; - - public PathCollectingVisitor( final Set ends, final ConversionCache cache ) - { - this.ends = ends; - this.cache = cache; - } - - public Set getPaths() - { - return paths; - } - - @Override - public boolean includeChildren( final Path path, final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - if ( ends.contains( path.endNode() ) ) - { - paths.add( graphPath ); - return false; - } - - return true; - } - - @Override - public void configure( final AtlasCollector collector ) - { - collector.setConversionCache( cache ); - } - - @Override - public Iterator iterator() - { - return paths.iterator(); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/PathExistenceVisitor.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/PathExistenceVisitor.java deleted file mode 100644 index ca235874..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/PathExistenceVisitor.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; - -public class PathExistenceVisitor - extends AbstractTraverseVisitor -{ - - private final Node end; - - private boolean found = false; - - public PathExistenceVisitor( final Node end ) - { - this.end = end; - } - - public boolean isFound() - { - return found; - } - - @Override - public boolean isEnabledFor( final Path path ) - { - return !found; - } - - @Override - public void includingChild( final Relationship child, final Neo4jGraphPath childPath, final GraphPathInfo childPathInfo, final Path parentPath ) - { - final Node end = child.getEndNode(); - if ( this.end.getId() == end.getId() ) - { - found = true; - } - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/RootedRelationshipsVisitor.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/RootedRelationshipsVisitor.java deleted file mode 100644 index f83daeef..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/RootedRelationshipsVisitor.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphRelType; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RootedRelationshipsVisitor - extends AbstractTraverseVisitor - implements Iterable> -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final Set> found = new HashSet>(); - - public Set> getRelationships() - { - return found; - } - - @Override - public Iterator> iterator() - { - return found.iterator(); - } - - @Override - public boolean includeChildren( final Path path, final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - for ( final Relationship r : path.relationships() ) - { - if ( r.getType() == GraphRelType.PARENT && r.getStartNode() - .getId() == r.getEndNode() - .getId() ) - { - logger.debug( "Skipping self-referential parent relationship to: {}", r.getStartNode() - .getProperty( Conversions.GAV ) ); - } - else - { - found.add( Conversions.toProjectRelationship( r, getConversionCache() ) ); - } - } - - return true; - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/SubPathsCollectingVisitor.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/SubPathsCollectingVisitor.java deleted file mode 100644 index 8289d934..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/SubPathsCollectingVisitor.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SubPathsCollectingVisitor - extends AbstractTraverseVisitor - implements Iterable -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final Set viaNodes; - - private final Set paths = new HashSet(); - - private final GraphAdmin admin; - - public SubPathsCollectingVisitor( final Set viaNodes, final GraphAdmin admin ) - { - this.viaNodes = viaNodes; - this.admin = admin; - } - - @Override - public Iterator iterator() - { - return paths.iterator(); - } - - public Set getSubPaths() - { - return paths; - } - - @Override - public boolean includeChildren( final Path path, final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - if ( path.length() > 1 ) - { - final Neo4jGraphPath gp = new Neo4jGraphPath( path ); - final long[] allRids = gp.getRelationshipIds(); - int i = 0; - Relationship start = null; - for ( ; i < allRids.length; i++ ) - { - start = admin.getRelationship( allRids[i] ); - if ( viaNodes.contains( start.getEndNode() - .getId() ) ) - { - logger.debug( "found via-node ending: {}", start ); - break; - } - } - - if ( start != null && i < allRids.length - 1 ) - { - final long[] rids = new long[allRids.length - i]; - System.arraycopy( allRids, i, rids, 0, rids.length ); - - final Relationship last = admin.getRelationship( allRids[allRids.length - 1] ); - paths.add( new Neo4jGraphPath( start.getStartNode(), last.getEndNode(), rids ) ); - } - } - - return true; - } - - @Override - public void configure( final AtlasCollector collector ) - { - collector.setUseSelections( false ); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/TraversalUtils.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/TraversalUtils.java deleted file mode 100644 index 0cab5eb6..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/TraversalUtils.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.POM_LOCATION_URI; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.SOURCE_URI; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.getURIProperty; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.getURISetProperty; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.toProjectRelationship; -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.POM_ROOT_URI; -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.UNKNOWN_SOURCE_URI; - -import java.net.URI; -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphRelType; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.neo4j.graphdb.Relationship; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class TraversalUtils -{ - - private static final Logger logger = LoggerFactory.getLogger( TraversalUtils.class ); - - private TraversalUtils() - { - } - - // public static boolean acceptedInView( final Path path, final GraphView view, final ConversionCache cache ) - // { - // ProjectRelationshipFilter f = view.getFilter(); - // final GraphWorkspace ws = view.getWorkspace(); - // - // for ( final Relationship r : path.relationships() ) - // { - // if ( !accepted( r, f, ws, cache ) ) - // { - // return false; - // } - // - // if ( f != null ) - // { - // final ProjectRelationship rel = toProjectRelationship( r, cache ); - // f = f.getChildFilter( rel ); - // } - // } - // - // debug( "ACCEPT: Path: {}", path ); - // return true; - // } - - public static boolean acceptedInView( final Relationship r, final ViewParams view, final ConversionCache cache ) - { - return accepted( r, view, cache ); - } - - public static boolean accepted( final Relationship r, final ViewParams view, final ConversionCache cache ) - { - final ProjectRelationship rel = toProjectRelationship( r, cache ); - - debug( "Checking relationship for acceptance: {} ({})", r, rel ); - - final Set sources = view.getActiveSources(); - if ( sources != null && !sources.isEmpty() ) - { - if ( !sources.contains( RelationshipUtils.ANY_SOURCE_URI ) ) - { - final Set s = getURISetProperty( SOURCE_URI, r, UNKNOWN_SOURCE_URI ); - boolean found = false; - for ( final URI uri : s ) - { - // TODO: What are the default sources anyway?? any:any?? - if ( /*sources == GraphWorkspace.DEFAULT_SOURCES ||*/sources.contains( uri ) ) - { - found = true; - break; - } - } - - if ( !found ) - { - debug( "REJECTED: Found relationship in path with de-selected source-repository URI: {} (r={}, permissable sources: {})", - s, r, sources ); - return false; - } - } - } - - final Set pomLocations = view.getActivePomLocations(); - if ( pomLocations != null && !pomLocations.isEmpty() ) - { - final URI pomLocation = getURIProperty( POM_LOCATION_URI, r, POM_ROOT_URI ); - if ( !pomLocations.contains( pomLocation ) ) - { - debug( "REJECTED: Found relationship in path with de-selected pom-location URI: {}", r ); - return false; - } - } - - final ProjectRelationshipFilter filter = view.getFilter(); - if ( filter != null ) - { - if ( !filter.accept( rel ) ) - { - debug( "Filter: {} REJECTED relationship: {} ({})", filter, r, rel ); - return false; - } - } - - debug( "ACCEPT: {} ({})", r, rel ); - return true; - } - - private static void debug( final String message, final Object... params ) - { - logger.debug( message, params ); - } - - public static GraphRelType[] getGraphRelTypes( final ProjectRelationshipFilter filter ) - { - if ( filter == null ) - { - return GraphRelType.atlasRelationshipTypes(); - } - - final Set result = new HashSet(); - - final Set types = filter.getAllowedTypes(); - for ( final RelationshipType rt : types ) - { - if ( filter.includeManagedRelationships() ) - { - final GraphRelType grt = GraphRelType.map( rt, true ); - if ( grt != null ) - { - result.add( grt ); - } - } - - if ( filter.includeConcreteRelationships() ) - { - final GraphRelType grt = GraphRelType.map( rt, false ); - if ( grt != null ) - { - result.add( grt ); - } - } - } - - return result.toArray( new GraphRelType[result.size()] ); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/TraverseVisitor.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/TraverseVisitor.java deleted file mode 100644 index fc94b078..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/TraverseVisitor.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; - -public interface TraverseVisitor -{ - - /** - * Allow configuration of extra options for this collector as it initializes - * with this visitor. - */ - void configure( AtlasCollector collector ); - - /** - * MUST call this after traverse completes, to allow resource reclamation. - */ - void traverseComplete( AtlasCollector collector ); - - /** - * Allow visitor to turn itself off and skip further traversal of a path. - */ - boolean isEnabledFor( Path path ); - - /** - * Handle detected cycle (which was traversed TO, but not THROUGH). - */ - void cycleDetected( CyclePath cp, Relationship injector ); - - /** - * Whether child edges of the given path should be visited. - */ - boolean includeChildren( Path path, Neo4jGraphPath graphPath, GraphPathInfo pathInfo ); - - /** - * Notice that a child relationship has been included. - * - * @param child The relationship that WILL BE traversed - * @param childPath The {@link Neo4jGraphPath} that will be associated with traversing this child - * @param childPathInfo {@link GraphPathInfo} that will be associated with traversing this child - * @param parentPath parent {@link Path} which will be extended by this child - */ - void includingChild( Relationship child, Neo4jGraphPath childPath, GraphPathInfo childPathInfo, Path parentPath ); - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/LuceneSeenTracker.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/LuceneSeenTracker.java deleted file mode 100644 index 398a319d..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/LuceneSeenTracker.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse.track; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.spi.neo4j.update.CycleCacheUpdater; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Transaction; -import org.neo4j.graphdb.index.Index; -import org.neo4j.graphdb.index.IndexHits; - -public class LuceneSeenTracker - implements TraverseSeenTracker -{ - - private static final String SEEN_RELS_PREFIX = "_seen_rels_"; - - private static final String KEY = "seen_key"; - - private final GraphAdmin admin; - - private final Index seen; - - private final Node viewNode; - - public LuceneSeenTracker( final ViewParams view, final Node viewNode, final GraphAdmin admin ) - { - this.viewNode = viewNode; - this.seen = admin.getNodeIndex( view.getShortId() + SEEN_RELS_PREFIX + System.currentTimeMillis() ); - this.admin = admin; - } - - @Override - public boolean hasSeen( final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - // TODO: This trims the path leading up to the cycle...is that alright?? - - String key; - final CyclePath cyclePath = CycleCacheUpdater.getTerminatingCycle( graphPath, admin ); - if ( cyclePath != null ) - { - key = cyclePath.getKey(); - } - else - { - key = graphPath.getKey(); - } - - key += "#" + pathInfo.getKey(); - final IndexHits hits = seen.get( KEY, key ); - if ( hits.hasNext() ) - { - return true; - } - - final Transaction tx = admin.beginTransaction(); - try - { - seen.add( viewNode, KEY, key ); - tx.success(); - } - finally - { - tx.finish(); - } - - return false; - } - - @Override - public void traverseComplete() - { - final Transaction tx = admin.beginTransaction(); - try - { - seen.delete(); - tx.success(); - } - finally - { - tx.finish(); - } - - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/MemorySeenTracker.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/MemorySeenTracker.java deleted file mode 100644 index f4d45133..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/MemorySeenTracker.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse.track; - -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.spi.neo4j.update.CycleCacheUpdater; - -public class MemorySeenTracker - implements TraverseSeenTracker -{ - - private final Set seenKeys = new HashSet(); - - private final GraphAdmin admin; - - public MemorySeenTracker( final GraphAdmin admin ) - { - this.admin = admin; - } - - @Override - public boolean hasSeen( final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - // TODO: This trims the path leading up to the cycle...is that alright?? - - String key; - final CyclePath cyclePath = CycleCacheUpdater.getTerminatingCycle( graphPath, admin ); - if ( cyclePath != null ) - { - key = cyclePath.getKey(); - } - else - { - key = graphPath.getKey(); - } - - key += "#" + pathInfo.getKey(); - return !seenKeys.add( key ); - } - - @Override - public void traverseComplete() - { - seenKeys.clear(); - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/TraverseSeenTracker.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/TraverseSeenTracker.java deleted file mode 100644 index 3bf4a995..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/track/TraverseSeenTracker.java +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse.track; - -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; - -public interface TraverseSeenTracker -{ - - boolean hasSeen( Neo4jGraphPath graphPath, GraphPathInfo pathInfo ); - - void traverseComplete(); - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/update/CycleCacheUpdater.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/update/CycleCacheUpdater.java deleted file mode 100644 index 5e9c5c53..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/update/CycleCacheUpdater.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.update; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.AbstractTraverseVisitor; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.AtlasCollector; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; -import org.neo4j.graphdb.Transaction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CycleCacheUpdater - extends AbstractTraverseVisitor -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final ConversionCache cache; - - private final Node viewNode; - - final Set cycles = new HashSet(); - - private final ViewParams view; - - private final GraphAdmin admin; - - public CycleCacheUpdater( final ViewParams view, final Node viewNode, final GraphAdmin admin, - final ConversionCache cache ) - { - this.view = view; - this.viewNode = viewNode; - this.admin = admin; - this.cache = cache; - } - - @Override - public void cycleDetected( final CyclePath cyclicPath, final Relationship injector ) - { - if ( cyclicPath.length() < 1 ) - { - logger.debug( "No paths in cycle!" ); - return; - } - - addCycleInternal( cyclicPath, injector ); - } - - public void addCycle( final CyclePath cyclicPath, final Relationship injector ) - { - if ( cyclicPath.length() < 1 ) - { - logger.debug( "No paths in cycle!" ); - return; - } - - addCycleInternal( cyclicPath, injector ); - } - - private void addCycleInternal( final CyclePath cyclicPath, final Relationship injector ) - { - final Transaction tx = admin.beginTransaction(); - try - { - logger.debug( "Adding cycle: {} (via: {})", cyclicPath, injector ); - Conversions.storeCachedCyclePath( cyclicPath, viewNode ); - - final List> cycle = Conversions.convertToRelationships( cyclicPath, admin, cache ); - logger.info( "CYCLES += {\n {}\n}", new JoinString( "\n ", cycle ) ); - cycles.add( new EProjectCycle( cycle ) ); - - tx.success(); - } - finally - { - tx.finish(); - } - } - - public static CyclePath getTerminatingCycle( final Path path ) - { - final Logger logger = LoggerFactory.getLogger( CycleCacheUpdater.class ); - logger.debug( "Looking for terminating cycle in: {}", path ); - - final List rids = new ArrayList(); - final List starts = new ArrayList(); - for ( final Relationship pathR : path.relationships() ) - { - rids.add( pathR.getId() ); - - final long sid = pathR.getStartNode() - .getId(); - - final long eid = pathR.getEndNode() - .getId(); - - final int idx = starts.indexOf( eid ); - if ( idx > -1 ) - { - final CyclePath cp = new CyclePath( rids.subList( idx, rids.size() ) ); - logger.debug( "Detected cycle: {}", cp ); - - return cp; - } - - starts.add( sid ); - } - - logger.debug( "No cycle detected" ); - - return null; - } - - public static CyclePath getTerminatingCycle( final Neo4jGraphPath graphPath, final GraphAdmin admin ) - { - final Logger logger = LoggerFactory.getLogger( CycleCacheUpdater.class ); - logger.debug( "Looking for terminating cycle in: {}", graphPath ); - - final Map startNodesToRids = new HashMap(); - final long[] rids = graphPath.getRelationshipIds(); - Long startRid = null; - for ( final long rid : rids ) - { - final Relationship r = admin.getRelationship( rid ); - - final long eid = r.getEndNode() - .getId(); - - startRid = startNodesToRids.get( eid ); - if ( startRid != null ) - { - break; - } - - startNodesToRids.put( r.getStartNode() - .getId(), r.getId() ); - } - - if ( startRid != null ) - { - int i = 0; - for ( ; i < rids.length; i++ ) - { - if ( rids[i] == startRid ) - { - break; - } - } - - final long[] cycle = new long[rids.length - i]; - System.arraycopy( rids, i, cycle, 0, cycle.length ); - - final CyclePath cp = new CyclePath( cycle ); - logger.debug( "Detected cycle: {}", cp ); - return cp; - } - - logger.debug( "No cycle detected" ); - - return null; - } - - @Override - public void configure( final AtlasCollector collector ) - { - collector.setConversionCache( cache ); - } - - public int getCycleCount() - { - return cycles.size(); - } - - public Set getCycles() - { - return cycles; - } - - @Override - public void traverseComplete( final AtlasCollector collector ) - { - final Transaction tx = admin.beginTransaction(); - try - { - logger.info( "Clearing PENDING cycle-detection for: {} of view: {}", viewNode, view.getShortId() ); - Conversions.setCycleDetectionPending( viewNode, false ); - tx.success(); - } - finally - { - tx.finish(); - } - } - -} diff --git a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/update/ViewUpdater.java b/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/update/ViewUpdater.java deleted file mode 100644 index 45b5376e..00000000 --- a/drivers/neo4j-embedded/src/main/java/org/commonjava/maven/atlas/graph/spi/neo4j/update/ViewUpdater.java +++ /dev/null @@ -1,242 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.update; - -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.NID; -import static org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.RID; - -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.neo4j.GraphAdmin; -import org.commonjava.maven.atlas.graph.spi.neo4j.ViewIndexes; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.ConversionCache; -import org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.CyclePath; -import org.commonjava.maven.atlas.graph.spi.neo4j.model.Neo4jGraphPath; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.AbstractTraverseVisitor; -import org.commonjava.maven.atlas.graph.spi.neo4j.traverse.AtlasCollector; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.Path; -import org.neo4j.graphdb.Relationship; -import org.neo4j.graphdb.Transaction; -import org.neo4j.graphdb.index.Index; -import org.neo4j.graphdb.index.IndexHits; -import org.neo4j.graphdb.index.RelationshipIndex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ViewUpdater - extends AbstractTraverseVisitor -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final Node viewNode; - - private final ConversionCache cache; - - private final GraphAdmin admin; - - private final CycleCacheUpdater cycleUpdater; - - private final ViewIndexes indexes; - - private Node stopNode; - - public ViewUpdater( final ViewParams view, final Node viewNode, final ViewIndexes indexes, - final ConversionCache cache, final GraphAdmin admin ) - { - this.viewNode = viewNode; - this.indexes = indexes; - this.cache = cache; - this.admin = admin; - this.cycleUpdater = new CycleCacheUpdater( view, viewNode, admin, cache ); - } - - public ViewUpdater( final Node stopNode, final ViewParams view, final Node viewNode, final ViewIndexes indexes, - final ConversionCache cache, - final GraphAdmin admin ) - { - this.stopNode = stopNode; - this.viewNode = viewNode; - this.indexes = indexes; - this.cache = cache; - this.admin = admin; - this.cycleUpdater = new CycleCacheUpdater( view, viewNode, admin, cache ); - } - - public void cacheRoots( final Set roots ) - { - final Transaction tx = admin.beginTransaction(); - try - { - final Index cachedNodes = indexes.getCachedNodes(); - for ( final Node node : roots ) - { - cachedNodes.add( node, NID, node.getId() ); - } - tx.success(); - } - finally - { - tx.finish(); - } - } - - public boolean processAddedRelationships( final Map> createdRelationshipsMap ) - { - for ( final Entry> entry : createdRelationshipsMap.entrySet() ) - { - final Long rid = entry.getKey(); - final Relationship add = admin.getRelationship( rid ); - - // TODO: WTF is the point of this?? - // indexes.getSelections() - // .remove( add ); - // - - final Transaction tx = admin.beginTransaction(); - try - { - logger.debug( "Checking node cache for: {}", add.getStartNode() ); - final IndexHits hits = indexes.getCachedNodes() - .get( NID, add.getStartNode() - .getId() ); - if ( hits.hasNext() ) - { - Conversions.setMembershipDetectionPending( viewNode, true ); - Conversions.setCycleDetectionPending( viewNode, true ); - - tx.success(); - return true; - } - } - finally - { - tx.finish(); - } - } - - return false; - } - - @Override - public void includingChild( final Relationship child, final Neo4jGraphPath childPath, final GraphPathInfo childPathInfo, final Path parentPath ) - { - cachePath( childPath, childPathInfo ); - } - - @Override - public void configure( final AtlasCollector collector ) - { - collector.setConversionCache( cache ); - cycleUpdater.configure( collector ); - } - - private void cachePath( final Neo4jGraphPath path, final GraphPathInfo pathInfo ) - { - final CyclePath cyclePath = CycleCacheUpdater.getTerminatingCycle( path, admin ); - if ( cyclePath != null ) - { - // logger.info( "CYCLE: {}", cyclePath ); - - final Relationship injector = admin.getRelationship( path.getLastRelationshipId() ); - cycleUpdater.addCycle( cyclePath, injector ); - - return; - } - - final Transaction tx = admin.beginTransaction(); - try - { - logger.debug( "Caching path: {}", path ); - - final RelationshipIndex cachedRels = indexes.getCachedRelationships(); - final Index cachedNodes = indexes.getCachedNodes(); - - final Set nodes = new HashSet(); - for ( final Long relId : path ) - { - final Relationship r = admin.getRelationship( relId ); - - logger.debug( "rel-membership += " + relId ); - cachedRels.add( r, RID, relId ); - - final long startId = r.getStartNode() - .getId(); - if ( nodes.add( startId ) ) - { - logger.debug( "node-membership += " + startId ); - cachedNodes.add( r.getStartNode(), NID, startId ); - } - - final long endId = r.getEndNode() - .getId(); - if ( nodes.add( endId ) ) - { - logger.debug( "node-membership += " + endId ); - cachedNodes.add( r.getEndNode(), NID, endId ); - } - } - tx.success(); - } - finally - { - tx.finish(); - } - } - - @Override - public void cycleDetected( final CyclePath path, final Relationship injector ) - { - cycleUpdater.cycleDetected( path, injector ); - } - - @Override - public boolean includeChildren( final Path path, final Neo4jGraphPath graphPath, final GraphPathInfo pathInfo ) - { - if ( stopNode != null && path.endNode() - .getId() == stopNode.getId() ) - { - return false; - } - - return true; - } - - @Override - public void traverseComplete( final AtlasCollector collector ) - { - if ( stopNode == null ) - { - final Transaction tx = admin.beginTransaction(); - try - { - // we did a complete traversal. - Conversions.setMembershipDetectionPending( viewNode, false ); - tx.success(); - } - finally - { - tx.finish(); - } - - cycleUpdater.traverseComplete( collector ); - } - } - -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/CypherQueriesTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/CypherQueriesTest.java deleted file mode 100644 index dc087df5..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/CypherQueriesTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import java.net.URI; -import java.util.Map; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.tck.graph.AbstractSPI_TCK; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; -import org.neo4j.cypher.javacompat.ExecutionResult; - -public class CypherQueriesTest - extends AbstractSPI_TCK -{ - - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Rule - public TestName naming = new TestName(); - - @Test - public void projectsWithVariableFlag_PartialQuery() - throws Exception - { - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef varDep = new ProjectVersionRef( "org.other", "dep", "1.0-SNAPSHOT" ); - final ProjectVersionRef varD2 = new ProjectVersionRef( "org.other", "dep2", "1.0-SNAPSHOT" ); - final ProjectVersionRef selected = new ProjectVersionRef( varDep, "1.0-20130314.161200-1" ); - - final URI source = sourceURI(); - RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - graph.storeRelationships( - new DependencyRelationship( source, project, new ArtifactRef( varDep, null, null, false ), null, 0, false ), - new DependencyRelationship( source, varDep, new ArtifactRef( varD2, null, null, false ), null, 0, false ) - ); - - graph = graphFactory().open( new ViewParams.Builder( graph.getParams() ).withSelection( varDep.asProjectRef(), selected ).build(), false ); - -// view.selectVersion( varDep, selected ); - - final String cypher = "START a=node(1) " - + "\nMATCH p=(a)-[:M_PLUGIN_DEP|C_PLUGIN|PARENT|EXTENSION|M_DEPENDENCY|M_PLUGIN|C_PLUGIN_DEP|C_DEPENDENCY*]->(n) " - + "\nWHERE " - + "\n none( " - + "\n r in relationships(p) " - + "\n WHERE has(r._deselected_for) " - + "\n ) " - + "\nRETURN n as node, p as path"; - /* @formatter:on */ - - final FileNeo4JGraphConnection driver = (FileNeo4JGraphConnection) graph.getDatabase(); - - final ExecutionResult result = driver.execute( cypher ); - int i = 0; - for ( final Map record : result ) - { - System.out.printf( "%d: %s", i++, record ); - } - } - - @Test - // @Ignore - public void projectsWithVariableFlagQuery() - throws Exception - { - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef varDep = new ProjectVersionRef( "org.other", "dep", "1.0-SNAPSHOT" ); - final ProjectVersionRef varD2 = new ProjectVersionRef( "org.other", "dep2", "1.0-SNAPSHOT" ); - final ProjectVersionRef selected = new ProjectVersionRef( varDep, "1.0-20130314.161200-1" ); - - final URI source = sourceURI(); - RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - graph.storeRelationships( - new DependencyRelationship( source, project, new ArtifactRef( varDep, null, null, false ), null, 0, false ), - new DependencyRelationship( source, varDep, new ArtifactRef( varD2, null, null, false ), null, 0, false ) - ); - - graph = graphFactory().open( new ViewParams.Builder( graph.getParams()).withSelection( varDep.asProjectRef(), selected ).build(), false ); - - final String cypher = "START a=node(1) " - + "\nMATCH p=(a)-[:M_PLUGIN_DEP|C_PLUGIN|PARENT|EXTENSION|M_DEPENDENCY|M_PLUGIN|C_PLUGIN_DEP|C_DEPENDENCY*]->(n) " - + "\nWHERE " - + "\n none( " - + "\n r in relationships(p) " - + "\n WHERE has(r._deselected_for) " - + "\n ) " - + "\n AND has(n.gav) " - + "\n AND has(n.gav) " - + "\n AND n._variable! = true " - + "\nRETURN n as node, p as path"; - /* @formatter:on */ - - final FileNeo4JGraphConnection driver = (FileNeo4JGraphConnection) graph.getDatabase(); - - final ExecutionResult result = driver.execute( cypher ); - int i = 0; - for ( final Map record : result ) - { - System.out.printf( "%d: %s", i++, record ); - } - } - - @Override - protected RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } - -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileCycleDetectionTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileCycleDetectionTest.java deleted file mode 100644 index 9cae0a36..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileCycleDetectionTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.CycleDetectionTCK; -import org.junit.Rule; - -public class FileCycleDetectionTest - extends CycleDetectionTCK -{ - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileGraphWorkspaceTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileGraphWorkspaceTest.java deleted file mode 100644 index 550132ae..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileGraphWorkspaceTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.RelationshipGraphConnection_TCK; -import org.junit.Rule; - -public class FileGraphWorkspaceTest - extends RelationshipGraphConnection_TCK -{ - - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileSubGraphSelectionTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileSubGraphSelectionTest.java deleted file mode 100644 index 3723ffcb..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/FileSubGraphSelectionTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.SubGraphSelectionTCK; -import org.junit.Rule; - -public class FileSubGraphSelectionTest - extends SubGraphSelectionTCK -{ - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/RelationshipGraphTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/RelationshipGraphTest.java deleted file mode 100644 index efa5da56..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/RelationshipGraphTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.RelationshipGraphTCK; -import org.junit.Rule; - -public class RelationshipGraphTest - extends RelationshipGraphTCK -{ - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/fixture/FileConnectionFixture.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/fixture/FileConnectionFixture.java deleted file mode 100644 index e9881202..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/fixture/FileConnectionFixture.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.fixture; - -import java.io.File; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.spi.neo4j.FileNeo4jConnectionFactory; -import org.junit.rules.ExternalResource; -import org.junit.rules.TemporaryFolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FileConnectionFixture - extends ExternalResource -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final TemporaryFolder folder = new TemporaryFolder(); - - private FileNeo4jConnectionFactory factory; - - @Override - protected void after() - { - super.after(); - try - { - factory.close(); - } - catch ( final RelationshipGraphConnectionException e ) - { - e.printStackTrace(); - } - - folder.delete(); - } - - @Override - protected void before() - throws Throwable - { - folder.create(); - - final File dbDir = folder.newFolder(); - dbDir.delete(); - dbDir.mkdirs(); - - logger.info( "Initializing db in: {}", dbDir ); - factory = new FileNeo4jConnectionFactory( dbDir, false ); - } - - public FileNeo4jConnectionFactory connectionFactory() - { - return factory; - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileAncestryTraversalTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileAncestryTraversalTest.java deleted file mode 100644 index 3a53f65f..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileAncestryTraversalTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.traverse.AncestryTraversalTCK; -import org.junit.Rule; - -public class FileAncestryTraversalTest - extends AncestryTraversalTCK -{ - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileBuildOrderTraversalTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileBuildOrderTraversalTest.java deleted file mode 100644 index f922747f..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileBuildOrderTraversalTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.traverse.BuildOrderTraversalTCK; -import org.junit.Rule; - -public class FileBuildOrderTraversalTest - extends BuildOrderTraversalTCK -{ - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileTransitiveDependencyTraversalTest.java b/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileTransitiveDependencyTraversalTest.java deleted file mode 100644 index 23fb1283..00000000 --- a/drivers/neo4j-embedded/src/test/java/org/commonjava/maven/atlas/graph/spi/neo4j/traverse/FileTransitiveDependencyTraversalTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi.neo4j.traverse; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.graph.spi.neo4j.fixture.FileConnectionFixture; -import org.commonjava.maven.atlas.tck.graph.traverse.TransitiveDependencyTraversalTCK; -import org.junit.Rule; - -public class FileTransitiveDependencyTraversalTest - extends TransitiveDependencyTraversalTCK -{ - @Rule - public FileConnectionFixture fixture = new FileConnectionFixture(); - - @Override - protected synchronized RelationshipGraphConnectionFactory connectionFactory() - throws Exception - { - return fixture.connectionFactory(); - } -} diff --git a/drivers/neo4j-embedded/src/test/resources/logback-test.xml b/drivers/neo4j-embedded/src/test/resources/logback-test.xml deleted file mode 100644 index 37e09750..00000000 --- a/drivers/neo4j-embedded/src/test/resources/logback-test.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - diff --git a/drivers/pom.xml b/drivers/pom.xml deleted file mode 100644 index 96329b04..00000000 --- a/drivers/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - 4.0.0 - - - org.commonjava.maven.atlas - atlas-parent - 0.12.0-EXP-SNAPSHOT - - - atlas-drivers-parent - pom - - Atlas :: Maven Project-Graph :: Drivers Parent - - - - org.commonjava.maven.atlas - atlas-relationships-api - - - org.commonjava.maven.atlas - atlas-drivers-tck - - - - - jung - neo4j-embedded - - diff --git a/identities/pom.xml b/identities/pom.xml index de0448b1..89a1cf16 100644 --- a/identities/pom.xml +++ b/identities/pom.xml @@ -1,27 +1,41 @@ 4.0.0 - org.commonjava.maven.atlas + org.commonjava.atlas atlas-parent - 0.12.0-EXP-SNAPSHOT + 1.2.3-SNAPSHOT atlas-identities Atlas :: Maven Project-Graph :: Identities Model - + + + + org.apache.commons + commons-lang3 + + + diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/DependencyScope.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/DependencyScope.java similarity index 64% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/DependencyScope.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/DependencyScope.java index 097699d5..7a01d702 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/DependencyScope.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/DependencyScope.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident; import java.util.ArrayList; import java.util.Arrays; @@ -18,20 +23,26 @@ public enum DependencyScope { - _import( "import" ), toolchain, provided, embedded, compile( provided, embedded ), runtime( compile ), system, test( provided, embedded, compile, - runtime, system ); + _import( "import" ), + toolchain, + provided, + embedded, + compile( provided, embedded ), + runtime( compile ), + system, + test( provided, embedded, compile, runtime, system ); private final Set implied; private String realName; - private DependencyScope( final String realName, final DependencyScope... implied ) + DependencyScope( final String realName, final DependencyScope... implied ) { this.realName = realName; this.implied = new HashSet( Arrays.asList( implied ) ); } - private DependencyScope( final DependencyScope... implied ) + DependencyScope( final DependencyScope... implied ) { realName = name(); this.implied = new HashSet( Arrays.asList( implied ) ); diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ScopeTransitivity.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ScopeTransitivity.java new file mode 100644 index 00000000..55958399 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ScopeTransitivity.java @@ -0,0 +1,54 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident; + +import static org.commonjava.atlas.maven.ident.DependencyScope.embedded; +import static org.commonjava.atlas.maven.ident.DependencyScope.runtime; +import static org.commonjava.atlas.maven.ident.DependencyScope.toolchain; + +public enum ScopeTransitivity +{ + maven + { + @Override + public DependencyScope getChildFor( final DependencyScope scope ) + { + switch ( scope ) + { + case provided: + return null; + case embedded: + return embedded; + case toolchain: + return toolchain; + default: + return runtime; + } + } + }, + + all + { + @Override + public DependencyScope getChildFor( final DependencyScope scope ) + { + return scope; + } + }; + + public abstract DependencyScope getChildFor( DependencyScope scope ); + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ArtifactRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ArtifactRef.java new file mode 100644 index 00000000..b30acf3a --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ArtifactRef.java @@ -0,0 +1,34 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/21/15. + */ +public interface ArtifactRef + extends ProjectVersionRef, Serializable, Comparable, VersionedRef +{ + String getType(); + + String getClassifier(); + + TypeAndClassifier getTypeAndClassifier(); + + @Override + boolean versionlessEquals( ProjectVersionRef other ); +} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/InvalidRefException.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/InvalidRefException.java similarity index 63% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/ref/InvalidRefException.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/ref/InvalidRefException.java index 77f8818a..7d46a9b2 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/InvalidRefException.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/InvalidRefException.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; import java.util.IllegalFormatException; diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ProjectRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ProjectRef.java new file mode 100644 index 00000000..a06da4c4 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ProjectRef.java @@ -0,0 +1,41 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/21/15. + */ +public interface ProjectRef + extends Serializable, Comparable +{ + String getGroupId(); + + String getArtifactId(); + + ProjectRef asProjectRef(); + + VersionlessArtifactRef asVersionlessPomArtifact(); + + VersionlessArtifactRef asVersionlessJarArtifact(); + + VersionlessArtifactRef asVersionlessArtifactRef( String type, String classifier ); + + VersionlessArtifactRef asVersionlessArtifactRef( TypeAndClassifier tc ); + + boolean matches( ProjectRef ref ); +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ProjectVersionRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ProjectVersionRef.java new file mode 100644 index 00000000..be8d6b67 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/ProjectVersionRef.java @@ -0,0 +1,81 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import org.commonjava.atlas.maven.ident.version.SingleVersion; +import org.commonjava.atlas.maven.ident.version.VersionSpec; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/21/15. + */ +public interface ProjectVersionRef + extends ProjectRef, VersionedRef,Serializable +{ + ProjectVersionRef asProjectVersionRef(); + + ArtifactRef asPomArtifact(); + + ArtifactRef asJarArtifact(); + + ArtifactRef asArtifactRef( String type, String classifier ); + + ArtifactRef asArtifactRef( TypeAndClassifier tc ); + + VersionSpec getVersionSpecRaw(); + + String getVersionStringRaw(); + + @Override + boolean isRelease(); + + @Override + boolean isSpecificVersion(); + + @Override + boolean matchesVersion( SingleVersion version ); + + @Override + ProjectVersionRef selectVersion( String version ); + + @Override + ProjectVersionRef selectVersion( String version, boolean force ); + + @Override + ProjectVersionRef selectVersion( SingleVersion version ); + + @Override + ProjectVersionRef selectVersion( SingleVersion version, boolean force ); + + ProjectVersionRef newRef( String groupId, String artifactId, SingleVersion version ); + + @Override + VersionSpec getVersionSpec(); + + boolean versionlessEquals( ProjectVersionRef other ); + + @Override + boolean isCompound(); + + @Override + boolean isSnapshot(); + + @Override + String getVersionString(); + + boolean isVariableVersion(); +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleArtifactRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleArtifactRef.java new file mode 100644 index 00000000..c7984b00 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleArtifactRef.java @@ -0,0 +1,220 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + +import java.io.Serializable; + +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.commonjava.atlas.maven.ident.version.SingleVersion; +import org.commonjava.atlas.maven.ident.version.VersionSpec; + +/** + * Represents an artifact, in Maven parlance. A tangible result of a build, which is typically made available in a Maven repository for others + * to consume. NOTE: a POM file is both a piece of metadata AND an artifact in the Maven world! + * + * Artifacts are based on the GAV coordinate for the project release, but also contain a type and optionally, a classifier. Type defaults to 'jar'. + * + * @see {@link SimpleProjectRef} + * @see {@link SimpleProjectVersionRef} + * + * @author jdcasey + */ +public class SimpleArtifactRef + extends SimpleProjectVersionRef + implements Serializable, ArtifactRef +{ + + private static final long serialVersionUID = 1L; + + private final TypeAndClassifier tc; + + public SimpleArtifactRef( final String groupId, final String artifactId, final VersionSpec version, + final String type, final String classifier ) + { + super( groupId, artifactId, version ); + this.tc = new SimpleTypeAndClassifier( type, classifier ); + } + + public SimpleArtifactRef( final ProjectVersionRef ref, final String type, final String classifier ) + { + super( ref.getGroupId(), ref.getArtifactId(), ref.getVersionSpecRaw(), ref.getVersionStringRaw() ); + this.tc = new SimpleTypeAndClassifier( type, classifier ); + } + + public SimpleArtifactRef( final ProjectVersionRef ref, final TypeAndClassifier tc ) + { + super( ref.getGroupId(), ref.getArtifactId(), ref.getVersionSpecRaw(), ref.getVersionStringRaw() ); + this.tc = getSimpleTypeAndClassifier( tc ); + } + + public SimpleArtifactRef( final String groupId, final String artifactId, final String versionSpec, + final String type, final String classifier ) + throws InvalidVersionSpecificationException + { + super( groupId, artifactId, versionSpec ); + this.tc = new SimpleTypeAndClassifier( type, classifier ); + } + + public SimpleArtifactRef( final ArtifactRef ref ) + { + super( ref ); + this.tc = getSimpleTypeAndClassifier( ref.getTypeAndClassifier() ); + } + + private SimpleTypeAndClassifier getSimpleTypeAndClassifier( final TypeAndClassifier tc ) + { + if ( tc instanceof SimpleTypeAndClassifier ) + { + return ( SimpleTypeAndClassifier ) tc; + } + else + { + return new SimpleTypeAndClassifier( tc.getType(), tc.getClassifier() ); + } + } + + @Override + public String toString() + { + return String.format( "%s:%s:%s:%s%s", getGroupId(), getArtifactId(), getType(), getVersionString(), + ( getClassifier() == null ? "" : ":" + getClassifier() ) ); + } + + public static SimpleArtifactRef parse( final String spec ) + { + final String[] parts = spec.split( ":" ); + + if ( parts.length < 3 || isEmpty( parts[0] ) || isEmpty( parts[1] ) || isEmpty( parts[2] ) ) + { + throw new InvalidRefException( + "SimpleArtifactRef must contain AT LEAST non-empty groupId, artifactId, AND version. (Given: '" + + spec + "')" ); + } + + final String g = parts[0]; + final String a = parts[1]; + + // assume we're actually parsing a GAV into a POM artifact... + String v = parts[2]; + String t = "pom"; + String c = null; + + if ( parts.length > 3 ) + { + // oops, it's a type, not a version...see toString() for the specification. + t = v; + v = parts[3]; + + if ( parts.length > 4 ) + { + c = parts[4]; + } + } + + // assume non-optional, because it might not matter if you're parsing a string like this...you'd be more careful if you were reading something + // that had an optional field, because it's not in the normal GATV[C] spec. + return new SimpleArtifactRef( g, a, v, t, c ); + } + + @Override + public SimpleArtifactRef newRef( final String groupId, final String artifactId, final SingleVersion version ) + { + return new SimpleArtifactRef( groupId, artifactId, version, tc.getType(), tc.getClassifier() ); + } + + @Override + public String getType() + { + return tc.getType(); + } + + @Override + public String getClassifier() + { + return tc.getClassifier(); + } + + @Override + public TypeAndClassifier getTypeAndClassifier() + { + return tc; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ( ( tc == null ) ? 0 : tc.hashCode() ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( !super.equals( obj ) ) + { + return false; + } + if ( !(obj instanceof ArtifactRef) ) + { + return false; + } + final ArtifactRef other = (ArtifactRef) obj; + + return artifactFieldsEqual( other ); + } + + private boolean artifactFieldsEqual( final ArtifactRef other ) + { + if ( tc == null ) + { + if ( other.getTypeAndClassifier() != null ) + { + return false; + } + } + else if ( !tc.equals( other.getTypeAndClassifier() ) ) + { + return false; + } + return true; + } + + @Override + public boolean versionlessEquals( final ProjectVersionRef other ) + { + if ( !super.versionlessEquals( other ) ) + { + return false; + } + + if ( !( other instanceof ArtifactRef ) ) + { + // compare vs. POM reference. + return artifactFieldsEqual( new SimpleArtifactRef( other, "pom", null ) ); + } + + return artifactFieldsEqual( (ArtifactRef) other ); + } + +} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ProjectRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleProjectRef.java similarity index 55% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ProjectRef.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleProjectRef.java index aaeb1c40..4b3e9bdb 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ProjectRef.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleProjectRef.java @@ -1,26 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import static org.apache.commons.lang.StringUtils.isEmpty; - -import java.io.Serializable; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import static org.apache.commons.lang3.StringUtils.isEmpty; /** - * Reference to a whole project (or module, in terms of Maven builds). This reference is not specific to a release of the project (see {@link ProjectVersionRef}). - * + * Reference to a whole project (or module, in terms of Maven builds). This reference is not specific to a release of the project (see {@link SimpleProjectVersionRef}). + * * @author jdcasey */ -public class ProjectRef - implements Serializable, Comparable +public class SimpleProjectRef + implements ProjectRef { private static final long serialVersionUID = 1L; @@ -31,71 +34,76 @@ public class ProjectRef // NEVER null private final String artifactId; - public ProjectRef( final String groupId, final String artifactId ) + public SimpleProjectRef( final String groupId, final String artifactId ) { if ( isEmpty( groupId ) || isEmpty( artifactId ) ) { - throw new InvalidRefException( "ProjectId must contain non-empty groupId AND artifactId. (Given: '" + groupId + "':'" + artifactId + "')" ); + throw new InvalidRefException( "ProjectId must contain non-empty groupId AND artifactId. (Given: '" + + groupId + "':'" + artifactId + "')" ); } this.groupId = groupId; this.artifactId = artifactId; } + public SimpleProjectRef( final ProjectRef ref ) + { + this.groupId = ref.getGroupId(); + this.artifactId = ref.getArtifactId(); + } + public static ProjectRef parse( final String ga ) { final String[] parts = ga.split( ":" ); if ( parts.length < 2 || isEmpty( parts[0] ) || isEmpty( parts[1] ) ) { - throw new InvalidRefException( "ProjectRef must contain non-empty groupId AND artifactId. (Given: '" + ga + "')" ); + throw new InvalidRefException( "ProjectRef must contain non-empty groupId AND artifactId. (Given: '" + ga + + "')" ); } - return new ProjectRef( parts[0], parts[1] ); + return new SimpleProjectRef( parts[0], parts[1] ); } + @Override public final String getGroupId() { return groupId; } + @Override public final String getArtifactId() { return artifactId; } + @Override public ProjectRef asProjectRef() { - return ProjectRef.class.equals( getClass() ) ? this : new ProjectRef( getGroupId(), getArtifactId() ); + return SimpleProjectRef.class.equals( getClass() ) ? this : new SimpleProjectRef( getGroupId(), getArtifactId() ); } + @Override public VersionlessArtifactRef asVersionlessPomArtifact() { - return asVersionlessArtifactRef( "pom", null, false ); + return asVersionlessArtifactRef( "pom", null ); } + @Override public VersionlessArtifactRef asVersionlessJarArtifact() { - return asVersionlessArtifactRef( "jar", null, false ); + return asVersionlessArtifactRef( "jar", null ); } + @Override public VersionlessArtifactRef asVersionlessArtifactRef( final String type, final String classifier ) { - return asVersionlessArtifactRef( type, classifier, false ); - } - - public VersionlessArtifactRef asVersionlessArtifactRef( final String type, final String classifier, final boolean optional ) - { - return new VersionlessArtifactRef( this, type, classifier, optional ); + return new SimpleVersionlessArtifactRef( this, type, classifier ); } + @Override public VersionlessArtifactRef asVersionlessArtifactRef( final TypeAndClassifier tc ) { - return asVersionlessArtifactRef( tc, false ); - } - - public VersionlessArtifactRef asVersionlessArtifactRef( final TypeAndClassifier tc, final boolean optional ) - { - return new VersionlessArtifactRef( this, tc, optional ); + return new SimpleVersionlessArtifactRef( this, tc ); } @Override @@ -125,34 +133,31 @@ public boolean equals( final Object obj ) { return false; } - if ( getClass() != obj.getClass() ) + if ( !(obj instanceof ProjectRef) ) { return false; } final ProjectRef other = (ProjectRef) obj; - if ( !artifactId.equals( other.artifactId ) ) + if ( !artifactId.equals( other.getArtifactId() ) ) { return false; } - if ( !groupId.equals( other.groupId ) ) - { - return false; - } - return true; + return groupId.equals( other.getGroupId() ); } @Override public int compareTo( final ProjectRef o ) { - int comp = groupId.compareTo( o.groupId ); + int comp = groupId.compareTo( o.getGroupId() ); if ( comp == 0 ) { - comp = artifactId.compareTo( o.artifactId ); + comp = artifactId.compareTo( o.getArtifactId() ); } - return 0; + return comp; } + @Override public boolean matches( final ProjectRef ref ) { if ( equals( ref ) ) @@ -168,13 +173,8 @@ public boolean matches( final ProjectRef ref ) } final String aidPattern = toWildcard( getArtifactId() ); - if ( !ref.getArtifactId() - .matches( aidPattern ) ) - { - return false; - } + return ref.getArtifactId().matches( aidPattern ); - return true; } private String toWildcard( final String val ) diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ProjectVersionRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleProjectVersionRef.java similarity index 58% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ProjectVersionRef.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleProjectVersionRef.java index 4032dcc5..e6579efd 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ProjectVersionRef.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleProjectVersionRef.java @@ -1,35 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import static org.apache.commons.lang.StringUtils.isEmpty; - -import java.io.Serializable; - -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.SingleVersion; -import org.commonjava.maven.atlas.ident.version.VersionSpec; -import org.commonjava.maven.atlas.ident.version.VersionUtils; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import org.apache.commons.lang3.StringUtils; +import org.commonjava.atlas.maven.ident.util.VersionUtils; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.commonjava.atlas.maven.ident.version.SingleVersion; +import org.commonjava.atlas.maven.ident.version.VersionSpec; + +import static org.apache.commons.lang3.StringUtils.isEmpty; /** - * Reference to a particular release of a project (or module, in terms of Maven builds). A release may contain many artifacts (see {@link ArtifactRef}). - * - * @see {@link ProjectRef} - * @see {@link ArtifactRef} - * + * Reference to a particular release of a project (or module, in terms of Maven builds). A release may contain many artifacts (see {@link SimpleArtifactRef}). + * + * @see {@link SimpleProjectRef} + * @see {@link SimpleArtifactRef} + * * @author jdcasey */ -public class ProjectVersionRef - extends ProjectRef - implements VersionedRef, Serializable +public class SimpleProjectVersionRef + extends SimpleProjectRef + implements ProjectVersionRef { private static final long serialVersionUID = 1L; @@ -39,93 +43,103 @@ public class ProjectVersionRef private String versionString; - public ProjectVersionRef( final ProjectRef ref, final VersionSpec versionSpec ) + public SimpleProjectVersionRef( final ProjectRef ref, final VersionSpec versionSpec ) { this( ref.getGroupId(), ref.getArtifactId(), versionSpec, null ); } - public ProjectVersionRef( final ProjectRef ref, final String versionSpec ) + public SimpleProjectVersionRef( final ProjectRef ref, final String versionSpec ) throws InvalidVersionSpecificationException { this( ref.getGroupId(), ref.getArtifactId(), versionSpec ); } - ProjectVersionRef( final String groupId, final String artifactId, final VersionSpec versionSpec, final String versionString ) + SimpleProjectVersionRef( final String groupId, final String artifactId, final VersionSpec versionSpec, + final String versionString ) { super( groupId, artifactId ); - if ( versionSpec == null && versionString == null ) + if ( versionSpec == null && StringUtils.isEmpty( versionString ) ) { - throw new InvalidRefException( "Version spec AND string cannot both be null for '" + groupId + ":" + artifactId + "'" ); + throw new InvalidRefException( + "Version spec AND string cannot both be empty for '" + groupId + ":" + artifactId + "'" ); } this.versionString = versionString; this.versionSpec = versionSpec; } - public ProjectVersionRef( final String groupId, final String artifactId, final VersionSpec versionSpec ) + public SimpleProjectVersionRef( final String groupId, final String artifactId, final VersionSpec versionSpec ) { this( groupId, artifactId, versionSpec, null ); } - public ProjectVersionRef( final String groupId, final String artifactId, final String versionString ) + public SimpleProjectVersionRef( final String groupId, final String artifactId, final String versionString ) throws InvalidVersionSpecificationException { this( groupId, artifactId, null, versionString ); } + public SimpleProjectVersionRef( final ProjectVersionRef ref ) + { + super( ref ); + this.versionSpec = ref.getVersionSpecRaw(); + this.versionString = ref.getVersionStringRaw(); + } + public static ProjectVersionRef parse( final String gav ) { final String[] parts = gav.split( ":" ); if ( parts.length < 3 || isEmpty( parts[0] ) || isEmpty( parts[1] ) || isEmpty( parts[2] ) ) { - throw new InvalidRefException( "ProjectVersionRef must contain non-empty groupId, artifactId, AND version. (Given: '" + gav + "')" ); + throw new InvalidRefException( + "ProjectVersionRef must contain non-empty groupId, artifactId, AND version. (Given: '" + + gav + "')" ); } - return new ProjectVersionRef( parts[0], parts[1], parts[2] ); + return new SimpleProjectVersionRef( parts[0], parts[1], parts[2] ); } - public ProjectVersionRef asProjectVersionRef() + @Override + public SimpleProjectVersionRef asProjectVersionRef() { - return ProjectVersionRef.class.equals( getClass() ) ? this : new ProjectVersionRef( getGroupId(), getArtifactId(), getVersionSpecRaw(), + return SimpleProjectVersionRef.class.equals( getClass() ) ? this : new SimpleProjectVersionRef( getGroupId(), + getArtifactId(), + getVersionSpecRaw(), getVersionStringRaw() ); } + @Override public ArtifactRef asPomArtifact() { - return asArtifactRef( "pom", null, false ); + return asArtifactRef( "pom", null ); } + @Override public ArtifactRef asJarArtifact() { - return asArtifactRef( "jar", null, false ); + return asArtifactRef( "jar", null ); } + @Override public ArtifactRef asArtifactRef( final String type, final String classifier ) { - return asArtifactRef( type, classifier, false ); - } - - public ArtifactRef asArtifactRef( final String type, final String classifier, final boolean optional ) - { - return new ArtifactRef( this, type, classifier, optional ); + return new SimpleArtifactRef( this, type, classifier ); } + @Override public ArtifactRef asArtifactRef( final TypeAndClassifier tc ) { - return asArtifactRef( tc, false ); - } - - public ArtifactRef asArtifactRef( final TypeAndClassifier tc, final boolean optional ) - { - return new ArtifactRef( this, tc, optional ); + return new SimpleArtifactRef( this, tc ); } - VersionSpec getVersionSpecRaw() + @Override + public VersionSpec getVersionSpecRaw() { return versionSpec; } - String getVersionStringRaw() + @Override + public String getVersionStringRaw() { return versionString; } @@ -149,27 +163,27 @@ public boolean matchesVersion( final SingleVersion version ) } @Override - public ProjectVersionRef selectVersion( final String version ) + public SimpleProjectVersionRef selectVersion( final String version ) { final SingleVersion single = VersionUtils.createSingleVersion( version ); return selectVersion( single, false ); } @Override - public ProjectVersionRef selectVersion( final String version, final boolean force ) + public SimpleProjectVersionRef selectVersion( final String version, final boolean force ) { final SingleVersion single = VersionUtils.createSingleVersion( version ); return selectVersion( single, force ); } @Override - public ProjectVersionRef selectVersion( final SingleVersion version ) + public SimpleProjectVersionRef selectVersion( final SingleVersion version ) { return selectVersion( version, false ); } @Override - public ProjectVersionRef selectVersion( final SingleVersion version, final boolean force ) + public SimpleProjectVersionRef selectVersion( final SingleVersion version, final boolean force ) { final VersionSpec versionSpec = getVersionSpec(); if ( versionSpec.equals( version ) ) @@ -179,16 +193,17 @@ public ProjectVersionRef selectVersion( final SingleVersion version, final boole if ( !force && !versionSpec.contains( version ) ) { - throw new IllegalArgumentException( "Specified version: " + version.renderStandard() + " is not contained in spec: " - + versionSpec.renderStandard() ); + throw new IllegalArgumentException( "Specified version: " + version.renderStandard() + + " is not contained in spec: " + versionSpec.renderStandard() ); } return newRef( getGroupId(), getArtifactId(), version ); } - protected ProjectVersionRef newRef( final String groupId, final String artifactId, final SingleVersion version ) + @Override + public SimpleProjectVersionRef newRef( final String groupId, final String artifactId, final SingleVersion version ) { - return new ProjectVersionRef( groupId, artifactId, version ); + return new SimpleProjectVersionRef( groupId, artifactId, version ); } @Override @@ -210,14 +225,10 @@ public int hashCode() return result; } + @Override public boolean versionlessEquals( final ProjectVersionRef other ) { - if ( this == other ) - { - return true; - } - - return super.equals( other ); + return this == other || super.equals( other ); } @Override @@ -231,10 +242,11 @@ public boolean equals( final Object obj ) { return false; } - if ( getClass() != obj.getClass() ) + if ( !(obj instanceof ProjectVersionRef) ) { return false; } + final ProjectVersionRef other = (ProjectVersionRef) obj; boolean result = true; try @@ -298,6 +310,7 @@ public String getVersionString() return versionString; } + @Override public boolean isVariableVersion() { return isCompound() || ( isSpecificVersion() && ( (SingleVersion) getVersionSpec() ).isLocalSnapshot() ); diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleTypeAndClassifier.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleTypeAndClassifier.java new file mode 100644 index 00000000..87bf9432 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleTypeAndClassifier.java @@ -0,0 +1,120 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + +public class SimpleTypeAndClassifier + implements TypeAndClassifier +{ + private static final long serialVersionUID = 1L; + + private final String type; + + private final String classifier; + + public SimpleTypeAndClassifier( final String type, final String classifier ) + { + this.type = type == null ? "jar" : type; + this.classifier = isEmpty( classifier ) ? null : classifier; + } + + public SimpleTypeAndClassifier( final String type ) + { + this( type, null ); + } + + public SimpleTypeAndClassifier() + { + this( null, null ); + } + + public SimpleTypeAndClassifier( TypeAndClassifier typeAndClassifier ) + { + this.type = typeAndClassifier.getType(); + this.classifier = typeAndClassifier.getClassifier(); + } + + @Override + public String getType() + { + return type == null ? "jar" : type; + } + + @Override + public String getClassifier() + { + return classifier; + } + + @Override + public String toString() + { + return String.format( "%s%s", type, ( classifier == null ? "" : ":" + classifier ) ); + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ( ( classifier == null ) ? 0 : classifier.hashCode() ); + result = prime * result + ( ( type == null ) ? 0 : type.hashCode() ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( obj == null ) + { + return false; + } + if ( !(obj instanceof TypeAndClassifier) ) + { + return false; + } + final TypeAndClassifier other = (TypeAndClassifier) obj; + if ( classifier == null ) + { + if ( other.getClassifier() != null ) + { + return false; + } + } + else if ( !classifier.equals( other.getClassifier() ) ) + { + return false; + } + if ( type == null ) + { + if ( other.getType() != null ) + { + return false; + } + } + else if ( !type.equals( other.getType() ) ) + { + return false; + } + return true; + } + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleVersionlessArtifactRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleVersionlessArtifactRef.java new file mode 100644 index 00000000..ac1a49b7 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/SimpleVersionlessArtifactRef.java @@ -0,0 +1,207 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; + +/** + * Special implementation of {@link SimpleArtifactRef} that forces all versions to ZERO, to allow calculation of transitive + * dependency graphs, where version collisions of the same project are likely. + * + * @author jdcasey + */ +public class SimpleVersionlessArtifactRef + extends SimpleProjectRef + implements VersionlessArtifactRef +{ + + private static final long serialVersionUID = 1L; + + private final TypeAndClassifier tc; + + public SimpleVersionlessArtifactRef( final ArtifactRef ref ) + { + super( ref.getGroupId(), ref.getArtifactId() ); + this.tc = ref.getTypeAndClassifier(); + } + + public SimpleVersionlessArtifactRef( final ProjectRef ref, final String type, final String classifier ) + { + super( ref.getGroupId(), ref.getArtifactId() ); + this.tc = new SimpleTypeAndClassifier( type, classifier ); + } + + public SimpleVersionlessArtifactRef( final ProjectRef ref, final TypeAndClassifier tc ) + { + super( ref.getGroupId(), ref.getArtifactId() ); + this.tc = tc == null ? new SimpleTypeAndClassifier() : tc; + } + + public SimpleVersionlessArtifactRef( final String groupId, final String artifactId, final String type, + final String classifier ) + throws InvalidVersionSpecificationException + { + super( groupId, artifactId ); + this.tc = new SimpleTypeAndClassifier( type, classifier ); + } + + public SimpleVersionlessArtifactRef( final VersionlessArtifactRef ref ) + { + super( ref ); + this.tc = ref.getTypeAndClassifier(); + } + + @Override + public String toString() + { + return String.format( "%s:%s:%s", getGroupId(), getArtifactId(), getTypeAndClassifier() ); + } + + public static VersionlessArtifactRef parse( final String spec ) + { + final String[] parts = spec.split( ":" ); + + if ( parts.length < 2 || isEmpty( parts[0] ) || isEmpty( parts[1] ) ) + { + throw new InvalidRefException( + "VersionlessArtifactRef must contain AT LEAST non-empty groupId and artifactId. (Given: '" + + spec + "')" ); + } + + final String g = parts[0]; + final String a = parts[1]; + + String t = "pom"; + String c = null; + + if ( parts.length > 2 ) + { + // we probably have a type in there. + t = parts[2]; + + if ( parts.length > 3 ) + { + // we have a classifier? What if it's GATV?? + // assume it's just a classifier... + c = parts[3]; + + if ( parts.length > 4 ) + { + // okay, wtf? It's a GATVC, and we need to shift to eliminate the V... + c = parts[4]; + } + } + } + + // assume non-optional, because it might not matter if you're parsing a string like this...you'd be more careful if you were reading something + // that had an optional field, because it's not in the normal GATV[C] spec. + return new SimpleVersionlessArtifactRef( g, a, t, c ); + } + + @Override + public String getType() + { + return tc.getType(); + } + + @Override + public String getClassifier() + { + return tc.getClassifier(); + } + + @Override + public TypeAndClassifier getTypeAndClassifier() + { + return tc; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ( ( tc == null ) ? 0 : tc.hashCode() ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( !super.equals( obj ) ) + { + return false; + } + if ( !(obj instanceof VersionlessArtifactRef) ) + { + return false; + } + final VersionlessArtifactRef other = (VersionlessArtifactRef) obj; + if ( tc == null ) + { + if ( other.getTypeAndClassifier() != null ) + { + return false; + } + } + else if ( !tc.equals( other.getTypeAndClassifier() ) ) + { + return false; + } + return true; + } + + @Override + public VersionlessArtifactRef asVersionlessPomArtifact() + { + return asVersionlessArtifactRef( "pom", null ); + } + + @Override + public VersionlessArtifactRef asVersionlessJarArtifact() + { + return asVersionlessArtifactRef( "jar", null ); + } + + @Override + public VersionlessArtifactRef asVersionlessArtifactRef( final String type, final String classifier ) + { + final TypeAndClassifier tc = new SimpleTypeAndClassifier( type, classifier ); + if ( SimpleVersionlessArtifactRef.class.equals( getClass() ) && this.tc.equals( tc ) ) + { + return this; + } + + return super.asVersionlessArtifactRef( type, classifier ); + } + + @Override + public VersionlessArtifactRef asVersionlessArtifactRef( final TypeAndClassifier tc ) + { + if ( SimpleVersionlessArtifactRef.class.equals( getClass() ) && this.tc.equals( tc ) ) + { + return this; + } + + return super.asVersionlessArtifactRef( tc ); + } +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/TypeAndClassifier.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/TypeAndClassifier.java new file mode 100644 index 00000000..682af2fd --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/TypeAndClassifier.java @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/21/15. + */ +public interface TypeAndClassifier + extends Serializable +{ + String getType(); + + String getClassifier(); +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/VersionedRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/VersionedRef.java new file mode 100644 index 00000000..72006deb --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/VersionedRef.java @@ -0,0 +1,49 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import java.io.Serializable; + +import org.commonjava.atlas.maven.ident.version.SingleVersion; +import org.commonjava.atlas.maven.ident.version.VersionSpec; + +public interface VersionedRef + extends Serializable +{ + + boolean isSpecificVersion(); + + boolean isRelease(); + + boolean isSnapshot(); + + boolean isCompound(); + + boolean matchesVersion( SingleVersion version ); + + VersionSpec getVersionSpec(); + + String getVersionString(); + + T selectVersion( String version ); + + T selectVersion( String version, boolean force ); + + T selectVersion( SingleVersion version ); + + T selectVersion( SingleVersion version, boolean force ); + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/VersionlessArtifactRef.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/VersionlessArtifactRef.java new file mode 100644 index 00000000..c088d6ab --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/ref/VersionlessArtifactRef.java @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +/** + * Created by jdcasey on 8/21/15. + */ +public interface VersionlessArtifactRef + extends ProjectRef +{ + String getType(); + + String getClassifier(); + + TypeAndClassifier getTypeAndClassifier(); + + @Override + VersionlessArtifactRef asVersionlessPomArtifact(); + + @Override + VersionlessArtifactRef asVersionlessJarArtifact(); + + @Override + VersionlessArtifactRef asVersionlessArtifactRef( String type, String classifier ); + + @Override + VersionlessArtifactRef asVersionlessArtifactRef( TypeAndClassifier tc ); + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ArtifactPathInfo.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ArtifactPathInfo.java new file mode 100644 index 00000000..b174066d --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ArtifactPathInfo.java @@ -0,0 +1,337 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import org.apache.commons.lang3.StringUtils; +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.version.part.SnapshotPart; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ArtifactPathInfo implements PathInfo +{ + private static final String GROUP_REGEX = "(([^/]+/)*[^/]+)"; // group 1~2 + + private static final String ARTIFACT_REGEX = "([^/]+)"; // group 3 + + private static final String VERSION_RAW_REGEX = "(([^/]+)(-SNAPSHOT)?)"; // group 4~6 + + private static final String CLASSIFIER_AND_TYPE = "-?(.+)"; + + // regex developed at: http://fiddle.re/tvk5 + private static final String ARTIFACT_PATH_REGEX = + "/?" + GROUP_REGEX + "/" + ARTIFACT_REGEX + "/" + VERSION_RAW_REGEX + "/(\\3-((\\4)|(\\5-" + + SnapshotUtils.RAW_REMOTE_SNAPSHOT_PART_PATTERN + "))" + CLASSIFIER_AND_TYPE + ")"; + + private static final int GROUP_ID_GROUP = 1; + + private static final int ARTIFACT_ID_GROUP = 3; + + private static final int FILE_GROUP = 7; + + private static final int VERSION_GROUP = 8; + + // Note: this looks a little ugly, but it's also caused by the "classifier with dots" problem in maven artifacts. + // So for the file types with more than one extension separated by dots, we should treat them as special types + // here and extract them before extract the classifier. + private static final Set DEFAULT_COMPOUND_EXTENSIONS_TYPES = + new HashSet<>( Arrays.asList( "tar.gz", "tar.bz2", "xml.gz", "spdx.rdf.xml" ) ); + + private static final String COMPOUND_EXTENSIONS_PROP = "atlas.compoext.types"; + + private static final Set CHECKSUM_TYPES = new HashSet<>( Arrays.asList( ".md5", ".sha1", ".sha128", ".sha256", ".sha384", ".sha512" ) ); + + public static ArtifactPathInfo parse( final String path ) + { + if ( path == null || path.isEmpty() ) + { + return null; + } + + final Matcher matcher = Pattern.compile( ARTIFACT_PATH_REGEX ) + .matcher( path.replace( '\\', '/' ) ); + if ( !matcher.matches() ) + { + return null; + } + + final int groupCount = matcher.groupCount(); + final String g = matcher.group( GROUP_ID_GROUP ) + .replace( '/', '.' ); + final String a = matcher.group( ARTIFACT_ID_GROUP ); + final String v = matcher.group( VERSION_GROUP ); + final String f = matcher.group( FILE_GROUP ); + + // Validate that the filename follows standard Maven layout: {artifactId}-{version}-... + // This prevents mis-parsing paths that match the regex pattern but don't follow Maven conventions + String expectedPrefix = a + "-" + v; + if ( !f.startsWith( expectedPrefix ) || f.contains( "/" ) ) + { + return null; + } + + String c = ""; + String t = null; + + String left = matcher.group( groupCount ); + + // If the path is a checksum path, we should abandon the checksum type and analyze its real artifact. + String checksumType = null; + for ( String type : CHECKSUM_TYPES ) + { + if ( left.endsWith( type ) ) + { + left = left.substring( 0, left.length() - type.length() ); + checksumType = type; + break; + } + } + + // The classifier can contain dots or hyphens, it is hard to separate it from type. e.g, + // wildfly8.1.3.jar, project-sources.tar.gz, etc. We don't have a very solid pattern to match the classifier. + // Here we use the best guess. + final String typesFromSys = System.getProperty( COMPOUND_EXTENSIONS_PROP ); + final Set compoundedExtensions = new HashSet<>( DEFAULT_COMPOUND_EXTENSIONS_TYPES ); + if ( StringUtils.isNotBlank( typesFromSys ) ) + { + for ( final String type : typesFromSys.split( "," ) ) + { + compoundedExtensions.add( type.trim() ); + } + } + for ( String type : compoundedExtensions ) + { + if ( left.endsWith( type ) ) + { + t = type; + break; + } + } + if ( t == null || t.isEmpty() ) + { + t = left.substring( left.lastIndexOf( "." ) + 1 ); // Otherwise, use the simple file ext as type + } + + + int extLen = t.length() + 1; // plus len of "." + int leftLen = left.length(); + if ( leftLen > extLen ) + { + c = left.substring( 0, leftLen - extLen ); + } + + if ( checksumType != null && CHECKSUM_TYPES.contains( checksumType ) ) + { + t = t + checksumType; + } + + return new ArtifactPathInfo( g, a, v, c, t, f, path ); + } + + private final String groupId; + + private final String artifactId; + + private final String version; + + private final String classifier; + + private final String type; + + private final String file; + + private final String fullPath; + + private final boolean isSnapshot; + + private final String releaseVersion; + + public ArtifactPathInfo( final String groupId, final String artifactId, final String version, final String file, + final String fullPath ) + { + this( groupId, artifactId, version, null, "jar", file, fullPath ); + } + + public ArtifactPathInfo( final String groupId, final String artifactId, final String version, + final String classifier, final String type, final String file, final String fullPath ) + { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + this.classifier = classifier; + this.type = type; + this.file = file; + this.fullPath = fullPath; + this.isSnapshot = SnapshotUtils.isSnapshotVersion( version ); + this.releaseVersion = calcReleaseVersion( version ); + } + + private String calcReleaseVersion( String version ) + { + int index = version.indexOf( "-" ); + if ( index > 0 ) + { + return version.substring( 0, index ); + } + return version; + } + + public String getReleaseVersion() + { + return releaseVersion; + } + + public boolean isSnapshot() + { + return isSnapshot; + } + + public synchronized SnapshotPart getSnapshotInfo() + { + return SnapshotUtils.extractSnapshotVersionPart(version); + } + + public String getGroupId() + { + return groupId; + } + + public String getArtifactId() + { + return artifactId; + } + + public String getVersion() + { + return version; + } + + public String getClassifier() + { + return classifier; + } + + public String getType() + { + return type; + } + + @Override + public String getFile() + { + return file; + } + + @Override + public String getFullPath() + { + return fullPath; + } + + @Override + public String toString() + { + return String.format( "ArtifactPathInfo [groupId=%s, artifactId=%s, version=%s, file=%s]", groupId, artifactId, + version, file ); + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ( ( artifactId == null ) ? 0 : artifactId.hashCode() ); + result = prime * result + ( ( file == null ) ? 0 : file.hashCode() ); + result = prime * result + ( ( groupId == null ) ? 0 : groupId.hashCode() ); + result = prime * result + ( ( version == null ) ? 0 : version.hashCode() ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( obj == null ) + { + return false; + } + if ( getClass() != obj.getClass() ) + { + return false; + } + final ArtifactPathInfo other = (ArtifactPathInfo) obj; + if ( artifactId == null ) + { + if ( other.artifactId != null ) + { + return false; + } + } + else if ( !artifactId.equals( other.artifactId ) ) + { + return false; + } + if ( file == null ) + { + if ( other.file != null ) + { + return false; + } + } + else if ( !file.equals( other.file ) ) + { + return false; + } + if ( groupId == null ) + { + if ( other.groupId != null ) + { + return false; + } + } + else if ( !groupId.equals( other.groupId ) ) + { + return false; + } + if ( version == null ) + { + return other.version == null; + } + else + return version.equals( other.version ); + } + + public ProjectVersionRef getProjectId() + { + return new SimpleProjectVersionRef( getGroupId(), getArtifactId(), getVersion() ); + } + + public ArtifactRef getArtifact() + { + return new SimpleArtifactRef( getGroupId(), getArtifactId(), getVersion(), getType(), getClassifier() ); + } + +} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/ArtifactRefComparator.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ArtifactRefComparator.java similarity index 60% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/util/ArtifactRefComparator.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/util/ArtifactRefComparator.java index 61ffa047..b5224a7e 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/ArtifactRefComparator.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ArtifactRefComparator.java @@ -1,18 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.util; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; import java.util.Comparator; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; public class ArtifactRefComparator implements Comparator diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/util/IdentityUtils.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/IdentityUtils.java new file mode 100644 index 00000000..0705c2ec --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/IdentityUtils.java @@ -0,0 +1,101 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; + +public final class IdentityUtils +{ + + private IdentityUtils() + { + } + + public static ArtifactRef artifact( final String groupId, final String artifactId, final String version ) + throws InvalidVersionSpecificationException + { + return new SimpleArtifactRef( projectVersion( groupId, artifactId, version ), null, null ); + } + + public static ArtifactRef artifact( final ProjectVersionRef ref ) + throws InvalidVersionSpecificationException + { + return new SimpleArtifactRef( ref, null, null ); + } + + public static ArtifactRef artifact( final String groupId, final String artifactId, final String version, + final String type, final String classifier ) + throws InvalidVersionSpecificationException + { + return new SimpleArtifactRef( projectVersion( groupId, artifactId, version ), type, classifier ); + } + + public static ArtifactRef artifact( final ProjectVersionRef dep, final String type, final String classifier ) + { + return new SimpleArtifactRef( dep, type, classifier ); + } + + public static ProjectVersionRef projectVersion( final String src ) + { + final String[] parts = src.split( ":" ); + if ( parts.length != 3 ) + { + throw new IllegalArgumentException( "Invalid: '" + src + + "'. Must contain exactly three fields separated by ':'" ); + } + + try + { + return new SimpleProjectVersionRef( parts[0], parts[1], parts[2] ); + } + catch ( final InvalidVersionSpecificationException e ) + { + throw new IllegalArgumentException( "Invalid: '" + src + "'. Version: '" + parts[2] + "' is invalid: " + + e.getMessage(), e ); + } + } + + public static ProjectVersionRef projectVersion( final String groupId, final String artifactId, final String version ) + throws InvalidVersionSpecificationException + { + return new SimpleProjectVersionRef( groupId, artifactId, version ); + } + + public static ProjectRef project( final String src ) + { + final String[] parts = src.split( ":" ); + if ( parts.length < 2 ) + { + throw new IllegalArgumentException( "Invalid: '" + src + + "'. Must contain at least two fields separated by ':'" ); + } + + return new SimpleProjectRef( parts[0], parts[1] ); + } + + public static ProjectRef project( final String groupId, final String artifactId ) + throws InvalidVersionSpecificationException + { + return new SimpleProjectRef( groupId, artifactId ); + } + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/util/JoinString.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/JoinString.java new file mode 100644 index 00000000..0c76b0a7 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/JoinString.java @@ -0,0 +1,49 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import static org.apache.commons.lang3.StringUtils.join; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; + +public class JoinString +{ + + private final String joint; + + private final Collection items; + + public JoinString( final String joint, final Collection items ) + { + this.joint = joint; + this.items = items == null ? Collections.emptyList() : items; + } + + public JoinString( final String joint, final Object[] items ) + { + this.joint = joint; + this.items = items == null ? Collections.emptyList() : Arrays.asList( items ); + } + + @Override + public String toString() + { + return join( items, joint ); + } + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/util/PathInfo.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/PathInfo.java new file mode 100644 index 00000000..b510f77f --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/PathInfo.java @@ -0,0 +1,23 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +public interface PathInfo +{ + String getFile(); + + String getFullPath(); +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ProjectVersionRefComparator.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ProjectVersionRefComparator.java new file mode 100644 index 00000000..583bb0a0 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/ProjectVersionRefComparator.java @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import java.util.Comparator; + +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.version.VersionSpec; + +public class ProjectVersionRefComparator + implements Comparator +{ + + @Override + public int compare( final ProjectVersionRef f, final ProjectVersionRef s ) + { + final int comp = f.compareTo( s ); // this compares groupId and artifactId ONLY + if ( comp == 0 ) + { + final VersionSpec fs = f.getVersionSpec(); + final VersionSpec ss = s.getVersionSpec(); + + return fs.compareTo( ss ); + } + + return comp; + } + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/util/SnapshotUtils.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/SnapshotUtils.java new file mode 100644 index 00000000..808d9a1b --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/SnapshotUtils.java @@ -0,0 +1,145 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.commonjava.atlas.maven.ident.version.part.SnapshotPart; + +public class SnapshotUtils +{ + + private static final String LAST_UPDATED_FORMAT = "yyyyMMddHHmmss"; + + public static final String SNAPSHOT_TSTAMP_FORMAT = "yyyyMMdd.HHmmss"; + + public static final String RAW_REMOTE_SNAPSHOT_PART_PATTERN = "([0-9]{8}.[0-9]{6})-([0-9]+)"; + + public static final String REMOTE_SNAPSHOT_PART_PATTERN = "^((.+)-)?" + RAW_REMOTE_SNAPSHOT_PART_PATTERN + "$"; + + public static final String LOCAL_SNAPSHOT_VERSION_PART = "-SNAPSHOT"; + + public static String generateSnapshotSuffix( final Date d, final int buildNumber ) + { + return generateSnapshotTimestamp( d ) + "-" + buildNumber; + } + + public static String generateSnapshotTimestamp( final Date d ) + { + return getFormat().format( d ); + } + + public static Date getCurrentTimestamp() + { + final Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); + cal.set( Calendar.MILLISECOND, 0 ); + return cal.getTime(); + } + + public static boolean isSnapshotVersion( final String literal ) + { + return literal.endsWith( LOCAL_SNAPSHOT_VERSION_PART ) || isRemoteSnapshotVersion( literal ); + } + + public static boolean isRemoteSnapshotVersion( final String literal ) + { + return literal.matches( REMOTE_SNAPSHOT_PART_PATTERN ); + } + + public static boolean isRemoteSnapshotVersionPart( final String literal ) + { + return literal.matches( REMOTE_SNAPSHOT_PART_PATTERN ); + } + + public static SnapshotPart parseRemoteSnapshotVersionPart( final String literal ) + { + final Pattern pattern = Pattern.compile( REMOTE_SNAPSHOT_PART_PATTERN ); + final Matcher matcher = pattern.matcher( literal ); + if ( matcher.matches() ) + { + final String tstamp = matcher.group( 3 ); + final String bn = matcher.group( 4 ); + if ( tstamp != null || bn != null ) + { + Date d; + try + { + d = parseSnapshotTimestamp( tstamp ); + } + catch ( final ParseException e ) + { + throw new IllegalArgumentException( "'" + literal + + "' is not a remote snapshot version-part (of the format: " + SNAPSHOT_TSTAMP_FORMAT + + "-NN (invalid timestamp)", e ); + } + final int build = Integer.parseInt( bn ); + + return new SnapshotPart( d, build, literal ); + } + } + + throw new IllegalArgumentException( "'" + literal + "' is not a remote snapshot version-part (of the format: " + + SNAPSHOT_TSTAMP_FORMAT + "-NN" ); + } + + public static Date parseSnapshotTimestamp( final String tstamp ) + throws ParseException + { + return getFormat().parse( tstamp ); + } + + private static DateFormat getFormat() + { + final SimpleDateFormat fmt = new SimpleDateFormat( SNAPSHOT_TSTAMP_FORMAT ); + // fmt.setTimeZone( TimeZone.getTimeZone( "UTC" ) ); + + return fmt; + } + + public static SnapshotPart extractSnapshotVersionPart( final String version ) + { + SnapshotPart part = null; + if ( SnapshotUtils.isRemoteSnapshotVersion( version ) ) + { + part = SnapshotUtils.parseRemoteSnapshotVersionPart( version ); + } + else if ( version.endsWith( LOCAL_SNAPSHOT_VERSION_PART ) ) + { + part = new SnapshotPart( LOCAL_SNAPSHOT_VERSION_PART ); + } + + return part; + } + + public static String generateUpdateTimestamp( final Date d ) + { + return new SimpleDateFormat( LAST_UPDATED_FORMAT ).format( d ); + } + + public static Date parseUpdateTimestamp( final String tstamp ) + throws ParseException + { + return new SimpleDateFormat( LAST_UPDATED_FORMAT ).parse( tstamp ); + } + +} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionUtils.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/VersionUtils.java similarity index 62% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionUtils.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/util/VersionUtils.java index 7c54e431..2d84c691 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionUtils.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/VersionUtils.java @@ -1,18 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; -import org.commonjava.maven.atlas.ident.version.parse.ParseException; -import org.commonjava.maven.atlas.ident.version.parse.TokenMgrError; -import org.commonjava.maven.atlas.ident.version.parse.VersionParser; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.commonjava.atlas.maven.ident.version.RangeVersionSpec; +import org.commonjava.atlas.maven.ident.version.SingleVersion; +import org.commonjava.atlas.maven.ident.version.VersionSpec; +import org.commonjava.atlas.maven.ident.version.parse.ParseException; +import org.commonjava.atlas.maven.ident.version.parse.TokenMgrError; +import org.commonjava.atlas.maven.ident.version.parse.VersionParser; public final class VersionUtils { @@ -99,4 +108,27 @@ public static SingleVersion createSingleVersion( final String version ) } } + public static boolean isValidSingleVersion( final String version ) + { + boolean result = true; + + if ( version == null || version.trim().length() < 1 ) + { + return false; + } + try + { + SingleVersion singleVersion = new VersionParser( version ).single(); + } + catch ( final ParseException e ) + { + result = false; + } + catch ( final TokenMgrError e ) + { + result = false; + } + return result; + } + } diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/VersionlessArtifactRefComparator.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/VersionlessArtifactRefComparator.java similarity index 58% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/util/VersionlessArtifactRefComparator.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/util/VersionlessArtifactRefComparator.java index dd9112fc..02a0ed15 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/VersionlessArtifactRefComparator.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/util/VersionlessArtifactRefComparator.java @@ -1,18 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.util; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; -import java.util.Comparator; +import org.commonjava.atlas.maven.ident.ref.VersionlessArtifactRef; -import org.commonjava.maven.atlas.ident.ref.VersionlessArtifactRef; +import java.util.Comparator; public class VersionlessArtifactRefComparator implements Comparator diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/CompoundVersionSpec.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/CompoundVersionSpec.java similarity index 88% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/CompoundVersionSpec.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/CompoundVersionSpec.java index 50d7f6ae..1acf4e62 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/CompoundVersionSpec.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/CompoundVersionSpec.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; import java.io.Serializable; import java.util.ArrayList; diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/InvalidVersionSpecificationException.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/InvalidVersionSpecificationException.java similarity index 59% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/InvalidVersionSpecificationException.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/InvalidVersionSpecificationException.java index 4aa02b66..493e8665 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/InvalidVersionSpecificationException.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/InvalidVersionSpecificationException.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; import java.util.IllegalFormatException; @@ -21,7 +26,8 @@ public class InvalidVersionSpecificationException private String version; - public InvalidVersionSpecificationException( final String version, final String message, final Throwable cause, final Object... params ) + public InvalidVersionSpecificationException( final String version, final String message, final Throwable cause, + final Object... params ) { super( "'" + version + "': " + message, cause ); this.params = params; diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/version/MultiVersionSpec.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/MultiVersionSpec.java new file mode 100644 index 00000000..625eb924 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/MultiVersionSpec.java @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; + +public interface MultiVersionSpec +{ + + boolean isPinned(); + + SingleVersion getPinnedVersion(); + + boolean isSnapshot(); + + boolean contains( VersionSpec spec ); + +} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/RangeVersionSpec.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/RangeVersionSpec.java similarity index 90% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/RangeVersionSpec.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/RangeVersionSpec.java index d90d50bc..1d09e2be 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/RangeVersionSpec.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/RangeVersionSpec.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; import java.io.Serializable; @@ -289,11 +294,7 @@ else if ( !upper.equals( other.upper ) ) { return false; } - if ( upperInclusive != other.upperInclusive ) - { - return false; - } - return true; + return upperInclusive == other.upperInclusive; } } diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/SingleVersion.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/SingleVersion.java similarity index 86% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/SingleVersion.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/SingleVersion.java index f82f1051..661135d7 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/SingleVersion.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/SingleVersion.java @@ -1,16 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; - -import static org.apache.commons.lang.StringUtils.join; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; + +import static org.apache.commons.lang3.StringUtils.join; import java.io.Serializable; import java.util.ArrayList; @@ -18,13 +23,13 @@ import java.util.List; import java.util.StringTokenizer; -import org.commonjava.maven.atlas.ident.version.part.NumericPart; -import org.commonjava.maven.atlas.ident.version.part.SeparatorPart; -import org.commonjava.maven.atlas.ident.version.part.SnapshotPart; -import org.commonjava.maven.atlas.ident.version.part.StringPart; -import org.commonjava.maven.atlas.ident.version.part.VersionPart; -import org.commonjava.maven.atlas.ident.version.part.VersionPartSeparator; -import org.commonjava.maven.atlas.ident.version.part.VersionPhrase; +import org.commonjava.atlas.maven.ident.version.part.NumericPart; +import org.commonjava.atlas.maven.ident.version.part.SeparatorPart; +import org.commonjava.atlas.maven.ident.version.part.SnapshotPart; +import org.commonjava.atlas.maven.ident.version.part.StringPart; +import org.commonjava.atlas.maven.ident.version.part.VersionPart; +import org.commonjava.atlas.maven.ident.version.part.VersionPartSeparator; +import org.commonjava.atlas.maven.ident.version.part.VersionPhrase; public class SingleVersion implements VersionSpec, Serializable @@ -84,9 +89,13 @@ private List parsePhrases( final List p ) final VersionPart part = parts.get( i ); final VersionPart next = i >= parts.size() - 1 ? null : parts.get( i + 1 ); - if ( ( part instanceof SeparatorPart ) && ( VersionPartSeparator.DASH == ( (SeparatorPart) part ).getValue() ) ) + if ( ( part instanceof SeparatorPart ) + && ( VersionPartSeparator.DASH == ( (SeparatorPart) part ).getValue() ) ) { - if ( prev != null && !( prev instanceof StringPart ) ) + // the next part is considering something like: "rebuild-SNAPTHOT" + final boolean prevNotString = !( prev instanceof StringPart ); + final boolean nextIsSnapshot = ( next != null && ( next instanceof SnapshotPart ) ); + if ( prev != null && ( prevNotString || nextIsSnapshot ) ) { try { @@ -112,7 +121,8 @@ private List parsePhrases( final List p ) i++; } } - else if ( ( ( part instanceof SnapshotPart ) || ( part instanceof StringPart ) ) && prev != null + else if ( ( ( part instanceof SnapshotPart ) || ( part instanceof StringPart ) ) + && prev != null && ( !( prev instanceof SeparatorPart ) || ( ( (SeparatorPart) prev ).getValue() != VersionPartSeparator.DASH ) ) ) { VersionPartSeparator sep = null; @@ -235,7 +245,8 @@ private void validate( final List parts ) { if ( part != parts.get( parts.size() - 1 ) && part instanceof SnapshotPart ) { - throw new InvalidVersionSpecificationException( rawExpression, "Snapshot marker MUST appear at the end of the version" ); + throw new InvalidVersionSpecificationException( rawExpression, + "Snapshot marker MUST appear at the end of the version" ); } } } @@ -470,4 +481,9 @@ else if ( !mine.isSilent() && !theirs.isSilent() ) return true; } + public SnapshotPart getSnapshotPart() + { + return isSnapshot() ? (SnapshotPart) getLastPart() : null; + } + } diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionSpec.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/VersionSpec.java similarity index 71% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionSpec.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/VersionSpec.java index 52e1d7ea..7bc27a22 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionSpec.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/VersionSpec.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; import java.io.Serializable; diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionSpecComparisons.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/VersionSpecComparisons.java similarity index 93% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionSpecComparisons.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/VersionSpecComparisons.java index 6d831d4d..53e2443d 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/VersionSpecComparisons.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/VersionSpecComparisons.java @@ -1,23 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; import java.util.ArrayList; import java.util.Comparator; import java.util.List; -import org.commonjava.maven.atlas.ident.version.part.NumericPart; -import org.commonjava.maven.atlas.ident.version.part.SeparatorPart; -import org.commonjava.maven.atlas.ident.version.part.VersionPart; -import org.commonjava.maven.atlas.ident.version.part.VersionPhrase; +import org.commonjava.atlas.maven.ident.version.part.NumericPart; +import org.commonjava.atlas.maven.ident.version.part.SeparatorPart; +import org.commonjava.atlas.maven.ident.version.part.VersionPart; +import org.commonjava.atlas.maven.ident.version.part.VersionPhrase; public final class VersionSpecComparisons { diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/NumericPart.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/NumericPart.java similarity index 75% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/NumericPart.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/NumericPart.java index 8144be0d..23967b44 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/NumericPart.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/NumericPart.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; import java.io.Serializable; import java.math.BigInteger; diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/SeparatorPart.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/SeparatorPart.java similarity index 63% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/SeparatorPart.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/SeparatorPart.java index 5df5daef..8663e63f 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/SeparatorPart.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/SeparatorPart.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; import java.io.Serializable; @@ -73,11 +78,7 @@ public boolean equals( final Object obj ) return false; } final SeparatorPart other = (SeparatorPart) obj; - if ( type != other.type ) - { - return false; - } - return true; + return type == other.type; } } diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/SnapshotPart.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/SnapshotPart.java similarity index 73% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/SnapshotPart.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/SnapshotPart.java index f64371ce..3fe52edb 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/SnapshotPart.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/SnapshotPart.java @@ -1,18 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; import java.io.Serializable; import java.util.Date; +import org.commonjava.atlas.maven.ident.util.SnapshotUtils; + public class SnapshotPart extends VersionPart implements Serializable @@ -26,7 +33,6 @@ public class SnapshotPart private final String literal; - // TODO: Parse into date and buildnumber for comparison public SnapshotPart( final Date timestamp, final int buildNumber, final String literal ) { this.timestamp = timestamp; @@ -36,8 +42,18 @@ public SnapshotPart( final Date timestamp, final int buildNumber, final String l public SnapshotPart( final String literal ) { - timestamp = null; - buildNumber = null; + if ( SnapshotUtils.isRemoteSnapshotVersionPart( literal ) ) + { + final SnapshotPart sp = SnapshotUtils.parseRemoteSnapshotVersionPart( literal ); + timestamp = sp.timestamp; + buildNumber = sp.buildNumber; + } + else + { + timestamp = null; + buildNumber = null; + } + this.literal = literal; } @@ -61,6 +77,11 @@ public boolean isLocalSnapshot() return timestamp == null; } + public boolean isRemoteSnapshot() + { + return timestamp != null; + } + @Override public String toString() { @@ -78,6 +99,7 @@ public String getValue() return renderStandard(); } + @Override public int compareTo( final VersionPart o ) { if ( o instanceof SnapshotPart ) @@ -90,14 +112,16 @@ public int compareTo( final VersionPart o ) { return getBuildNumber() - oSnap.getBuildNumber(); } + + return comp; } else if ( isLocalSnapshot() && !oSnap.isLocalSnapshot() ) { - return -1; + return 1; } else if ( !isLocalSnapshot() && oSnap.isLocalSnapshot() ) { - return 1; + return -1; } return 0; diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/StringPart.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/StringPart.java similarity index 89% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/StringPart.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/StringPart.java index cc91c175..02c7124d 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/StringPart.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/StringPart.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; import java.io.Serializable; import java.util.ArrayList; diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPart.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPart.java new file mode 100644 index 00000000..b645d5c2 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPart.java @@ -0,0 +1,40 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; + +import java.io.Serializable; + +public abstract class VersionPart + implements Comparable, Serializable +{ + + private static final long serialVersionUID = 1L; + + private boolean silent = false; + + public abstract String renderStandard(); + + final boolean isSilent() + { + return silent; + } + + final void setSilent( final boolean silent ) + { + this.silent = silent; + } + +} diff --git a/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPartSeparator.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPartSeparator.java new file mode 100644 index 00000000..fb8c5742 --- /dev/null +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPartSeparator.java @@ -0,0 +1,48 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; + +public enum VersionPartSeparator +{ + + BLANK( "" ), DASH( "-" ), UNDERSCORE( "_" ), DOT( "." ), PLUS("+"); + + private String rendered; + + VersionPartSeparator( final String rendered ) + { + this.rendered = rendered; + } + + public String getRenderedString() + { + return rendered; + } + + public static VersionPartSeparator find( final String literal ) + { + for ( final VersionPartSeparator vps : values() ) + { + if ( vps.rendered.equals( literal ) ) + { + return vps; + } + } + + return null; + } + +} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPhrase.java b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPhrase.java similarity index 87% rename from identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPhrase.java rename to identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPhrase.java index 3ba1b75c..01e67910 100644 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPhrase.java +++ b/identities/src/main/java/org/commonjava/atlas/maven/ident/version/part/VersionPhrase.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; import java.io.Serializable; import java.util.ArrayList; @@ -16,8 +21,8 @@ import java.util.Iterator; import java.util.List; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.VersionSpecComparisons; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.commonjava.atlas.maven.ident.version.VersionSpecComparisons; public class VersionPhrase implements Comparable, Serializable @@ -66,7 +71,8 @@ else if ( part instanceof SeparatorPart ) { silenced = true; } - else if ( ( part instanceof StringPart ) && ( (StringPart) part ).getZeroCompareIndex() == StringPart.ADJ_ZERO_EQUIV_INDEX ) + else if ( ( part instanceof StringPart ) + && ( (StringPart) part ).getZeroCompareIndex() == StringPart.ADJ_ZERO_EQUIV_INDEX ) { silenced = true; } @@ -167,7 +173,8 @@ private void validate( final List parts ) { if ( part != parts.get( parts.size() - 1 ) && part instanceof SnapshotPart ) { - throw new InvalidVersionSpecificationException( renderStandard( parts ), "Snapshot marker MUST appear at the end of the version" ); + throw new InvalidVersionSpecificationException( renderStandard( parts ), + "Snapshot marker MUST appear at the end of the version" ); } } } @@ -186,8 +193,10 @@ public VersionPhrase getBaseVersion() } catch ( final InvalidVersionSpecificationException e ) { - throw new InvalidVersionSpecificationException( e.getVersion(), "Cannot create base version for non-release: %s. Reason: %s", e, - e.getVersion(), e.getMessage() ); + throw new InvalidVersionSpecificationException( + e.getVersion(), + "Cannot create base version for non-release: %s. Reason: %s", + e, e.getVersion(), e.getMessage() ); } } diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ScopeTransitivity.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/ScopeTransitivity.java deleted file mode 100644 index 0da34cc1..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ScopeTransitivity.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident; - -import static org.commonjava.maven.atlas.ident.DependencyScope.embedded; -import static org.commonjava.maven.atlas.ident.DependencyScope.runtime; -import static org.commonjava.maven.atlas.ident.DependencyScope.toolchain; - -public enum ScopeTransitivity -{ - maven - { - @Override - public DependencyScope getChildFor( final DependencyScope scope ) - { - switch ( scope ) - { - case provided: - return null; - case embedded: - return embedded; - case toolchain: - return toolchain; - default: - return runtime; - } - } - }, - - all - { - @Override - public DependencyScope getChildFor( final DependencyScope scope ) - { - return scope; - } - }; - - public abstract DependencyScope getChildFor( DependencyScope scope ); - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ArtifactRef.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ArtifactRef.java deleted file mode 100644 index 41df7dc6..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/ArtifactRef.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import java.io.Serializable; - -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.SingleVersion; -import org.commonjava.maven.atlas.ident.version.VersionSpec; - -/** - * Represents an artifact, in Maven parlance. A tangible result of a build, which is typically made available in a Maven repository for others - * to consume. NOTE: a POM file is both a piece of metadata AND an artifact in the Maven world! - * - * Artifacts are based on the GAV coordinate for the project release, but also contain a type and optionally, a classifier. Type defaults to 'jar'. - * - * @see {@link ProjectRef} - * @see {@link ProjectVersionRef} - * - * @author jdcasey - */ -public class ArtifactRef - extends ProjectVersionRef - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - private final TypeAndClassifier tc; - - private final boolean optional; - - public ArtifactRef( final String groupId, final String artifactId, final VersionSpec version, final String type, final String classifier, - final boolean optional ) - { - super( groupId, artifactId, version ); - this.optional = optional; - this.tc = new TypeAndClassifier( type, classifier ); - } - - public ArtifactRef( final ProjectVersionRef ref, final String type, final String classifier, final boolean optional ) - { - super( ref.getGroupId(), ref.getArtifactId(), ref.getVersionSpecRaw(), ref.getVersionStringRaw() ); - this.optional = optional; - this.tc = new TypeAndClassifier( type, classifier ); - } - - public ArtifactRef( final ProjectVersionRef ref, final TypeAndClassifier tc, final boolean optional ) - { - super( ref.getGroupId(), ref.getArtifactId(), ref.getVersionSpecRaw(), ref.getVersionStringRaw() ); - this.tc = tc; - this.optional = optional; - } - - public ArtifactRef( final String groupId, final String artifactId, final String versionSpec, final String type, final String classifier, - final boolean optional ) - throws InvalidVersionSpecificationException - { - super( groupId, artifactId, versionSpec ); - this.tc = new TypeAndClassifier( type, classifier ); - this.optional = optional; - } - - @Override - protected ProjectVersionRef newRef( final String groupId, final String artifactId, final SingleVersion version ) - { - return new ArtifactRef( groupId, artifactId, version, tc.getType(), tc.getClassifier(), optional ); - } - - public String getType() - { - return tc.getType(); - } - - public String getClassifier() - { - return tc.getClassifier(); - } - - public TypeAndClassifier getTypeAndClassifier() - { - return tc; - } - - public ArtifactRef setOptional( final boolean optional ) - { - if ( this.optional == optional ) - { - return this; - } - - return new ArtifactRef( this, getType(), getClassifier(), optional ); - } - - public boolean isOptional() - { - return optional; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( ( tc == null ) ? 0 : tc.hashCode() ); - result = prime * result + Boolean.valueOf( optional ) - .hashCode(); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final ArtifactRef other = (ArtifactRef) obj; - - return artifactFieldsEqual( other ); - } - - private boolean artifactFieldsEqual( final ArtifactRef other ) - { - if ( tc == null ) - { - if ( other.tc != null ) - { - return false; - } - } - else if ( !tc.equals( other.tc ) ) - { - return false; - } - return true; - } - - @Override - public String toString() - { - return String.format( "%s:%s:%s:%s%s", getGroupId(), getArtifactId(), getType(), getVersionString(), ( getClassifier() == null ? "" : ":" - + getClassifier() ) ); - } - - @Override - public boolean versionlessEquals( final ProjectVersionRef other ) - { - if ( !super.versionlessEquals( other ) ) - { - return false; - } - - if ( !( other instanceof ArtifactRef ) ) - { - // compare vs. POM reference. - return artifactFieldsEqual( new ArtifactRef( other, "pom", null, false ) ); - } - - return artifactFieldsEqual( (ArtifactRef) other ); - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/TypeAndClassifier.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/TypeAndClassifier.java deleted file mode 100644 index b6df3afc..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/TypeAndClassifier.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import static org.apache.commons.lang.StringUtils.isEmpty; - -public class TypeAndClassifier -{ - private final String type; - - private final String classifier; - - public TypeAndClassifier( final String type, final String classifier ) - { - this.type = type == null ? "jar" : type; - this.classifier = isEmpty( classifier ) ? null : classifier; - } - - public TypeAndClassifier( final String type ) - { - this( type, null ); - } - - public TypeAndClassifier() - { - this( null, null ); - } - - public String getType() - { - return type; - } - - public String getClassifier() - { - return classifier; - } - - @Override - public String toString() - { - return String.format( "%s%s", type, ( classifier == null ? "" : ":" + classifier ) ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( classifier == null ) ? 0 : classifier.hashCode() ); - result = prime * result + ( ( type == null ) ? 0 : type.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final TypeAndClassifier other = (TypeAndClassifier) obj; - if ( classifier == null ) - { - if ( other.classifier != null ) - { - return false; - } - } - else if ( !classifier.equals( other.classifier ) ) - { - return false; - } - if ( type == null ) - { - if ( other.type != null ) - { - return false; - } - } - else if ( !type.equals( other.type ) ) - { - return false; - } - return true; - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/VersionedRef.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/VersionedRef.java deleted file mode 100644 index 59271f27..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/VersionedRef.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import java.io.Serializable; - -import org.commonjava.maven.atlas.ident.version.SingleVersion; -import org.commonjava.maven.atlas.ident.version.VersionSpec; - -public interface VersionedRef - extends Serializable -{ - - boolean isSpecificVersion(); - - boolean isRelease(); - - boolean isSnapshot(); - - boolean isCompound(); - - boolean matchesVersion( SingleVersion version ); - - VersionSpec getVersionSpec(); - - String getVersionString(); - - T selectVersion( String version ); - - T selectVersion( String version, boolean force ); - - T selectVersion( SingleVersion version ); - - T selectVersion( SingleVersion version, boolean force ); - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/VersionlessArtifactRef.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/VersionlessArtifactRef.java deleted file mode 100644 index d2fe2838..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/ref/VersionlessArtifactRef.java +++ /dev/null @@ -1,176 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; - -/** - * Special implementation of {@link ArtifactRef} that forces all versions to ZERO, to allow calculation of transitive - * dependency graphs, where version collisions of the same project are likely. - * - * @author jdcasey - */ -public class VersionlessArtifactRef - extends ProjectRef -{ - - private static final long serialVersionUID = 1L; - - private final TypeAndClassifier tc; - - private final boolean optional; - - public VersionlessArtifactRef( final ArtifactRef ref ) - { - super( ref.getGroupId(), ref.getArtifactId() ); - this.optional = ref.isOptional(); - this.tc = ref.getTypeAndClassifier(); - } - - public VersionlessArtifactRef( final ProjectRef ref, final String type, final String classifier, final boolean optional ) - { - super( ref.getGroupId(), ref.getArtifactId() ); - this.optional = optional; - this.tc = new TypeAndClassifier( type, classifier ); - } - - public VersionlessArtifactRef( final ProjectRef ref, final TypeAndClassifier tc, final boolean optional ) - { - super( ref.getGroupId(), ref.getArtifactId() ); - this.tc = tc == null ? new TypeAndClassifier() : tc; - this.optional = optional; - } - - public VersionlessArtifactRef( final String groupId, final String artifactId, final String type, final String classifier, final boolean optional ) - throws InvalidVersionSpecificationException - { - super( groupId, artifactId ); - this.tc = new TypeAndClassifier( type, classifier ); - this.optional = optional; - } - - @Override - public String toString() - { - return String.format( "%s:%s:%s", getGroupId(), getArtifactId(), getTypeAndClassifier() ); - } - - public String getType() - { - return tc.getType(); - } - - public String getClassifier() - { - return tc.getClassifier(); - } - - public TypeAndClassifier getTypeAndClassifier() - { - return tc; - } - - public boolean isOptional() - { - return optional; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( optional ? 1231 : 1237 ); - result = prime * result + ( ( tc == null ) ? 0 : tc.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final VersionlessArtifactRef other = (VersionlessArtifactRef) obj; - if ( optional != other.optional ) - { - return false; - } - if ( tc == null ) - { - if ( other.tc != null ) - { - return false; - } - } - else if ( !tc.equals( other.tc ) ) - { - return false; - } - return true; - } - - @Override - public VersionlessArtifactRef asVersionlessPomArtifact() - { - return asVersionlessArtifactRef( "pom", null, false ); - } - - @Override - public VersionlessArtifactRef asVersionlessJarArtifact() - { - return asVersionlessArtifactRef( "jar", null, false ); - } - - @Override - public VersionlessArtifactRef asVersionlessArtifactRef( final String type, final String classifier ) - { - return asVersionlessArtifactRef( type, classifier, false ); - } - - @Override - public VersionlessArtifactRef asVersionlessArtifactRef( final String type, final String classifier, final boolean optional ) - { - final TypeAndClassifier tc = new TypeAndClassifier( type, classifier ); - if ( VersionlessArtifactRef.class.equals( getClass() ) && this.tc.equals( tc ) && this.optional == optional ) - { - return this; - } - - return super.asVersionlessArtifactRef( type, classifier, optional ); - } - - @Override - public VersionlessArtifactRef asVersionlessArtifactRef( final TypeAndClassifier tc ) - { - return asVersionlessArtifactRef( tc, false ); - } - - @Override - public VersionlessArtifactRef asVersionlessArtifactRef( final TypeAndClassifier tc, final boolean optional ) - { - if ( VersionlessArtifactRef.class.equals( getClass() ) && this.tc.equals( tc ) && this.optional == optional ) - { - return this; - } - - return super.asVersionlessArtifactRef( tc, optional ); - } -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/IdentityUtils.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/util/IdentityUtils.java deleted file mode 100644 index 765e6972..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/IdentityUtils.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.util; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; - -public final class IdentityUtils -{ - - private IdentityUtils() - { - } - - public static ArtifactRef artifact( final String groupId, final String artifactId, final String version ) - throws InvalidVersionSpecificationException - { - return new ArtifactRef( projectVersion( groupId, artifactId, version ), null, null, false ); - } - - public static ArtifactRef artifact( final ProjectVersionRef ref ) - throws InvalidVersionSpecificationException - { - return new ArtifactRef( ref, null, null, false ); - } - - public static ArtifactRef artifact( final String groupId, final String artifactId, final String version, final String type, - final String classifier, final boolean optional ) - throws InvalidVersionSpecificationException - { - return new ArtifactRef( projectVersion( groupId, artifactId, version ), type, classifier, optional ); - } - - public static ArtifactRef artifact( final ProjectVersionRef dep, final String type, final String classifier, final boolean optional ) - { - return new ArtifactRef( dep, type, classifier, optional ); - } - - public static ProjectVersionRef projectVersion( final String src ) - { - final String[] parts = src.split( ":" ); - if ( parts.length != 3 ) - { - throw new IllegalArgumentException( "Invalid: '" + src + "'. Must contain exactly three fields separated by ':'" ); - } - - try - { - return new ProjectVersionRef( parts[0], parts[1], parts[2] ); - } - catch ( final InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( "Invalid: '" + src + "'. Version: '" + parts[2] + "' is invalid: " + e.getMessage(), e ); - } - } - - public static ProjectVersionRef projectVersion( final String groupId, final String artifactId, final String version ) - throws InvalidVersionSpecificationException - { - return new ProjectVersionRef( groupId, artifactId, version ); - } - - public static ProjectRef project( final String src ) - { - final String[] parts = src.split( ":" ); - if ( parts.length < 2 ) - { - throw new IllegalArgumentException( "Invalid: '" + src + "'. Must contain at least two fields separated by ':'" ); - } - - return new ProjectRef( parts[0], parts[1] ); - } - - public static ProjectRef project( final String groupId, final String artifactId ) - throws InvalidVersionSpecificationException - { - return new ProjectRef( groupId, artifactId ); - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/JoinString.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/util/JoinString.java deleted file mode 100644 index e3f2d742..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/JoinString.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.util; - -import static org.apache.commons.lang.StringUtils.join; - -import java.util.Arrays; -import java.util.Collection; - -public class JoinString -{ - - private final String joint; - - private final Collection items; - - public JoinString( final String joint, final Collection items ) - { - this.joint = joint; - this.items = items; - } - - public JoinString( final String joint, final Object[] items ) - { - this.joint = joint; - this.items = Arrays.asList( items ); - } - - @Override - public String toString() - { - return join( items, joint ); - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/ProjectVersionRefComparator.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/util/ProjectVersionRefComparator.java deleted file mode 100644 index e6758606..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/util/ProjectVersionRefComparator.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.util; - -import java.util.Comparator; - -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.VersionSpec; - -public class ProjectVersionRefComparator - implements Comparator -{ - - @Override - public int compare( final ProjectVersionRef f, final ProjectVersionRef s ) - { - final int comp = f.compareTo( s ); // this compares groupId and artifactId ONLY - if ( comp == 0 ) - { - final VersionSpec fs = f.getVersionSpec(); - final VersionSpec ss = s.getVersionSpec(); - - return fs.compareTo( ss ); - } - - return comp; - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/MultiVersionSpec.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/version/MultiVersionSpec.java deleted file mode 100644 index 80102e43..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/MultiVersionSpec.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; - -public interface MultiVersionSpec -{ - - boolean isPinned(); - - SingleVersion getPinnedVersion(); - - boolean isSnapshot(); - - boolean contains( VersionSpec spec ); - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPart.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPart.java deleted file mode 100644 index b7e14d40..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPart.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; - -import java.io.Serializable; - -public abstract class VersionPart - implements Comparable, Serializable -{ - - private static final long serialVersionUID = 1L; - - private boolean silent = false; - - public abstract String renderStandard(); - - final boolean isSilent() - { - return silent; - } - - final void setSilent( final boolean silent ) - { - this.silent = silent; - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPartSeparator.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPartSeparator.java deleted file mode 100644 index 4d1bbc1c..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/part/VersionPartSeparator.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; - -public enum VersionPartSeparator -{ - - BLANK( "" ), DASH( "-" ), UNDERSCORE( "_" ), DOT( "." ); - - private String rendered; - - private VersionPartSeparator( final String rendered ) - { - this.rendered = rendered; - } - - public String getRenderedString() - { - return rendered; - } - - public static VersionPartSeparator find( final String literal ) - { - for ( final VersionPartSeparator vps : values() ) - { - if ( vps.rendered.equals( literal ) ) - { - return vps; - } - } - - return null; - } - -} diff --git a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/transform/SnapshotSupport.java b/identities/src/main/java/org/commonjava/maven/atlas/ident/version/transform/SnapshotSupport.java deleted file mode 100644 index 908781a5..00000000 --- a/identities/src/main/java/org/commonjava/maven/atlas/ident/version/transform/SnapshotSupport.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.transform; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -public class SnapshotSupport -{ - - public static final String SNAPSHOT_TSTAMP_FORMAT = "yyyyMMdd.hhmmss"; - - public static final String SNAPSHOT_PATTERN = "^((.+)-)?([0-9]{8}.[0-9]{6})-([0-9]+)$"; - - public static String generateSnapshotSuffix( final Date d, final int buildNumber ) - { - return generateSnapshotTimestamp( d ) + "-" + buildNumber; - } - - public static String generateSnapshotTimestamp( final Date d ) - { - return getFormat().format( d ); - } - - public static Date parseSnapshotTimestamp( final String tstamp ) - throws ParseException - { - return getFormat().parse( tstamp ); - } - - private static DateFormat getFormat() - { - final SimpleDateFormat fmt = new SimpleDateFormat( SNAPSHOT_TSTAMP_FORMAT ); - fmt.setTimeZone( TimeZone.getTimeZone( "UTC" ) ); - - return fmt; - } - -} diff --git a/identities/src/main/javacc/version.jj b/identities/src/main/javacc/version.jj index 373f80c2..d97598fb 100644 --- a/identities/src/main/javacc/version.jj +++ b/identities/src/main/javacc/version.jj @@ -8,11 +8,11 @@ options { } PARSER_BEGIN(VersionParser) -package org.commonjava.maven.atlas.ident.version.parse; +package org.commonjava.atlas.maven.ident.version.parse; -import org.commonjava.maven.atlas.ident.version.*; -import org.commonjava.maven.atlas.ident.version.part.*; -import org.commonjava.maven.atlas.ident.version.transform.*; +import org.commonjava.atlas.maven.ident.util.*; +import org.commonjava.atlas.maven.ident.version.*; +import org.commonjava.atlas.maven.ident.version.part.*; import java.util.*; import java.text.*; import java.io.*; @@ -63,7 +63,7 @@ public class VersionParser { try { - return new SnapshotPart( SnapshotSupport.parseSnapshotTimestamp( date ), Integer.parseInt( buildnum ), date + "-" + buildnum ); + return new SnapshotPart( SnapshotUtils.parseSnapshotTimestamp( date ), Integer.parseInt( buildnum ), date + "-" + buildnum ); } catch ( java.text.ParseException e ) { @@ -112,6 +112,7 @@ TOKEN: | | | +| | | ) > | @@ -381,6 +382,8 @@ VersionPartSeparator sep = null; {sep = VersionPartSeparator.DOT;} | {sep = VersionPartSeparator.DASH;} +| + {sep = VersionPartSeparator.PLUS;} | {sep = VersionPartSeparator.UNDERSCORE;} ) diff --git a/identities/src/site/site.xml b/identities/src/site/site.xml index 92932c60..6214a864 100644 --- a/identities/src/site/site.xml +++ b/identities/src/site/site.xml @@ -1,13 +1,20 @@ set = new HashSet(); + assertThat( set.add( ref1 ), equalTo( true ) ); + assertThat( set.add( ref2 ), equalTo( false ) ); + } + + @Test + public void addTwoIdenticalCompoundRefsToASetAndVerifyThatOnlyOneIsAdded() + throws InvalidVersionSpecificationException + { + final ProjectVersionRef ref1 = new SimpleProjectVersionRef( "org.foo", "bar", "[1.1.1-baz-1,1.1.1-baz-2]" ); + final ProjectVersionRef ref2 = new SimpleProjectVersionRef( "org.foo", "bar", "[1.1.1-baz-1,1.1.1-baz-2]" ); + + assertThat( ref1, equalTo( ref2 ) ); + + final Set set = new HashSet(); + assertThat( set.add( ref1 ), equalTo( true ) ); + assertThat( set.add( ref2 ), equalTo( false ) ); + } + + @Test + public void parseSnapshotWithNumericRebuildSuffix() + throws InvalidVersionSpecificationException + { + final String ver = "org.bar:foo:2.1.1.rebuild-SNAPSHOT"; + + final ProjectVersionRef ref = SimpleProjectVersionRef.parse( ver ); + //new SimpleProjectVersionRef( "g", "a", ver ); + final VersionSpec spec = ref.getVersionSpec(); + final List phrases = spec.getSingleVersion().getVersionPhrases(); + + System.out.println ("### ref " + ref + " and snap " + ref.getVersionSpec().isSnapshot()); + System.out.println ("### spec " + spec.getSingleVersion() + " and " + spec.renderStandard()); + System.out.println ("### phrases " + phrases); + System.out.println ("### snap " + spec.getSingleVersion().getSnapshotPart().renderStandard()); + System.out.println ("### snap " + spec.getSingleVersion().isSnapshot()); + + assertTrue ( ref.isSnapshot() ); + assertThat( "org.bar:foo:" + spec.renderStandard(), equalTo( ver ) ); + assertTrue( "SNAPSHOT".equals( spec.getSingleVersion().getSnapshotPart().renderStandard() ) ); + assertTrue( phrases.size() == 3); + } + +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/ref/SimpleArtifactRefTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/ref/SimpleArtifactRefTest.java new file mode 100644 index 00000000..86a3e325 --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/ref/SimpleArtifactRefTest.java @@ -0,0 +1,87 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.InvalidRefException; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.junit.Test; + +public class SimpleArtifactRefTest +{ + + @Test( expected = InvalidRefException.class ) + public void failParsingGA() + { + SimpleArtifactRef.parse( "org.foo:bar" ); + } + + @Test + public void parseGAVIntoPOM() + { + final String g = "org.foo"; + final String a = "bar"; + final String v = "1.0"; + + final ArtifactRef ar = SimpleArtifactRef.parse( String.format( "%s:%s:%s", g, a, v ) ); + + assertThat( ar.getGroupId(), equalTo( g ) ); + assertThat( ar.getArtifactId(), equalTo( a ) ); + assertThat( ar.getVersionString(), equalTo( v ) ); + assertThat( ar.getType(), equalTo( "pom" ) ); + assertThat( ar.getClassifier(), nullValue() ); + } + + @Test + public void parseGATV() + { + final String g = "org.foo"; + final String a = "bar"; + final String v = "1.0"; + final String t = "zip"; + + final ArtifactRef ar = SimpleArtifactRef.parse( String.format( "%s:%s:%s:%s", g, a, t, v ) ); + + assertThat( ar.getGroupId(), equalTo( g ) ); + assertThat( ar.getArtifactId(), equalTo( a ) ); + assertThat( ar.getVersionString(), equalTo( v ) ); + assertThat( ar.getType(), equalTo( t ) ); + assertThat( ar.getClassifier(), nullValue() ); + } + + @Test + public void parseGATVC() + { + final String g = "org.foo"; + final String a = "bar"; + final String v = "1.0"; + final String t = "zip"; + final String c = "sources"; + + final ArtifactRef ar = SimpleArtifactRef.parse( String.format( "%s:%s:%s:%s:%s", g, a, t, v, c ) ); + + assertThat( ar.getGroupId(), equalTo( g ) ); + assertThat( ar.getArtifactId(), equalTo( a ) ); + assertThat( ar.getVersionString(), equalTo( v ) ); + assertThat( ar.getType(), equalTo( t ) ); + assertThat( ar.getClassifier(), equalTo( c ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/ref/VersionlessArtifactRefTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/ref/VersionlessArtifactRefTest.java new file mode 100644 index 00000000..65c738a5 --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/ref/VersionlessArtifactRefTest.java @@ -0,0 +1,202 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.ref; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleVersionlessArtifactRef; +import org.commonjava.atlas.maven.ident.ref.VersionlessArtifactRef; +import org.junit.Test; + +public class VersionlessArtifactRefTest +{ + + @Test + public void parseGA() + { + final String g = "org.foo"; + final String a = "bar"; + final VersionlessArtifactRef var = SimpleVersionlessArtifactRef.parse( String.format( "%s:%s", g, a ) ); + + assertThat( var.getGroupId(), equalTo( g ) ); + assertThat( var.getArtifactId(), equalTo( a ) ); + assertThat( var.getType(), equalTo( "pom" ) ); + assertThat( var.getClassifier(), nullValue() ); + } + + @Test + public void parseGAT() + { + final String g = "org.foo"; + final String a = "bar"; + final String t = "zip"; + + final VersionlessArtifactRef var = SimpleVersionlessArtifactRef.parse( String.format( "%s:%s:%s", g, a, t ) ); + + assertThat( var.getGroupId(), equalTo( g ) ); + assertThat( var.getArtifactId(), equalTo( a ) ); + assertThat( var.getType(), equalTo( t ) ); + assertThat( var.getClassifier(), nullValue() ); + } + + @Test + public void parseGATC() + { + final String g = "org.foo"; + final String a = "bar"; + final String t = "zip"; + final String c = "sources"; + + final VersionlessArtifactRef var = SimpleVersionlessArtifactRef.parse( + String.format( "%s:%s:%s:%s", g, a, t, c ) ); + + assertThat( var.getGroupId(), equalTo( g ) ); + assertThat( var.getArtifactId(), equalTo( a ) ); + assertThat( var.getType(), equalTo( t ) ); + assertThat( var.getClassifier(), equalTo( c ) ); + } + + @Test + public void parseGATVC_VersionDiscarded() + { + final String g = "org.foo"; + final String a = "bar"; + final String t = "zip"; + final String v = "1.0"; + final String c = "sources"; + + final VersionlessArtifactRef var = + SimpleVersionlessArtifactRef.parse( String.format( "%s:%s:%s:%s:%s", g, a, t, v, c ) ); + + assertThat( var.getGroupId(), equalTo( g ) ); + assertThat( var.getArtifactId(), equalTo( a ) ); + assertThat( var.getType(), equalTo( t ) ); + assertThat( var.getClassifier(), equalTo( c ) ); + } + + @Test + public void parseGATV_MistakeForGATC() + { + final String g = "org.foo"; + final String a = "bar"; + final String t = "zip"; + final String v = "1.0"; + + final VersionlessArtifactRef var = SimpleVersionlessArtifactRef.parse( + String.format( "%s:%s:%s:%s", g, a, t, v ) ); + + assertThat( var.getGroupId(), equalTo( g ) ); + assertThat( var.getArtifactId(), equalTo( a ) ); + assertThat( var.getType(), equalTo( t ) ); + assertThat( var.getClassifier(), equalTo( v ) ); + } + + @Test + public void parseGATVC() + { + final String g = "org.foo"; + final String a = "bar"; + final VersionlessArtifactRef var = SimpleVersionlessArtifactRef.parse( String.format( "%s:%s", g, a ) ); + + assertThat( var.getGroupId(), equalTo( g ) ); + assertThat( var.getArtifactId(), equalTo( a ) ); + assertThat( var.getType(), equalTo( "pom" ) ); + assertThat( var.getClassifier(), nullValue() ); + } + + @Test + public void twoIdenticalArtifactsWrappedInVersionlessInstanceAreEqual_DefaultTypeAndClassifier() + { + final ProjectVersionRef pvr = new SimpleProjectVersionRef( "group", "artifact", "1" ); + final ArtifactRef r1 = new SimpleArtifactRef( pvr, null, null ); + final ArtifactRef r2 = new SimpleArtifactRef( pvr, null, null ); + + final VersionlessArtifactRef vr1 = new SimpleVersionlessArtifactRef( r1 ); + final VersionlessArtifactRef vr2 = new SimpleVersionlessArtifactRef( r2 ); + + assertThat( vr1, equalTo( vr2 ) ); + assertThat( vr1.hashCode(), equalTo( vr2.hashCode() ) ); + } + + @Test + public void twoArtifactsWrappedInVersionlessInstanceAreNotEqualWhenTypeDiffers() + { + final ProjectVersionRef pvr = new SimpleProjectVersionRef( "group", "artifact", "1" ); + final ArtifactRef r1 = new SimpleArtifactRef( pvr, "jar", null ); + final ArtifactRef r2 = new SimpleArtifactRef( pvr, "pom", null ); + + final VersionlessArtifactRef vr1 = new SimpleVersionlessArtifactRef( r1 ); + final VersionlessArtifactRef vr2 = new SimpleVersionlessArtifactRef( r2 ); + + assertThat( vr1.equals( vr2 ), equalTo( false ) ); + assertThat( vr1.hashCode() == vr2.hashCode(), equalTo( false ) ); + } + + @Test + public void twoArtifactsWrappedInVersionlessInstanceAreNotEqualWhenClassifierDiffers() + { + final ProjectVersionRef pvr = new SimpleProjectVersionRef( "group", "artifact", "1" ); + final ArtifactRef r1 = new SimpleArtifactRef( pvr, "jar", null ); + final ArtifactRef r2 = new SimpleArtifactRef( pvr, "jar", "foo" ); + + final VersionlessArtifactRef vr1 = new SimpleVersionlessArtifactRef( r1 ); + final VersionlessArtifactRef vr2 = new SimpleVersionlessArtifactRef( r2 ); + + assertThat( vr1.equals( vr2 ), equalTo( false ) ); + assertThat( vr1.hashCode() == vr2.hashCode(), equalTo( false ) ); + } + + @Test + public void twoArtifactsWrappedInVersionlessInstanceAreEqualWhenVersionDiffers() + { + final ProjectVersionRef pvr1 = new SimpleProjectVersionRef( "group", "artifact", "1" ); + final ProjectVersionRef pvr2 = new SimpleProjectVersionRef( "group", "artifact", "2" ); + final ArtifactRef r1 = new SimpleArtifactRef( pvr1, null, null ); + final ArtifactRef r2 = new SimpleArtifactRef( pvr2, null, null ); + + final VersionlessArtifactRef vr1 = new SimpleVersionlessArtifactRef( r1 ); + final VersionlessArtifactRef vr2 = new SimpleVersionlessArtifactRef( r2 ); + + assertThat( vr1, equalTo( vr2 ) ); + assertThat( vr1.hashCode(), equalTo( vr2.hashCode() ) ); + } + + @Test + public void twoArtifactsWrappedInVersionlessInstanceAreEqualWhenVersionDiffersWithRange() + { + final ProjectVersionRef pvr1 = new SimpleProjectVersionRef( "group", "artifact", "1" ); + final ProjectVersionRef pvr2 = new SimpleProjectVersionRef( "group", "artifact", "[2,3.1]" ); + final ArtifactRef r1 = new SimpleArtifactRef( pvr1, null, null ); + final ArtifactRef r2 = new SimpleArtifactRef( pvr2, null, null ); + + // trigger parsing. + r1.getVersionSpec(); + r2.getVersionSpec(); + + final VersionlessArtifactRef vr1 = new SimpleVersionlessArtifactRef( r1 ); + final VersionlessArtifactRef vr2 = new SimpleVersionlessArtifactRef( r2 ); + + assertThat( vr1, equalTo( vr2 ) ); + assertThat( vr1.hashCode(), equalTo( vr2.hashCode() ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/util/ArtifactPathInfoTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/util/ArtifactPathInfoTest.java new file mode 100644 index 00000000..a28bfc7b --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/util/ArtifactPathInfoTest.java @@ -0,0 +1,243 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.commonjava.atlas.maven.ident.version.part.SnapshotPart; +import org.junit.Test; + +import java.text.SimpleDateFormat; + +public class ArtifactPathInfoTest +{ + + @Test + public void matchSnapshotUIDVersion() + { + final String path = + "/path/to/unsigner-maven-plugin/0.2-SNAPSHOT/unsigner-maven-plugin-0.2-20120307.200227-1.jar"; + assertThat( ArtifactPathInfo.parse( path ) + .isSnapshot(), equalTo( true ) ); + } + + @Test + public void matchSnapshotNonUIDVersion() + { + final String path = "/path/to/unsigner-maven-plugin/0.2-SNAPSHOT/unsigner-maven-plugin-0.2-SNAPSHOT.jar"; + assertThat( ArtifactPathInfo.parse( path ) + .isSnapshot(), equalTo( true ) ); + } + + @Test + public void dontMatchNonSnapshotVersion() + { + final String path = "/path/to/unsigner-maven-plugin/0.2/unsigner-maven-plugin-0.2.jar"; + assertThat( ArtifactPathInfo.parse( path ) + .isSnapshot(), equalTo( false ) ); + } + + @Test + public void matchNormalClassifier() + { + String path = "/org/apache/commons/commons-lang3/3.0.0/commons-lang3-3.0.0-test.jar"; + ArtifactPathInfo pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getVersion(), equalTo( "3.0.0" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "test" ) ); + assertThat( pathInfo.getType(), equalTo( "jar" ) ); + + path = "/org/apache/commons/commons-lang3/3.0.0/commons-lang3-3.0.0-test.tar.gz"; + pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getVersion(), equalTo( "3.0.0" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "test" ) ); + assertThat( pathInfo.getType(), equalTo( "tar.gz" ) ); + } + + @Test + public void matchNormalClassifier2() + { + String path = "/org/jboss/modules/jboss-modules/1.5.0.Final-temporary-redhat-00033/jboss-modules-1.5.0.Final-temporary-redhat-00033-project-sources.tar.gz"; + ArtifactPathInfo pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getVersion(), equalTo( "1.5.0.Final-temporary-redhat-00033" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "project-sources" ) ); + assertThat( pathInfo.getType(), equalTo( "tar.gz" ) ); + } + + @Test + public void matchGAWithClassifier() + { + String path = "/org/apache/commons/commons-lang3/3.0.0.GA/commons-lang3-3.0.0.GA-test.jar"; + ArtifactPathInfo pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getVersion(), equalTo( "3.0.0.GA" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "test" ) ); + assertThat( pathInfo.getType(), equalTo( "jar" ) ); + + path = "/org/apache/commons/commons-lang3/3.0.0.GA/commons-lang3-3.0.0.GA-test.tar.gz"; + pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getVersion(), equalTo( "3.0.0.GA" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "test" ) ); + assertThat( pathInfo.getType(), equalTo( "tar.gz" ) ); + } + + @Test + public void matchClassifierWithDot() + { + String path = + "/org/uberfire/showcase-distribution-wars/7.33.0.Final-redhat-00003/showcase-distribution-wars-7.33.0.Final-redhat-00003-wildfly8.1.war"; + ArtifactPathInfo pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getClassifier(), equalTo( "wildfly8.1" ) ); + assertThat( pathInfo.getType(), equalTo( "war" ) ); + + path = + "/org/uberfire/showcase-distribution-wars/7.33.0.Final-redhat-00003/showcase-distribution-wars-7.33.0.Final-redhat-00003-wildfly8.2.3.0.tar.gz"; + pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getClassifier(), equalTo( "wildfly8.2.3.0" ) ); + assertThat( pathInfo.getType(), equalTo( "tar.gz" ) ); + + path = + "/org/uberfire/showcase-distribution-wars/7.33.0.Final-redhat-00003/showcase-distribution-wars-7.33.0.Final-redhat-00003-wildfly.8.2.3.0.tar.gz"; + pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getClassifier(), equalTo( "wildfly.8.2.3.0" ) ); + assertThat( pathInfo.getType(), equalTo( "tar.gz" ) ); + } + + @Test + public void testSnapshotPath() + { + final String path = "/org/commonjava/maven/galley/galley-transport-httpclient/0.10.4-SNAPSHOT/galley-transport-httpclient-0.10.4-20160229.212037-2.pom"; + ArtifactPathInfo info = ArtifactPathInfo.parse( path ); + SnapshotPart snap = info.getSnapshotInfo(); + assertEquals( "0.10.4", info.getReleaseVersion() ); + assertTrue( snap.isRemoteSnapshot() ); + assertEquals( "0.10.4-20160229.212037-2", snap.getValue() ); + assertEquals( "0.10.4-20160229.212037-2", snap.getLiteral() ); + assertEquals( 2, snap.getBuildNumber() ); + assertEquals( "20160229", new SimpleDateFormat( "yyyyMMdd" ).format( snap.getTimestamp() ) ); + } + + @Test + public void matchCompoundExtTypes1() + { + String path = + "/com/github/jomrazek/jomrazek-empty/1.0.1.redhat-00010/jomrazek-empty-1.0.1.redhat-00010-src.tar.bz2"; + ArtifactPathInfo info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "1.0.1.redhat-00010" ) ); + assertThat( info.getClassifier(), equalTo( "src" ) ); + assertThat( info.getType(), equalTo( "tar.bz2" ) ); + + path = + "/io/quarkus/platform/quarkus-google-cloud-services-bom-quarkus-platform-descriptor/2.13.7.Final-redhat-00001/quarkus-google-cloud-services-bom-quarkus-platform-descriptor-2.13.7.Final-redhat-00001-2.13.7.Final-redhat-00001.json"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "2.13.7.Final-redhat-00001" ) ); + assertThat( info.getClassifier(), equalTo( "2.13.7.Final-redhat-00001" ) ); + assertThat( info.getType(), equalTo( "json" ) ); + + path = + "/org/apache/cxf/cxf-repository/3.2.7.fuse-750011-redhat-00001/cxf-repository-3.2.7.fuse-750011-redhat-00001.xml.gz"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "3.2.7.fuse-750011-redhat-00001" ) ); + assertThat( info.getClassifier(), equalTo( "" ) ); + assertThat( info.getType(), equalTo( "xml.gz" ) ); + + path = + "/org/apache/commons/commons-compress/1.26.0.temporary-redhat-00002/commons-compress-1.26.0.temporary-redhat-00002.spdx.rdf.xml"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "1.26.0.temporary-redhat-00002" ) ); + assertThat( info.getClassifier(), equalTo( "" ) ); + assertThat( info.getType(), equalTo( "spdx.rdf.xml" ) ); + + + } + + @Test + public void matchCompoundExtTypes2(){ + System.setProperty("atlas.compoext.types", "a.b.c, x.y.z"); + + String path = + "/com/example/example-artifact/1.0.0.redhat-00001/example-artifact-1.0.0.redhat-00001-x.y.z.tar"; + ArtifactPathInfo info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "1.0.0.redhat-00001" ) ); + assertThat( info.getClassifier(), equalTo( "x.y.z" ) ); + assertThat( info.getType(), equalTo( "tar" ) ); + + path = + "/com/example/example-artifact/1.0.0.redhat-00001/example-artifact-1.0.0.redhat-00001.a.b.c"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "1.0.0.redhat-00001" ) ); + assertThat( info.getClassifier(), equalTo( "" ) ); + assertThat( info.getType(), equalTo( "a.b.c" ) ); + + path = + "/com/example/example-artifact/1.0.0.redhat-00001/example-artifact-1.0.0.redhat-00001-sources.a.b.c"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "1.0.0.redhat-00001" ) ); + assertThat( info.getClassifier(), equalTo( "sources" ) ); + assertThat( info.getType(), equalTo( "a.b.c" ) ); + } + + @Test + public void testNonStandardRpmPathReturnsNull() + { + // RPM path where filename doesn't follow Maven naming convention + String path = "/org/jboss/pnc/rpm/org/hibernate/search/hibernate-search-integrationtest-jakarta-jb-eap-8.0-rhel-9/6.2.2.Final/eap8-hibernate-search-6.2.2-1.Final.1.el8.src.rpm"; + ArtifactPathInfo info = ArtifactPathInfo.parse( path ); + assertThat( info, equalTo( null ) ); + } + + @Test + public void testChecksumTypes() + { + String path = + "/com/webauthn4j/webauthn4j-test/0.12.0.RELEASE-redhat-00002/webauthn4j-test-0.12.0.RELEASE-redhat-00002-sources.jar.md5"; + ArtifactPathInfo info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "0.12.0.RELEASE-redhat-00002" ) ); + assertThat( info.getClassifier(), equalTo( "sources" ) ); + assertThat( info.getType(), equalTo( "jar.md5" ) ); + + path = + "com/github/jomrazek/jomrazek-empty/1.0.1.redhat-00010/jomrazek-empty-1.0.1.redhat-00010-src.tar.bz2.sha1"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "1.0.1.redhat-00010" ) ); + assertThat( info.getClassifier(), equalTo( "src" ) ); + assertThat( info.getType(), equalTo( "tar.bz2.sha1" ) ); + + path = "/org/apache/commons/commons-lang3/3.0.0.GA/commons-lang3-3.0.0.GA-test.tar.gz.sha128"; + info = ArtifactPathInfo.parse( path ); + assertThat( info.getVersion(), equalTo( "3.0.0.GA" ) ); + assertThat( info.getClassifier(), equalTo( "test" ) ); + assertThat( info.getType(), equalTo( "tar.gz.sha128" ) ); + + path = + "/org/jboss/modules/jboss-modules/1.5.0.Final-temporary-redhat-00033/jboss-modules-1.5.0.Final-temporary-redhat-00033-project-sources.tar.gz.sha256"; + ArtifactPathInfo pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getVersion(), equalTo( "1.5.0.Final-temporary-redhat-00033" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "project-sources" ) ); + assertThat( pathInfo.getType(), equalTo( "tar.gz.sha256" ) ); + + path = + "/com/webauthn4j/webauthn4j-test/0.12.0.RELEASE-redhat-00002/webauthn4j-test-0.12.0.RELEASE-redhat-00002-sources.jar.sha512"; + pathInfo = ArtifactPathInfo.parse( path ); + assertThat( pathInfo.getGroupId(), equalTo( "com.webauthn4j" ) ); + assertThat( pathInfo.getArtifactId(), equalTo( "webauthn4j-test" ) ); + assertThat( pathInfo.getVersion(), equalTo( "0.12.0.RELEASE-redhat-00002" ) ); + assertThat( pathInfo.getClassifier(), equalTo( "sources" ) ); + assertThat( pathInfo.getType(), equalTo( "jar.sha512" ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/util/SnapshotUtilsTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/util/SnapshotUtilsTest.java new file mode 100644 index 00000000..d02ad713 --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/util/SnapshotUtilsTest.java @@ -0,0 +1,78 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.util; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.text.ParseException; +import java.util.Date; + +import org.commonjava.atlas.maven.ident.util.SnapshotUtils; +import org.junit.Test; + +public class SnapshotUtilsTest +{ + + @Test + public void roundTripSnapshotTimestamp_StartWithString() + throws ParseException + { + final String tstamp = "20140828.225831"; + + System.out.println( tstamp ); + + final Date d = SnapshotUtils.parseSnapshotTimestamp( tstamp ); + + final String result = SnapshotUtils.generateSnapshotTimestamp( d ); + System.out.println( result ); + + assertThat( result, equalTo( tstamp ) ); + } + + @Test + public void roundTripSnapshotTimestamp() + throws ParseException + { + final Date d = SnapshotUtils.getCurrentTimestamp(); + + System.out.println( d ); + final String tstamp = SnapshotUtils.generateSnapshotTimestamp( d ); + System.out.println( tstamp ); + + final Date result = SnapshotUtils.parseSnapshotTimestamp( tstamp ); + System.out.println( result ); + + assertThat( result, equalTo( d ) ); + } + + @Test + public void roundTripLastUpdatedTimestamp() + throws ParseException + { + final Date d = SnapshotUtils.getCurrentTimestamp(); + + System.out.println( d ); + final String tstamp = SnapshotUtils.generateUpdateTimestamp( d ); + System.out.println( tstamp ); + + final Date result = SnapshotUtils.parseUpdateTimestamp( tstamp ); + System.out.println( result ); + + assertThat( result, equalTo( d ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/SingleVersionComparisonsTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/SingleVersionComparisonsTest.java similarity index 94% rename from identities/src/test/java/org/commonjava/maven/atlas/ident/version/SingleVersionComparisonsTest.java rename to identities/src/test/java/org/commonjava/atlas/maven/ident/version/SingleVersionComparisonsTest.java index b3034434..d1b57362 100644 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/SingleVersionComparisonsTest.java +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/SingleVersionComparisonsTest.java @@ -1,14 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -29,7 +34,7 @@ * under the License. */ -import static org.apache.commons.lang.StringUtils.join; +import static org.apache.commons.lang3.StringUtils.join; import static org.junit.Assert.fail; import java.text.NumberFormat; @@ -37,9 +42,7 @@ import java.util.List; import java.util.Locale; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.SingleVersion; -import org.commonjava.maven.atlas.ident.version.VersionUtils; +import org.commonjava.atlas.maven.ident.util.VersionUtils; import org.junit.After; import org.junit.Rule; import org.junit.Test; @@ -199,6 +202,12 @@ private void checkVersionsOrder( final String v1, final String v2 ) checkTrue( "expected > 0: " + v2 + " > " + v1 + " (got: " + comp + ")", comp > 0 ); } + @Test + public void testZeroFill() + { + checkVersionsEqual( "7", "7.0.0" ); + } + @Test public void testVersionsQualifier() throws InvalidVersionSpecificationException diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionParserTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionParserTest.java similarity index 56% rename from identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionParserTest.java rename to identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionParserTest.java index b6f54ef3..c05a389d 100644 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionParserTest.java +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionParserTest.java @@ -1,17 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; -import org.commonjava.maven.atlas.ident.version.VersionSpec; -import org.commonjava.maven.atlas.ident.version.parse.VersionParser; +import org.commonjava.atlas.maven.ident.version.VersionSpec; +import org.commonjava.atlas.maven.ident.version.parse.VersionParser; import org.junit.Test; public class VersionParserTest @@ -67,4 +72,13 @@ public void parseSingleVersionWithExtendedDateTimeFormat() System.out.println( parsed ); } + @Test + public void parseSingleVersionWithPlusSeparator() + throws Exception + { + final String version = "9+181-r4173-1"; + final VersionSpec parsed = new VersionParser( version ).parse(); + + System.out.println( parsed ); + } } diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionRangeTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionRangeTest.java new file mode 100644 index 00000000..58500de9 --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionRangeTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import org.commonjava.atlas.maven.ident.util.VersionUtils; +import org.junit.Test; + +public class VersionRangeTest +{ + + @Test + public void identialRangeEquality() + throws InvalidVersionSpecificationException + { + final RangeVersionSpec r1 = VersionUtils.createRange( "[1.1.1-baz-1,1.1.1-baz-2]" ); + final RangeVersionSpec r2 = VersionUtils.createRange( "[1.1.1-baz-1,1.1.1-baz-2]" ); + + assertThat( r1.renderStandard(), equalTo( r2.renderStandard() ) ); + assertThat( r1.hashCode(), equalTo( r2.hashCode() ) ); + assertThat( r1, equalTo( r2 ) ); + assertThat( r2, equalTo( r1 ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionUtilsTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionUtilsTest.java new file mode 100644 index 00000000..1e18f35d --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/VersionUtilsTest.java @@ -0,0 +1,48 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version; + +import org.commonjava.atlas.maven.ident.util.VersionUtils; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +public class VersionUtilsTest +{ + + @Test + public void createSingleTimestampVersionFormat() + throws Exception + { + final String spec = "20031129.200437"; + final SingleVersion version = VersionUtils.createSingleVersion( spec ); + + System.out.println( version ); + } + + @Test + public void SingleVersionStringValidationTest() throws Exception + { + final String invalid1 = "abc@1"; + final String invalid2 = "abc//1"; + final String valid = "abc123a."; + + assertThat( VersionUtils.isValidSingleVersion( invalid1 ), equalTo( false ) ); + assertThat( VersionUtils.isValidSingleVersion( invalid2 ), equalTo( false ) ); + assertThat( VersionUtils.isValidSingleVersion( valid ), equalTo( true ) ); + } +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/version/part/NumericPartTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/part/NumericPartTest.java new file mode 100644 index 00000000..3194bcdf --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/part/NumericPartTest.java @@ -0,0 +1,35 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.commonjava.atlas.maven.ident.version.part.NumericPart; +import org.junit.Test; + +public class NumericPartTest +{ + + @Test + public void largeNumericVersionsEqual() + throws InvalidVersionSpecificationException + { + assertThat( new NumericPart( "20050331" ), equalTo( new NumericPart( "20050331" ) ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/atlas/maven/ident/version/part/SnapshotPartTest.java b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/part/SnapshotPartTest.java new file mode 100644 index 00000000..34785669 --- /dev/null +++ b/identities/src/test/java/org/commonjava/atlas/maven/ident/version/part/SnapshotPartTest.java @@ -0,0 +1,51 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.ident.version.part; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import org.commonjava.atlas.maven.ident.util.SnapshotUtils; +import org.junit.Test; + +public class SnapshotPartTest +{ + + @Test + public void compareTwoRemoteSnapshotsWithDifferentTimestamps_ParsedFromLiterals() + throws Exception + { + final SnapshotPart first = new SnapshotPart( "20140604.124355-1" ); + final SnapshotPart second = new SnapshotPart( "20140604.124350-1" ); + + final int result = first.compareTo( second ); + + assertThat( result, equalTo( 1 ) ); + } + + @Test + public void compareLocalVsRemoteSnapshot_LocalSortsLastAsMostRecent() + throws Exception + { + final SnapshotPart first = new SnapshotPart( SnapshotUtils.LOCAL_SNAPSHOT_VERSION_PART ); + final SnapshotPart second = new SnapshotPart( "20140604.124350-1" ); + + final int result = first.compareTo( second ); + + assertThat( result, equalTo( 1 ) ); + } + +} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/ProjectRefTest.java b/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/ProjectRefTest.java deleted file mode 100644 index baf87bd3..00000000 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/ProjectRefTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class ProjectRefTest -{ - - @Test - public void matchesTotalWildcardGroupId() - { - final ProjectRef pattern = new ProjectRef( "*", "foo" ); - final ProjectRef test = new ProjectRef( "org.bar", "foo" ); - - assertThat( pattern.matches( test ), equalTo( true ) ); - } - - @Test - public void matchesTotalWildcardArtifactId() - { - final ProjectRef pattern = new ProjectRef( "org.bar", "*" ); - final ProjectRef test = new ProjectRef( "org.bar", "foo" ); - - assertThat( pattern.matches( test ), equalTo( true ) ); - } - - @Test - public void matchesTerminatingWildcardGroupId() - { - final ProjectRef pattern = new ProjectRef( "org.*", "foo" ); - final ProjectRef test = new ProjectRef( "org.bar", "foo" ); - - assertThat( pattern.matches( test ), equalTo( true ) ); - } - - @Test - public void matchesTerminatingWildcardArtifactId() - { - final ProjectRef pattern = new ProjectRef( "org.bar", "fo*" ); - final ProjectRef test = new ProjectRef( "org.bar", "foo" ); - - assertThat( pattern.matches( test ), equalTo( true ) ); - } - - @Test - public void matchesEmbeddedWildcardGroupId() - { - final ProjectRef pattern = new ProjectRef( "org.*r", "foo" ); - final ProjectRef test = new ProjectRef( "org.bar", "foo" ); - - assertThat( pattern.matches( test ), equalTo( true ) ); - } - - @Test - public void matchesEmbeddedWildcardArtifactId() - { - final ProjectRef pattern = new ProjectRef( "org.bar", "f*o" ); - final ProjectRef test = new ProjectRef( "org.bar", "foo" ); - - assertThat( pattern.matches( test ), equalTo( true ) ); - } - -} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/ProjectVersionRefTest.java b/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/ProjectVersionRefTest.java deleted file mode 100644 index 1be566ce..00000000 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/ProjectVersionRefTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.VersionSpec; -import org.junit.Test; - -public class ProjectVersionRefTest -{ - - @Test - public void constructWithStringVersionAndRenderStandardSpecMatches() - throws InvalidVersionSpecificationException - { - final String ver = "2.1.1.Final"; - final ProjectVersionRef ref = new ProjectVersionRef( "g", "a", ver ); - final VersionSpec spec = ref.getVersionSpec(); - - assertThat( spec.renderStandard(), equalTo( ver ) ); - } - - @Test - public void hashCodeEquality() - throws InvalidVersionSpecificationException - { - final ProjectVersionRef ref1 = new ProjectVersionRef( "org.foo", "bar", "1.1.1-baz-1" ); - final ProjectVersionRef ref2 = new ProjectVersionRef( "org.foo", "bar", "1.1.1-baz-1" ); - - assertThat( ref1.hashCode(), equalTo( ref2.hashCode() ) ); - } - - @Test - public void objectEquality() - throws InvalidVersionSpecificationException - { - final ProjectVersionRef ref1 = new ProjectVersionRef( "org.foo", "bar", "1.1.1-baz-1" ); - final ProjectVersionRef ref2 = new ProjectVersionRef( "org.foo", "bar", "1.1.1-baz-1" ); - - assertThat( ref1, equalTo( ref2 ) ); - } - - @Test - public void addTwoIdenticalRefsToASetAndVerifyThatOnlyOneIsAdded() - throws InvalidVersionSpecificationException - { - final ProjectVersionRef ref1 = new ProjectVersionRef( "org.foo", "bar", "1.1.1-baz-1" ); - final ProjectVersionRef ref2 = new ProjectVersionRef( "org.foo", "bar", "1.1.1-baz-1" ); - - assertThat( ref1, equalTo( ref2 ) ); - - final Set set = new HashSet(); - assertThat( set.add( ref1 ), equalTo( true ) ); - assertThat( set.add( ref2 ), equalTo( false ) ); - } - - @Test - public void addTwoIdenticalCompoundRefsToASetAndVerifyThatOnlyOneIsAdded() - throws InvalidVersionSpecificationException - { - final ProjectVersionRef ref1 = new ProjectVersionRef( "org.foo", "bar", "[1.1.1-baz-1,1.1.1-baz-2]" ); - final ProjectVersionRef ref2 = new ProjectVersionRef( "org.foo", "bar", "[1.1.1-baz-1,1.1.1-baz-2]" ); - - assertThat( ref1, equalTo( ref2 ) ); - - final Set set = new HashSet(); - assertThat( set.add( ref1 ), equalTo( true ) ); - assertThat( set.add( ref2 ), equalTo( false ) ); - } - -} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/VersionlessArtifactRefTest.java b/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/VersionlessArtifactRefTest.java deleted file mode 100644 index 6f6a9839..00000000 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/ref/VersionlessArtifactRefTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.ref; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.ref.VersionlessArtifactRef; -import org.junit.Test; - -public class VersionlessArtifactRefTest -{ - @Test - public void identicalVersionlessArtifactsAreNotEqualWhenOptionalFlagsDiffer() - { - // net.sf.kxml:kxml2:*:jar - final String g = "net.sf.kxml"; - final String a = "kxml2"; - final String v = "1"; - final String t = "jar"; - - final VersionlessArtifactRef r1 = new VersionlessArtifactRef( new ArtifactRef( g, a, v, t, null, false ) ); - final VersionlessArtifactRef r2 = new VersionlessArtifactRef( new ArtifactRef( g, a, v, t, null, true ) ); - - assertThat( r1.equals( r2 ), equalTo( false ) ); - assertThat( r1.hashCode() == r2.hashCode(), equalTo( false ) ); - } - - @Test - public void twoIdenticalArtifactsWrappedInVersionlessInstanceAreEqual_DefaultTypeAndClassifier() - { - final ProjectVersionRef pvr = new ProjectVersionRef( "group", "artifact", "1" ); - final ArtifactRef r1 = new ArtifactRef( pvr, null, null, false ); - final ArtifactRef r2 = new ArtifactRef( pvr, null, null, false ); - - final VersionlessArtifactRef vr1 = new VersionlessArtifactRef( r1 ); - final VersionlessArtifactRef vr2 = new VersionlessArtifactRef( r2 ); - - assertThat( vr1, equalTo( vr2 ) ); - assertThat( vr1.hashCode(), equalTo( vr2.hashCode() ) ); - } - - @Test - public void twoArtifactsWrappedInVersionlessInstanceAreNotEqualWhenTypeDiffers() - { - final ProjectVersionRef pvr = new ProjectVersionRef( "group", "artifact", "1" ); - final ArtifactRef r1 = new ArtifactRef( pvr, "jar", null, false ); - final ArtifactRef r2 = new ArtifactRef( pvr, "pom", null, false ); - - final VersionlessArtifactRef vr1 = new VersionlessArtifactRef( r1 ); - final VersionlessArtifactRef vr2 = new VersionlessArtifactRef( r2 ); - - assertThat( vr1.equals( vr2 ), equalTo( false ) ); - assertThat( vr1.hashCode() == vr2.hashCode(), equalTo( false ) ); - } - - @Test - public void twoArtifactsWrappedInVersionlessInstanceAreNotEqualWhenClassifierDiffers() - { - final ProjectVersionRef pvr = new ProjectVersionRef( "group", "artifact", "1" ); - final ArtifactRef r1 = new ArtifactRef( pvr, "jar", null, false ); - final ArtifactRef r2 = new ArtifactRef( pvr, "jar", "foo", false ); - - final VersionlessArtifactRef vr1 = new VersionlessArtifactRef( r1 ); - final VersionlessArtifactRef vr2 = new VersionlessArtifactRef( r2 ); - - assertThat( vr1.equals( vr2 ), equalTo( false ) ); - assertThat( vr1.hashCode() == vr2.hashCode(), equalTo( false ) ); - } - - @Test - public void twoArtifactsWrappedInVersionlessInstanceAreEqualWhenVersionDiffers() - { - final ProjectVersionRef pvr1 = new ProjectVersionRef( "group", "artifact", "1" ); - final ProjectVersionRef pvr2 = new ProjectVersionRef( "group", "artifact", "2" ); - final ArtifactRef r1 = new ArtifactRef( pvr1, null, null, false ); - final ArtifactRef r2 = new ArtifactRef( pvr2, null, null, false ); - - final VersionlessArtifactRef vr1 = new VersionlessArtifactRef( r1 ); - final VersionlessArtifactRef vr2 = new VersionlessArtifactRef( r2 ); - - assertThat( vr1, equalTo( vr2 ) ); - assertThat( vr1.hashCode(), equalTo( vr2.hashCode() ) ); - } - - @Test - public void twoArtifactsWrappedInVersionlessInstanceAreEqualWhenVersionDiffersWithRange() - { - final ProjectVersionRef pvr1 = new ProjectVersionRef( "group", "artifact", "1" ); - final ProjectVersionRef pvr2 = new ProjectVersionRef( "group", "artifact", "[2,3.1]" ); - final ArtifactRef r1 = new ArtifactRef( pvr1, null, null, false ); - final ArtifactRef r2 = new ArtifactRef( pvr2, null, null, false ); - - // trigger parsing. - r1.getVersionSpec(); - r2.getVersionSpec(); - - final VersionlessArtifactRef vr1 = new VersionlessArtifactRef( r1 ); - final VersionlessArtifactRef vr2 = new VersionlessArtifactRef( r2 ); - - assertThat( vr1, equalTo( vr2 ) ); - assertThat( vr1.hashCode(), equalTo( vr2.hashCode() ) ); - } - -} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionRangeTest.java b/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionRangeTest.java deleted file mode 100644 index e6d10b11..00000000 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionRangeTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.RangeVersionSpec; -import org.commonjava.maven.atlas.ident.version.VersionUtils; -import org.junit.Test; - -public class VersionRangeTest -{ - - @Test - public void identialRangeEquality() - throws InvalidVersionSpecificationException - { - final RangeVersionSpec r1 = VersionUtils.createRange( "[1.1.1-baz-1,1.1.1-baz-2]" ); - final RangeVersionSpec r2 = VersionUtils.createRange( "[1.1.1-baz-1,1.1.1-baz-2]" ); - - assertThat( r1.renderStandard(), equalTo( r2.renderStandard() ) ); - assertThat( r1.hashCode(), equalTo( r2.hashCode() ) ); - assertThat( r1, equalTo( r2 ) ); - assertThat( r2, equalTo( r1 ) ); - } - -} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionUtilsTest.java b/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionUtilsTest.java deleted file mode 100644 index fb612fe4..00000000 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/VersionUtilsTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version; - -import org.commonjava.maven.atlas.ident.version.SingleVersion; -import org.commonjava.maven.atlas.ident.version.VersionUtils; -import org.junit.Test; - -public class VersionUtilsTest -{ - - @Test - public void createSingleTimestampVersionFormat() - throws Exception - { - final String spec = "20031129.200437"; - final SingleVersion version = VersionUtils.createSingleVersion( spec ); - - System.out.println( version ); - } - -} diff --git a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/part/NumericPartTest.java b/identities/src/test/java/org/commonjava/maven/atlas/ident/version/part/NumericPartTest.java deleted file mode 100644 index 4ee76339..00000000 --- a/identities/src/test/java/org/commonjava/maven/atlas/ident/version/part/NumericPartTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.ident.version.part; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.part.NumericPart; -import org.junit.Test; - -public class NumericPartTest -{ - - @Test - public void largeNumericVersionsEqual() - throws InvalidVersionSpecificationException - { - assertThat( new NumericPart( "20050331" ), equalTo( new NumericPart( "20050331" ) ) ); - } - -} diff --git a/npm-identities/pom.xml b/npm-identities/pom.xml new file mode 100644 index 00000000..774360e5 --- /dev/null +++ b/npm-identities/pom.xml @@ -0,0 +1,42 @@ + + + + 4.0.0 + + + org.commonjava.atlas + atlas-parent + 1.2.3-SNAPSHOT + + + atlas-npm-identities + + Atlas :: Maven Project-Graph :: NPM Identities Model + + + + org.commonjava.atlas + atlas-identities + + + com.github.zafarkhaja + java-semver + + + diff --git a/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/InvalidNpmRefException.java b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/InvalidNpmRefException.java new file mode 100644 index 00000000..18c67973 --- /dev/null +++ b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/InvalidNpmRefException.java @@ -0,0 +1,66 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.npm.ident.ref; + +import java.util.IllegalFormatException; + +/** + * Thrown to signal an invalid reference to another project. This happens most commonly when a name or version string is + * left blank or null. + */ +public class InvalidNpmRefException + extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + private final Object[] params; + + public InvalidNpmRefException( final String message, final Throwable cause, final Object... params ) + { + super( message, cause ); + this.params = params; + } + + public InvalidNpmRefException( final String message, final Object... params ) + { + super( message ); + this.params = params; + } + + @Override + public String getLocalizedMessage() + { + return getMessage(); + } + + @Override + public String getMessage() + { + String format = super.getMessage(); + if ( params != null && params.length > 0 ) + { + try + { + format = String.format( format, params ); + } + catch ( final IllegalFormatException e ) + { + } + } + + return format; + } +} diff --git a/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/NpmPackageRef.java b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/NpmPackageRef.java new file mode 100644 index 00000000..40d71ca8 --- /dev/null +++ b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/NpmPackageRef.java @@ -0,0 +1,203 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.npm.ident.ref; + +import com.github.zafarkhaja.semver.ParseException; +import com.github.zafarkhaja.semver.Version; +import org.commonjava.atlas.npm.ident.util.NpmVersionUtils; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + +/** + * NpmPackageRef use jsemver Version object. Ref https://github.com/zafarkhaja/jsemver + * + * Created by ruhan on 10/17/18. + */ +public class NpmPackageRef extends NpmProjectRef + implements Externalizable +{ + private Version version; + + private String versionString; + + public NpmPackageRef() + { + } + + public NpmPackageRef( final String name, final Version version ) + { + this( name, version, null ); + } + + public NpmPackageRef( final String name, final String versionString ) + { + this( name, null, versionString ); + } + + NpmPackageRef( final String name, final Version version, final String versionString ) + { + super( name ); + this.version = version; + this.versionString = versionString; + } + + /** + * Parses new instance from a string. The expected format is "[name]:[version]". + * + * @param nv the string to be parsed + * @return parsed package ref + * @throws InvalidNpmRefException when the given string doesn't match the expected format + */ + public static NpmPackageRef parse( final String nv ) + { + final String[] parts = nv.split( ":" ); + if ( ( parts.length < 2 ) || isEmpty( parts[0] ) || isEmpty( parts[1] ) ) + { + throw new InvalidNpmRefException( "NpmPackageRef must contain non-empty name AND version. (Given: '" + nv + + "')" ); + } + + return new NpmPackageRef( parts[0], parts[1] ); + } + + public Version getVersionRaw() + { + return version; + } + + public Version getVersion() + { + if ( ( version == null ) && ( versionString != null ) ) + { + version = NpmVersionUtils.valueOf( versionString ); + } + return version; + } + + public String getVersionString() + { + if ( ( versionString == null ) && ( version != null ) ) + { + versionString = version.toString(); + } + return versionString; + } + + public String getVersionStringRaw() + { + return versionString; + } + + public NpmPackageRef selectVersion( final String versionString ) + { + Version version = NpmVersionUtils.valueOf( versionString ); + return selectVersion( version ); + } + + public NpmPackageRef selectVersion( final Version newVersion ) + { + final Version version = getVersion(); + if ( version.equals( newVersion ) ) + { + return this; + } + return new NpmPackageRef( name, newVersion ); + } + + + @Override + public String toString() + { + return getName() + ":" + version; + } + + @Override + public boolean equals( final Object o ) + { + if ( this == o ) + { + return true; + } + if ( ( o == null ) || ( getClass() != o.getClass() ) ) + { + return false; + } + if ( !super.equals( o ) ) + { + return false; + } + + boolean result = true; + NpmPackageRef other = (NpmPackageRef) o; + try + { + if ( getVersion() == null ) + { + if ( other.getVersion() != null ) + { + result = false; + } + } + else if ( !getVersion().equals( other.getVersion() ) ) + { + result = false; + } + } + catch ( final ParseException e ) + { + if ( getVersionString() == null ) + { + if ( other.getVersionString() != null ) + { + result = false; + } + } + else if ( !getVersionString().equals( other.getVersionString() ) ) + { + result = false; + } + } + + return result; + } + + @Override + public int hashCode() + { + int result = super.hashCode(); + result = ( 31 * result ) + ( ( getVersionString() == null ) ? 0 : getVersionString().hashCode() ); + return result; + } + + @Override + public void writeExternal( final ObjectOutput objectOutput ) throws IOException + { + objectOutput.writeObject( getName() ); + objectOutput.writeObject( version.toString() ); + } + + @Override + public void readExternal( final ObjectInput objectInput ) throws IOException, ClassNotFoundException + { + this.name = (String) objectInput.readObject(); + this.version = NpmVersionUtils.valueOf( (String) objectInput.readObject() ); + } +} diff --git a/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/NpmProjectRef.java b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/NpmProjectRef.java new file mode 100644 index 00000000..6a7b2893 --- /dev/null +++ b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/ref/NpmProjectRef.java @@ -0,0 +1,77 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.npm.ident.ref; + +import java.io.Serializable; + +/** + * Created by ruhan on 11/3/18. + */ +public class NpmProjectRef implements Serializable +{ + private static final long serialVersionUID = -1799733486053972932L; + + protected String name; + + public NpmProjectRef() + { + } + + public NpmProjectRef( final String name ) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public NpmProjectRef asNpmProjectRef() + { + return NpmProjectRef.class.equals( getClass() ) ? this : new NpmProjectRef( getName() ); + } + + @Override + public boolean equals( final Object o ) + { + if ( this == o ) + { + return true; + } + if ( o == null || getClass() != o.getClass() ) + { + return false; + } + + NpmProjectRef that = (NpmProjectRef) o; + + return name.equals( that.name ); + + } + + @Override + public int hashCode() + { + return name.hashCode(); + } + + @Override + public String toString() + { + return name; + } +} diff --git a/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/util/NpmPackagePathInfo.java b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/util/NpmPackagePathInfo.java new file mode 100644 index 00000000..9e0c816e --- /dev/null +++ b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/util/NpmPackagePathInfo.java @@ -0,0 +1,112 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.npm.ident.util; + +import com.github.zafarkhaja.semver.Version; +import org.commonjava.atlas.maven.ident.util.PathInfo; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.commonjava.atlas.npm.ident.util.NpmVersionUtils.valueOf; + +/** + * Created by ruhan on 11/2/18. + */ +public class NpmPackagePathInfo implements PathInfo +{ + private static final String EXT_TGZ = ".tgz"; + + private static final String PACKAGE_PATH_REGEX = "/((?:(.+)/)?(.+))/-/(.+)\\" + EXT_TGZ; + + private static final int SCOPED_PACKAGE_NAME_GROUP = 1; + + private static final int PACKAGE_SCOPE_GROUP = 2; + + private static final int PACKAGE_NAME_GROUP = 3; + + private static final int PACKAGE_NAME_AND_VERSION_GROUP = 4; + + + /** + * Parses an npm package path into fields. The path might be scoped or not. A package metadata path, e.g. + * "/keycloak-connect", cannot be parsed by this method. + * + * @param path + * parsed path starting with '/', e.g. /keycloak-connect/-/keycloak-connect-3.4.1.tgz or + * /@hawtio/core-dts/-/core-dts-3.3.2.tgz + * @return parsed path into an NpmPackagePathInfo instance + */ + public static NpmPackagePathInfo parse( final String path ) + { + final Matcher matcher = Pattern.compile( PACKAGE_PATH_REGEX ).matcher( path.replace( '\\', '/' ) ); + if ( !matcher.matches() ) + { + return null; + } + + final String scopedName = matcher.group( SCOPED_PACKAGE_NAME_GROUP ); + final String name = matcher.group( PACKAGE_NAME_GROUP ); + final String nameAndVersion = matcher.group( PACKAGE_NAME_AND_VERSION_GROUP ); + + final String version = nameAndVersion.substring( name.length() + 1 ); + + return new NpmPackagePathInfo( scopedName, valueOf( version ), nameAndVersion + EXT_TGZ, path ); + } + + + private String name; + + private Version version; + + private String file; + + private String fullPath; + + + public NpmPackagePathInfo( String name, Version version, String file, String fullPath ) + { + this.name = name; + this.version = version; + this.file = file; + this.fullPath = fullPath; + } + + @Override + public String getFile() + { + return file; + } + + @Override + public String getFullPath() + { + return fullPath; + } + + /** + * @return package name, can be scoped, e.g. @hawtio/core-dts + */ + public String getName() + { + return name; + } + + public Version getVersion() + { + return version; + } +} diff --git a/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/util/NpmVersionUtils.java b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/util/NpmVersionUtils.java new file mode 100644 index 00000000..27caa16b --- /dev/null +++ b/npm-identities/src/main/java/org/commonjava/atlas/npm/ident/util/NpmVersionUtils.java @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.npm.ident.util; + +import com.github.zafarkhaja.semver.Version; + +/** + * Created by ruhan on 10/17/18. + */ +public class NpmVersionUtils +{ + public static Version valueOf( String ver ) + { + return Version.valueOf( ver ); + } +} diff --git a/npm-identities/src/test/java/org/commonjava/atlas/npm/ident/ref/NpmPackageRefTest.java b/npm-identities/src/test/java/org/commonjava/atlas/npm/ident/ref/NpmPackageRefTest.java new file mode 100644 index 00000000..570579b7 --- /dev/null +++ b/npm-identities/src/test/java/org/commonjava/atlas/npm/ident/ref/NpmPackageRefTest.java @@ -0,0 +1,105 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.npm.ident.ref; + +import com.github.zafarkhaja.semver.Version; +import org.commonjava.atlas.npm.ident.util.NpmPackagePathInfo; +import org.commonjava.atlas.npm.ident.util.NpmVersionUtils; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Created by ruhan on 10/17/18. + */ +public class NpmPackageRefTest +{ + @Test + public void pathParseTest() + { + String path = "/keycloak-connect/-/keycloak-connect-3.4.1.tgz"; + + NpmPackagePathInfo info = NpmPackagePathInfo.parse( path ); + assertTrue( info.getName().equals( "keycloak-connect" ) ); + assertTrue( info.getVersion().toString().equals( "3.4.1" ) ); + assertTrue( info.getFile().equals( "keycloak-connect-3.4.1.tgz" ) ); + assertTrue( info.getFullPath().equals( path ) ); + } + + @Test + public void scopedPathParseTest() + { + String path = "/@hawtio/core-dts/-/core-dts-3.3.2.tgz"; + + NpmPackagePathInfo info = NpmPackagePathInfo.parse( path ); + assertTrue( info.getName().equals( "@hawtio/core-dts" ) ); + assertTrue( info.getVersion().toString().equals( "3.3.2" ) ); + assertTrue( info.getFile().equals( "core-dts-3.3.2.tgz" ) ); + assertTrue( info.getFullPath().equals( path ) ); + } + + @Test + public void versionTest() + { + Version v = NpmVersionUtils.valueOf( "1.0.0-rc.1+build.1" ); + + int major = v.getMajorVersion(); // 1 + int minor = v.getMinorVersion(); // 0 + int patch = v.getPatchVersion(); // 0 + + assertTrue( major == 1 ); + assertTrue( minor == 0 ); + assertTrue( patch == 0 ); + + String normal = v.getNormalVersion(); // "1.0.0" + String preRelease = v.getPreReleaseVersion(); // "rc.1" + String build = v.getBuildMetadata(); // "build.1" + + assertTrue( normal.equals( "1.0.0" ) ); + assertTrue( preRelease.equals( "rc.1" ) ); + assertTrue( build.equals( "build.1" ) ); + + String str = v.toString(); // "1.0.0-rc.1+build.1" + assertTrue( str.equals( "1.0.0-rc.1+build.1" ) ); + } + + @Test + public void serializeTest() throws IOException, ClassNotFoundException + { + Version v = NpmVersionUtils.valueOf( "1.0.0-rc.1+build.1" ); + NpmPackageRef ref = new NpmPackageRef( "test", v ); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream( bos ); + oos.writeObject( ref ); + oos.close(); + + byte[] bytes = bos.toByteArray(); + + ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( bytes ) ); + NpmPackageRef ref2 = (NpmPackageRef) ois.readObject(); + ois.close(); + + assertEquals( ref, ref2 ); + } +} diff --git a/pom.xml b/pom.xml index ddb3ad73..635c5881 100644 --- a/pom.xml +++ b/pom.xml @@ -1,13 +1,20 @@ 4.0.0 @@ -15,66 +22,73 @@ org.commonjava commonjava - 3 + 21 - org.commonjava.maven.atlas + org.commonjava.atlas atlas-parent - 0.12.0-EXP-SNAPSHOT + 1.2.3-SNAPSHOT pom + 2012-2022 + + Atlas :: Parent - Atlas :: Maven Project-Graph :: Parent - - scm:git:http://jdcasey@github.com/jdcasey/atlas.git - scm:git:git@github.com:jdcasey/atlas.git - http://github.com/jdcasey/atlas + scm:git:https://github.com/commonjava/atlas + scm:git:https://github.com/commonjava/atlas + https://github.com/Commonjava/atlas + HEAD - + + + 1.8 + Red Hat, Inc. + nos-devel@redhat.com + true + false + + - org.commonjava.maven.atlas + org.commonjava.atlas atlas-identities - 0.12.0-EXP-SNAPSHOT + ${project.version} - org.commonjava.maven.atlas + org.commonjava.atlas atlas-relationships-api - 0.12.0-EXP-SNAPSHOT + ${project.version} - org.commonjava.maven.atlas - atlas-drivers-tck - 0.12.0-EXP-SNAPSHOT - test + org.commonjava.atlas + atlas-bindings-jackson-identities + ${project.version} - - org.commonjava.boms - web-commons-bom - 9 - import - pom + org.commonjava.atlas + atlas-npm-identities + ${project.version} - - org.neo4j - neo4j - 1.9.6 + com.github.zafarkhaja + java-semver + 0.10.2 - net.sf.jung - jung-graph-impl - 2.0.1 + org.commonjava.boms + web-commons-bom + 34 + import + pom - commons-lang - commons-lang + org.slf4j + slf4j-api junit @@ -85,21 +99,21 @@ logback-classic - + maven-compiler-plugin - 1.6 - 1.6 + ${javaVersion} + ${javaVersion} org.codehaus.mojo javacc-maven-plugin - 2.6 + 3.2.0 javacc @@ -109,14 +123,26 @@ + + maven-javadoc-plugin + ${version.plugin.javadoc} + + false + -Xdoclint:none + -Xdoclint:none + none + 8 + + + - + identities + npm-identities relationships-api - tck - drivers + bindings diff --git a/relationships-api/pom.xml b/relationships-api/pom.xml index dadd7eb3..4702219f 100644 --- a/relationships-api/pom.xml +++ b/relationships-api/pom.xml @@ -1,21 +1,28 @@ 4.0.0 - org.commonjava.maven.atlas + org.commonjava.atlas atlas-parent - 0.12.0-EXP-SNAPSHOT + 1.2.3-SNAPSHOT atlas-relationships-api @@ -24,9 +31,25 @@ - org.commonjava.maven.atlas + org.commonjava.atlas atlas-identities + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-core + + + org.commonjava.atlas + atlas-bindings-jackson-identities + commons-codec commons-codec diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/PluginKeyDeserializer.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/PluginKeyDeserializer.java new file mode 100644 index 00000000..1fd75dec --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/PluginKeyDeserializer.java @@ -0,0 +1,40 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.jackson; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.KeyDeserializer; +import org.commonjava.atlas.maven.graph.model.PluginKey; + +import java.io.IOException; + +/** + * Created by ruhan on 3/16/17. + */ +@SuppressWarnings( { "rawtypes", "unchecked" } ) +public final class PluginKeyDeserializer + extends KeyDeserializer +{ + public PluginKeyDeserializer() {} + + @Override + public Object deserializeKey(String json, DeserializationContext ctx) + throws IOException, JsonProcessingException + { + return PluginKey.parse( json ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/PluginKeySerializer.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/PluginKeySerializer.java new file mode 100644 index 00000000..9ad0e5d5 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/PluginKeySerializer.java @@ -0,0 +1,39 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.jackson; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import org.commonjava.atlas.maven.graph.model.PluginKey; + +import java.io.IOException; + +/** + * Created by ruhan on 3/17/17. + */ +public class PluginKeySerializer + extends JsonSerializer +{ + + @Override + public void serialize(PluginKey pluginKey, JsonGenerator gen, SerializerProvider provider) + throws IOException, JsonProcessingException + { + gen.writeFieldName( pluginKey.toString() ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipDeserializer.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipDeserializer.java new file mode 100644 index 00000000..10df9e95 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipDeserializer.java @@ -0,0 +1,270 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.jackson; + +import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; +import org.commonjava.atlas.maven.graph.rel.RelationshipConstants; +import org.commonjava.atlas.maven.graph.rel.RelationshipType; +import org.commonjava.atlas.maven.graph.rel.SimpleBomRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleExtensionRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleParentRelationship; +import org.commonjava.atlas.maven.graph.rel.SimplePluginDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.SimplePluginRelationship; +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.DependencyScope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +/** + * Created by jdcasey on 8/26/15. + */ +@SuppressWarnings( { "rawtypes", "unchecked" } ) +public final class ProjectRelationshipDeserializer + extends StdDeserializer +{ + private static final long serialVersionUID = 1L; + + public ProjectRelationshipDeserializer() + { + super( ProjectRelationship.class ); + } + + @Override + public T deserialize( final JsonParser jp, final DeserializationContext ctx ) + throws JsonProcessingException, IOException + { + Map ast = new HashMap(); + Map locations = new HashMap(); + + JsonToken token = jp.getCurrentToken(); + String currentField = null; + List currentArry = null; + + Logger logger = LoggerFactory.getLogger( getClass() ); + do + { + // logger.info( "Token: {}", token ); + switch ( token ) + { + case START_ARRAY: + { + // logger.info( "Starting array for field: {}", currentField ); + currentArry = new ArrayList(); + break; + } + case END_ARRAY: + // logger.info( "Ending array for field: {}", currentField ); + locations.put( currentField, jp.getCurrentLocation() ); + ast.put( currentField, currentArry ); + currentArry = null; + break; + case FIELD_NAME: + currentField = jp.getCurrentName(); + break; + case VALUE_STRING: + if ( currentArry != null ) + { + currentArry.add( jp.getText() ); + } + else + { + locations.put( currentField, jp.getCurrentLocation() ); + ast.put( currentField, jp.getText() ); + } + break; + case VALUE_NUMBER_INT: + locations.put( currentField, jp.getCurrentLocation() ); + ast.put( currentField, jp.getIntValue() ); + break; + case VALUE_NUMBER_FLOAT: + locations.put( currentField, jp.getCurrentLocation() ); + ast.put( currentField, jp.getFloatValue() ); + break; + case VALUE_TRUE: + locations.put( currentField, jp.getCurrentLocation() ); + ast.put( currentField, Boolean.TRUE ); + break; + case VALUE_FALSE: + locations.put( currentField, jp.getCurrentLocation() ); + ast.put( currentField, Boolean.FALSE ); + break; + } + + token = jp.nextToken(); + } + while ( token != JsonToken.END_OBJECT ); + + StringBuilder sb = new StringBuilder(); + sb.append( "AST is:" ); + for ( String field : ast.keySet() ) + { + Object value = ast.get( field ); + sb.append( "\n " ).append( field ).append( " = " ); + if ( value == null ) + { + sb.append( "null" ); + } + else + { + sb.append( value ).append( " (type: " ).append( value.getClass().getSimpleName() ).append( ")" ); + } + } + + logger.debug( sb.toString() ); + + final RelationshipType type = RelationshipType.getType( (String) ast.get( SerializationConstants.RELATIONSHIP_TYPE ) ); + + final String uri = (String) ast.get( SerializationConstants.POM_LOCATION_URI ); + URI pomLocation; + if ( uri == null ) + { + pomLocation = RelationshipConstants.POM_ROOT_URI; + } + else + { + try + { + pomLocation = new URI( uri ); + } + catch ( final URISyntaxException e ) + { + throw new JsonParseException( "Invalid " + SerializationConstants.POM_LOCATION_URI + ": '" + uri + "': " + e.getMessage(), + locations.get( SerializationConstants.POM_LOCATION_URI ), e ); + } + } + + Collection sources = new HashSet(); + List srcs = (List) ast.get( SerializationConstants.SOURCE_URIS ); + if ( srcs != null ) + { + for ( String u : srcs ) + { + try + { + sources.add( new URI( u ) ); + } + catch ( URISyntaxException e ) + { + throw new JsonParseException( "Failed to parse source URI: " + u, + locations.get( SerializationConstants.SOURCE_URIS ) ); + } + } + } + + String decl = (String) ast.get( SerializationConstants.DECLARING_REF ); + final ProjectVersionRef declaring = SimpleProjectVersionRef.parse( decl ); + + String tgt = (String) ast.get( SerializationConstants.TARGET_REF ); + Integer index = (Integer) ast.get( SerializationConstants.INDEX ); + if ( index == null ) + { + index = 0; + } + + // handle null implicitly by comparing to true. + boolean managed = Boolean.TRUE.equals( ast.get( SerializationConstants.MANAGED ) ); + boolean inherited = Boolean.TRUE.equals( ast.get( SerializationConstants.INHERITED ) ); + boolean mixin = Boolean.TRUE.equals( ast.get( SerializationConstants.MIXIN ) ); + boolean optional = Boolean.TRUE.equals( ast.get( SerializationConstants.OPTIONAL ) ); + + ProjectRelationship rel = null; + switch ( type ) + { + case DEPENDENCY: + { + final ArtifactRef target = SimpleArtifactRef.parse( tgt ); + + String scp = (String) ast.get( SerializationConstants.SCOPE ); + final DependencyScope scope; + if ( scp == null ) + { + scope = DependencyScope.compile; + } + else + { + scope = DependencyScope.getScope( scp ); + } + + rel = new SimpleDependencyRelationship( sources, pomLocation, declaring, target, scope, index, + managed, inherited, optional ); + break; + } + case EXTENSION: + { + final ProjectVersionRef target = SimpleProjectVersionRef.parse( tgt ); + + rel = new SimpleExtensionRelationship( sources, pomLocation, declaring, target, index, inherited ); + break; + } + case PARENT: + { + final ProjectVersionRef target = SimpleProjectVersionRef.parse( tgt ); + + rel = new SimpleParentRelationship( sources, declaring, target ); + break; + } + case PLUGIN: + { + final ProjectVersionRef target = SimpleProjectVersionRef.parse( tgt ); + + Boolean report = (Boolean) ast.get( SerializationConstants.REPORTING ); + rel = new SimplePluginRelationship( sources, pomLocation, declaring, target, index, managed, + Boolean.TRUE.equals( report ), inherited ); + break; + } + case PLUGIN_DEP: + { + String plug = (String) ast.get( SerializationConstants.PLUGIN_REF ); + if ( plug == null ) + { + throw new JsonParseException( "No plugin reference (field: " + SerializationConstants.PLUGIN_REF + + ") found in plugin-dependency relationship!", + jp.getCurrentLocation() ); + } + + final ProjectRef plugin = SimpleProjectRef.parse( plug ); + final ArtifactRef target = SimpleArtifactRef.parse( tgt ); + + rel = new SimplePluginDependencyRelationship( sources, pomLocation, declaring, plugin, target, + index, managed, inherited ); + break; + } + case BOM: + { + final ProjectVersionRef target = SimpleProjectVersionRef.parse( tgt ); + + rel = new SimpleBomRelationship( sources, pomLocation, declaring, target, index, inherited, mixin ); + break; + } + } + + return (T) rel; + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipSerializer.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipSerializer.java new file mode 100644 index 00000000..6245358b --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipSerializer.java @@ -0,0 +1,113 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.jackson; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.commonjava.atlas.maven.graph.rel.DependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.PluginDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.PluginRelationship; +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; + +import java.io.IOException; +import java.net.URI; +import java.util.Iterator; +import java.util.Set; + +/** + * Created by jdcasey on 8/26/15. + */ +@SuppressWarnings( "rawtypes" ) +public final class ProjectRelationshipSerializer + extends StdSerializer +{ + public ProjectRelationshipSerializer( final Class cls ) + { + super( cls ); + } + + @SuppressWarnings( "incomplete-switch" ) + @Override + public void serialize( final T value, final JsonGenerator gen, final SerializerProvider provider ) + throws IOException, JsonGenerationException + { + gen.writeStartObject(); + gen.writeStringField( SerializationConstants.RELATIONSHIP_TYPE, value.getType().name() ); + gen.writeStringField( SerializationConstants.POM_LOCATION_URI, value.getPomLocation().toString() ); + gen.writeBooleanField( SerializationConstants.INHERITED, value.isInherited() ); + + Set sources = value.getSources(); + if ( sources != null ) + { + for ( Iterator iter = sources.iterator(); iter.hasNext(); ) + { + if ( iter.next() == null ) + { + iter.remove(); + } + } + if ( !sources.isEmpty() ) + { + gen.writeArrayFieldStart( SerializationConstants.SOURCE_URIS ); + for ( URI uri : sources ) + { + if ( uri == null ) + { + continue; + } + gen.writeString( uri.toString() ); + } + gen.writeEndArray(); + } + } + provider.defaultSerializeField( SerializationConstants.DECLARING_REF, value.getDeclaring(), gen ); + provider.defaultSerializeField( SerializationConstants.TARGET_REF, value.getTarget(), gen ); + + switch ( value.getType() ) + { + case BOM: + gen.writeBooleanField( SerializationConstants.MIXIN, value.isMixin() ); + break; + case DEPENDENCY: + { + gen.writeStringField( SerializationConstants.SCOPE, ( (DependencyRelationship) value ).getScope().realName() ); + gen.writeBooleanField( SerializationConstants.MANAGED, value.isManaged() ); + gen.writeBooleanField( SerializationConstants.OPTIONAL, ( (DependencyRelationship) value ).isOptional() ); + break; + } + case PLUGIN_DEP: + { + provider.defaultSerializeField( SerializationConstants.PLUGIN_REF, ( (PluginDependencyRelationship) value ).getPlugin(), + gen ); + gen.writeBooleanField( SerializationConstants.MANAGED, value.isManaged() ); + break; + } + case PLUGIN: + { + + gen.writeBooleanField( SerializationConstants.MANAGED, value.isManaged() ); + gen.writeBooleanField( SerializationConstants.REPORTING, ( (PluginRelationship) value ).isReporting() ); + break; + } + } + + gen.writeNumberField( SerializationConstants.INDEX, value.getIndex() ); + gen.writeEndObject(); + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipSerializerModule.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipSerializerModule.java new file mode 100644 index 00000000..c519cdd2 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/ProjectRelationshipSerializerModule.java @@ -0,0 +1,92 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.jackson; + +import com.fasterxml.jackson.databind.module.SimpleModule; +import org.commonjava.atlas.maven.graph.rel.BomRelationship; +import org.commonjava.atlas.maven.graph.rel.DependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.ExtensionRelationship; +import org.commonjava.atlas.maven.graph.rel.ParentRelationship; +import org.commonjava.atlas.maven.graph.rel.PluginDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.PluginRelationship; +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleBomRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleExtensionRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleParentRelationship; +import org.commonjava.atlas.maven.graph.rel.SimplePluginDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.SimplePluginRelationship; +import org.commonjava.atlas.maven.graph.model.PluginKey; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +public class ProjectRelationshipSerializerModule + extends SimpleModule +{ + + private static final long serialVersionUID = 1L; + + private static final Set> REL_CLASSES; + + static + { + REL_CLASSES = Collections.unmodifiableSet( new HashSet>( + Arrays.asList( ProjectRelationship.class, BomRelationship.class, DependencyRelationship.class, + ExtensionRelationship.class, ParentRelationship.class, + PluginDependencyRelationship.class, PluginRelationship.class, + SimpleBomRelationship.class, SimpleDependencyRelationship.class, + SimpleExtensionRelationship.class, SimpleParentRelationship.class, + SimplePluginDependencyRelationship.class, SimplePluginRelationship.class ) ) ); + } + + public static final ProjectRelationshipSerializerModule INSTANCE = new ProjectRelationshipSerializerModule(); + + public ProjectRelationshipSerializerModule() + { + super( "ProjectRelationship Serializer" ); + + for ( Class cls : REL_CLASSES ) + { + register( cls ); + } + addKeySerializer( PluginKey.class, new PluginKeySerializer() ); + addKeyDeserializer( PluginKey.class, new PluginKeyDeserializer() ); + } + + private void register( Class cls ) + { + Logger logger = LoggerFactory.getLogger( getClass() ); + logger.debug( "Registering serializer/deserializer for: {}", cls.getSimpleName() ); + + addSerializer( cls, new ProjectRelationshipSerializer( cls ) ); + addDeserializer( cls, new ProjectRelationshipDeserializer() ); + } + + @Override + public int hashCode() + { + return getClass().getSimpleName().hashCode() + 17; + } + + @Override + public boolean equals( final Object other ) + { + return getClass().equals( other.getClass() ); + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/SerializationConstants.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/SerializationConstants.java new file mode 100644 index 00000000..03ec0fad --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/jackson/SerializationConstants.java @@ -0,0 +1,73 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.jackson; + +public final class SerializationConstants +{ + + private SerializationConstants() + { + } + + public static final String SOURCE_URIS = "source-uris"; + + public static final String SOURCE_URI = "source-uri"; + + public static final String POM_LOCATION_URI = "pom-location-uri"; + + public static final String PROJECT_VERSION = "gav"; + + public static final String GAV = PROJECT_VERSION; + + public static final String RELATIONSHIP_TYPE = "type"; + + public static final String DECLARING_REF = "declaring"; + + public static final String TARGET_REF = "target"; + + public static final String INDEX = "idx"; + + public static final String INHERITED = "inherited"; + + public static final String MANAGED = "managed"; + + public static final String MIXIN = "mixin"; + + public static final String OPTIONAL = "optional"; + + public static final String REPORTING = "reporting"; + + public static final String SCOPE = "scope"; + + public static final String PLUGIN_REF = "plugin"; + + public static final String JSON_VERSION = "jsonVersion"; + + public static final int CURRENT_JSON_VERSION = 1; + + public static final String EPROJECT_KEY = "ekey"; + + public static final String RELATIONSHIPS = "relationships"; + + public static final String EPROFILES = "eprofiles"; + + public static final String CYCLES = "cycles"; + + public static final String WEB_ROOTS = "gavs"; + + public static final String GAVS = WEB_ROOTS; + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectCycle.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectCycle.java new file mode 100644 index 00000000..b1e9b682 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectCycle.java @@ -0,0 +1,269 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.model; + +import static org.apache.commons.lang3.StringUtils.join; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; +import org.commonjava.atlas.maven.graph.rel.RelationshipComparator; +import org.commonjava.atlas.maven.graph.util.RelationshipUtils; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +public class EProjectCycle + implements Iterable>, EProjectRelationshipCollection +{ + + private static final long serialVersionUID = 1L; + + private List> relationships = new ArrayList>(); + + public static final class Builder + { + private final List> participants; + + public Builder( final ProjectRelationship... rels ) + { + participants = new ArrayList>( Arrays.asList( rels ) ); + } + + public Builder( final List> rels ) + { + participants = new ArrayList>( rels ); + } + + public Builder( final Builder builder ) + { + participants = new ArrayList>( builder.participants ); + } + + public Builder( final Builder builder, final int start ) + { + participants = new ArrayList>( builder.participants ); + for ( int i = 0; i < start; i++ ) + { + participants.remove( 0 ); + } + } + + public Builder with( final ProjectRelationship rel ) + { + participants.add( rel ); + return this; + } + + public Builder withoutLast() + { + participants.remove( participants.size() - 1 ); + return this; + } + + public EProjectCycle build() + { + return new EProjectCycle( participants ); + } + + public int indexOf( final ProjectVersionRef ref ) + { + return build().indexOf( ref ); + } + + public int indexOf( final ProjectRelationship rel ) + { + return build().indexOf( rel ); + } + + public boolean contains( final ProjectVersionRef ref ) + { + return build().contains( ref ); + } + + public boolean contains( final ProjectRelationship rel ) + { + return build().contains( rel ); + } + } + + public EProjectCycle(){} + + public EProjectCycle( final List> cycle ) + { + this.relationships = new ArrayList>( cycle ); + } + + public boolean contains( final ProjectRelationship rel ) + { + return relationships.contains( rel ); + } + + public boolean contains( final ProjectVersionRef ref ) + { + for ( final ProjectRelationship rel : relationships ) + { + if ( rel.getDeclaring() + .equals( ref ) ) + { + return true; + } + } + + return false; + } + + public int indexOf( final ProjectRelationship rel ) + { + return relationships.indexOf( rel ); + } + + public int indexOf( final ProjectVersionRef ref ) + { + int targetIdx = -1; + for ( int i = 0; i < relationships.size(); i++ ) + { + final ProjectRelationship rel = relationships.get( i ); + if ( rel.getDeclaring() + .equals( ref ) ) + { + return i; + } + + // if we find the ref we're after as a TARGET, log it. + // if, at the end, we haven't found it as a DECLARING ref, return + // the index of the relationship that lists it as a target. + if ( targetIdx < 0 && rel.getTarget() + .asProjectVersionRef() + .equals( ref ) ) + { + targetIdx = i; + } + } + + return targetIdx; + } + + @Override + public Iterator> iterator() + { + return relationships.iterator(); + } + + @Override + public Collection> getAllRelationships() + { + final Collection> rels = getExactAllRelationships(); + RelationshipUtils.filterTerminalParents( rels ); + + return rels; + } + + @Override + public Collection> getExactAllRelationships() + { + return new ArrayList>( relationships ); + } + + public Set getAllParticipatingProjects() + { + final Set refs = new HashSet(); + for ( final ProjectRelationship rel : relationships ) + { + refs.add( rel.getDeclaring() ); + refs.add( rel.getTarget() + .asProjectVersionRef() ); + } + + return refs; + } + + public List> getRelationships() + { + return relationships; + } + + public void setRelationships( final List> relationships ) + { + this.relationships = relationships; + } + + @Override + public String toString() + { + return String.format( "Project cycle: [%s]", join( relationships, " -> " ) ); + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + + final List> sorted = new ArrayList>( relationships ); + Collections.sort( sorted, RelationshipComparator.INSTANCE ); + + result = prime * result + sorted.hashCode(); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( obj == null ) + { + return false; + } + if ( getClass() != obj.getClass() ) + { + return false; + } + final EProjectCycle other = (EProjectCycle) obj; + if ( relationships == null ) + { + if ( other.relationships != null ) + { + return false; + } + } + else + { + + final Set> cycle = new HashSet>( this.relationships ); + final Set> otherCycle = new HashSet>( other.relationships ); + + for ( final ProjectRelationship rel : cycle ) + { + if ( !otherCycle.contains( rel ) ) + { + return false; + } + } + } + + return true; + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectDirectRelationships.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectDirectRelationships.java similarity index 71% rename from relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectDirectRelationships.java rename to relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectDirectRelationships.java index fa0abaa9..305406cb 100644 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectDirectRelationships.java +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectDirectRelationships.java @@ -1,16 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.model; - -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.filterTerminalParents; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.model; + +import static org.commonjava.atlas.maven.graph.rel.RelationshipConstants.POM_ROOT_URI; +import static org.commonjava.atlas.maven.graph.util.RelationshipUtils.filterTerminalParents; import java.io.Serializable; import java.net.URI; @@ -24,18 +30,22 @@ import java.util.Map; import java.util.Set; -import org.commonjava.maven.atlas.graph.rel.BomRelationship; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ExtensionRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginDependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.commonjava.atlas.maven.graph.rel.BomRelationship; +import org.commonjava.atlas.maven.graph.rel.DependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.ExtensionRelationship; +import org.commonjava.atlas.maven.graph.rel.ParentRelationship; +import org.commonjava.atlas.maven.graph.rel.PluginDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.PluginRelationship; +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleExtensionRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleParentRelationship; +import org.commonjava.atlas.maven.graph.rel.SimplePluginRelationship; +import org.commonjava.atlas.maven.ident.DependencyScope; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; public class EProjectDirectRelationships implements EProjectRelationshipCollection, Serializable @@ -43,25 +53,27 @@ public class EProjectDirectRelationships private static final long serialVersionUID = 1L; - private final URI source; + private URI source; - private final ProjectVersionRef ref; + private ProjectVersionRef projectRef; - private final List boms; + private List boms; - private final List dependencies; + private List dependencies; - private final List managedDependencies; + private List managedDependencies; - private final List plugins; + private List plugins; - private final List managedPlugins; + private List managedPlugins; - private final List extensions; + private List extensions; - private final ParentRelationship parent; + private ParentRelationship parent; - private final Map> pluginDependencies; + private Map> pluginDependencies; + + public EProjectDirectRelationships() {} public EProjectDirectRelationships( final URI source, final ProjectVersionRef ref, @@ -70,10 +82,10 @@ public EProjectDirectRelationships( final URI source, final List dependencies, final List plugins, final List managedDependencies, final List managedPlugins, final List extensions, - final Map> pluginDependencies ) + final Map> pluginDependencies ) { this.source = source; - this.ref = ref; + this.projectRef = ref; this.parent = parent; this.boms = Collections.unmodifiableList( boms ); this.dependencies = Collections.unmodifiableList( dependencies ); @@ -82,10 +94,10 @@ public EProjectDirectRelationships( final URI source, this.managedPlugins = Collections.unmodifiableList( managedPlugins ); this.extensions = Collections.unmodifiableList( extensions ); - final HashMap> pdrels = - new HashMap>(); + final HashMap> pdrels = + new HashMap>(); - for ( final Map.Entry> entry : pluginDependencies.entrySet() ) + for ( final Map.Entry> entry : pluginDependencies.entrySet() ) { pdrels.put( entry.getKey(), Collections.unmodifiableList( entry.getValue() ) ); } @@ -93,9 +105,14 @@ public EProjectDirectRelationships( final URI source, this.pluginDependencies = Collections.unmodifiableMap( pdrels ); } + public final URI getSource() + { + return source; + } + public final ProjectVersionRef getProjectRef() { - return ref; + return projectRef; } public final List getDependencies() @@ -128,15 +145,16 @@ public final ParentRelationship getParent() return parent; } - public final Map> getPluginDependencies() + public final Map> getPluginDependencies() { return pluginDependencies; } - public final List getPluginDependencies( final ProjectVersionRef plugin, final boolean managed ) + public final List getPluginDependencies( final ProjectVersionRef plugin, final boolean managed, + final boolean inherited ) { - final PluginRelationship pr = new PluginRelationship( source, getProjectRef(), plugin, 0, managed ); - return pluginDependencies.get( pr ); + PluginKey pk = new PluginKey( plugin, managed ); + return pluginDependencies.get( pk ); } public final List getBoms() @@ -144,19 +162,21 @@ public final List getBoms() return boms; } + @JsonIgnore @Override - public Set> getAllRelationships() + public Set> getAllRelationships() { - final Set> rels = getExactAllRelationships(); + final Set> rels = getExactAllRelationships(); filterTerminalParents( rels ); return rels; } + @JsonIgnore @Override - public Set> getExactAllRelationships() + public Set> getExactAllRelationships() { - final Set> result = new HashSet>(); + final Set> result = new HashSet>(); if ( parent != null ) { result.add( parent ); @@ -197,8 +217,8 @@ public static final class Builder private ParentRelationship parent; - private final Map> pluginDependencies = - new HashMap>(); + private final Map> pluginDependencies = + new HashMap>(); public Builder( final URI source, final ProjectVersionRef projectRef, final String... activeProfiles ) { @@ -210,7 +230,7 @@ public EProjectDirectRelationships build() { if ( parent == null ) { - parent = new ParentRelationship( source, ref ); + parent = new SimpleParentRelationship( ref ); } return new EProjectDirectRelationships( source, ref, parent, boms, dependencies, plugins, @@ -220,7 +240,7 @@ public EProjectDirectRelationships build() public Builder withParent( final ProjectVersionRef parent ) { - this.parent = new ParentRelationship( source, ref, parent ); + this.parent = new SimpleParentRelationship( source, ref, parent ); return this; } @@ -232,7 +252,7 @@ public Builder withParent( final ParentRelationship parent ) } @SuppressWarnings( "unchecked" ) - private > C adjustDeclaring( final C rel ) + private > C adjustDeclaring( final C rel ) { if ( !ref .equals( rel.getDeclaring() ) ) @@ -329,14 +349,14 @@ public Builder withPluginDependencies( final Collection pdrs = pluginDependencies.get( pr ); + List pdrs = pluginDependencies.get( pk ); if ( pdrs == null ) { pdrs = new ArrayList(); - pluginDependencies.put( pr, pdrs ); + pluginDependencies.put( pk, pdrs ); } if ( !pdrs.contains( rel ) ) @@ -393,10 +413,10 @@ public Builder withExtensions( final Collection exts ) return this; } - public Builder withRelationships( final Collection> relationships ) + public Builder withRelationships( final Collection> relationships ) { final Set pluginDepRels = new HashSet(); - for ( ProjectRelationship rel : relationships ) + for ( ProjectRelationship rel : relationships ) { rel = adjustDeclaring( rel ); switch ( rel.getType() ) @@ -447,10 +467,11 @@ public int getNextPluginIndex( final boolean managed ) return managed ? managedPlugins.size() : plugins.size(); } - public int getNextPluginDependencyIndex( final ProjectVersionRef plugin, final boolean managed ) + public int getNextPluginDependencyIndex( final ProjectVersionRef plugin, final boolean managed, + final boolean inherited ) { final List list = - pluginDependencies.get( new PluginRelationship( source, ref, plugin, 0, managed ) ); + pluginDependencies.get( new PluginKey( plugin, managed ) ); return list == null ? 0 : list.size(); } @@ -465,26 +486,26 @@ public int getNextExtensionIndex() } public Builder withDependency( final ProjectVersionRef ref, final String type, final String classifier, final DependencyScope scope, - final boolean managed ) + final boolean managed, final boolean inherited, final boolean optional ) { - withDependencies( new DependencyRelationship( source, ref, new ArtifactRef( ref, type, classifier, false ), + withDependencies( new SimpleDependencyRelationship( source, ref, new SimpleArtifactRef( ref, type, classifier ), scope, - getNextDependencyIndex( managed ), managed ) ); + getNextDependencyIndex( managed ), managed, inherited, optional ) ); return this; } - public Builder withPlugin( final ProjectVersionRef ref, final boolean managed ) + public Builder withPlugin( final ProjectVersionRef ref, final boolean managed, final boolean inherited ) { - withPlugins( new PluginRelationship( source, ref, ref, getNextPluginIndex( managed ), managed ) ); + withPlugins( new SimplePluginRelationship( source, ref, ref, getNextPluginIndex( managed ), managed, inherited ) ); return this; } - public Builder withExtension( final ProjectVersionRef ref ) + public Builder withExtension( final ProjectVersionRef ref, final boolean inherited ) { - withExtensions( new ExtensionRelationship( source, RelationshipUtils.POM_ROOT_URI, ref, ref, - getNextExtensionIndex() ) ); + withExtensions( new SimpleExtensionRelationship( source, POM_ROOT_URI, ref, ref, + getNextExtensionIndex(), inherited ) ); return this; } diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectRelationshipCollection.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectRelationshipCollection.java new file mode 100644 index 00000000..bef042a7 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/EProjectRelationshipCollection.java @@ -0,0 +1,31 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.model; + +import java.io.Serializable; +import java.util.Collection; + +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; + +public interface EProjectRelationshipCollection + extends Serializable +{ + + Collection> getAllRelationships(); + + Collection> getExactAllRelationships(); + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/PluginKey.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/PluginKey.java new file mode 100644 index 00000000..4b12e8bc --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/model/PluginKey.java @@ -0,0 +1,161 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.model; + +import org.commonjava.atlas.maven.graph.rel.PluginRelationship; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; + +/** + * Created by ruhan on 3/17/17. + */ +public final class PluginKey + implements Serializable +{ + private String groupId; + + private String artifactId; + + private String version; + + private boolean managed; + + public PluginKey() {} + + public PluginKey(ProjectVersionRef target, boolean managed) + { + this.groupId = target.getGroupId(); + this.artifactId = target.getArtifactId(); + this.version = target.getVersionString(); + this.managed = managed; + } + + public PluginKey(PluginRelationship rel) + { + this(rel.getTarget(), rel.isManaged()); + } + + public String getGroupId() + { + return groupId; + } + + public String getArtifactId() + { + return artifactId; + } + + public String getVersion() + { + return version; + } + + public boolean getManaged() + { + return managed; + } + + @Override + public String toString() + { + return String.format( "%s:%s:%s:%s", groupId, artifactId, version, managed ); + } + + public static PluginKey parse( final String pk ) + { + final String[] parts = pk.split( ":" ); + if ( parts.length < 4 ) + { + throw new RuntimeException( "PluginKey parse failed. (Given: '" + pk + "')" ); + } + PluginKey ret = new PluginKey(); + ret.groupId = parts[0]; + ret.artifactId = parts[1]; + ret.version = parts[2]; + ret.managed = Boolean.parseBoolean(parts[3]); + return ret; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); + result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) + { + if (this == obj) + { + return true; + } + if (obj == null) + { + return false; + } + if (!(obj instanceof PluginKey)) + { + return false; + } + + final PluginKey other = (PluginKey) obj; + + if (groupId == null) + { + if (other.getGroupId() != null) + { + return false; + } + } + else if (!groupId.equals(other.getGroupId())) + { + return false; + } + + if (artifactId == null) + { + if (other.getArtifactId() != null) + { + return false; + } + } + else if (!artifactId.equals(other.getArtifactId())) + { + return false; + } + + if (version == null) + { + if (other.getVersion() != null) + { + return false; + } + } + else if (!version.equals(other.getVersion())) + { + return false; + } + + return managed == other.getManaged(); + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/AbstractSimpleProjectRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/AbstractSimpleProjectRelationship.java new file mode 100644 index 00000000..ae3631f5 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/AbstractSimpleProjectRelationship.java @@ -0,0 +1,263 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; + +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.net.URI; +import java.util.*; + +public abstract class AbstractSimpleProjectRelationship, T extends ProjectVersionRef> + implements ProjectRelationship, Serializable +{ + + private static final long serialVersionUID = 1L; + + private final List sources = new ArrayList(); + + private final RelationshipType type; + + private final ProjectVersionRef declaring; + + private final T target; + + private final int index; + + private boolean managed = false; + + private boolean inherited; + + private boolean mixin; + + @SuppressWarnings( "rawtypes" ) + private transient Constructor cloneCtor; + + private URI pomLocation; + + private final boolean cloneUsesLocation = true; + + protected AbstractSimpleProjectRelationship( final URI source, final RelationshipType type, + final ProjectVersionRef declaring, final T target, final int index, + final boolean inherited, final boolean mixin ) + { + this( Collections.singleton( source ), RelationshipConstants.POM_ROOT_URI, type, declaring, target, index, false, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final Collection sources, final RelationshipType type, + final ProjectVersionRef declaring, final T target, final int index, + final boolean inherited, final boolean mixin ) + { + this( sources, RelationshipConstants.POM_ROOT_URI, type, declaring, target, index, false, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final URI source, final RelationshipType type, + final ProjectVersionRef declaring, final T target, final int index, + final boolean managed, final boolean inherited, final boolean mixin ) + { + this( Collections.singleton( source ), RelationshipConstants.POM_ROOT_URI, type, declaring, target, index, managed, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final Collection sources, final RelationshipType type, + final ProjectVersionRef declaring, final T target, final int index, + final boolean managed, final boolean inherited, final boolean mixin ) + { + this( sources, RelationshipConstants.POM_ROOT_URI, type, declaring, target, index, managed, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final URI source, final URI pomLocation, final RelationshipType type, + final ProjectVersionRef declaring, final T target, final int index, + final boolean inherited, final boolean mixin ) + { + this( Collections.singleton( source ), pomLocation, type, declaring, target, index, false, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final Collection sources, final URI pomLocation, + final RelationshipType type, final ProjectVersionRef declaring, + final T target, final int index, final boolean inherited, final boolean mixin ) + { + this( sources, pomLocation, type, declaring, target, index, false, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final URI source, final URI pomLocation, final RelationshipType type, + final ProjectVersionRef declaring, final T target, final int index, + final boolean managed, final boolean inherited, final boolean mixin ) + { + this( Collections.singleton( source ), pomLocation, type, declaring, target, index, managed, inherited, mixin ); + } + + protected AbstractSimpleProjectRelationship( final Collection sources, final URI pomLocation, + final RelationshipType type, final ProjectVersionRef declaring, + final T target, final int index, final boolean managed, + final boolean inherited, final boolean mixin ) + { + if ( sources == null ) + { + throw new NullPointerException( "Source URIs cannot be null" ); + } + + for ( URI u : sources ) + { + if ( !this.sources.contains( u ) ) + { + this.sources.add( u ); + } + } + + this.pomLocation = pomLocation; + if ( declaring == null || target == null ) + { + throw new NullPointerException( "Neither declaring ref (" + declaring + ") nor target ref (" + target + + ") can be null!" ); + } + + this.type = type; + this.declaring = declaring; + this.target = target; + this.index = index; + this.managed = managed; + this.inherited = inherited; + this.mixin = mixin; + } + + public AbstractSimpleProjectRelationship( final ProjectRelationship relationship ) + { + this.sources.addAll( relationship.getSources() ); + this.declaring = new SimpleProjectVersionRef( relationship.getDeclaring() ); + this.pomLocation = relationship.getPomLocation(); + this.index = relationship.getIndex(); + this.managed = relationship.isManaged(); + this.inherited = relationship.isInherited(); + this.mixin = relationship.isMixin(); + this.type = relationship.getType(); + this.target = cloneTarget( relationship.getTarget() ); + } + + protected abstract T cloneTarget( T target ); + + @Override + public final boolean isManaged() + { + return managed; + } + + @Override + public final boolean isInherited() + { + return inherited; + } + + @Override + public final boolean isMixin() + { + return mixin; + } + + @Override + public final int getIndex() + { + return index; + } + + @Override + public final RelationshipType getType() + { + return type; + } + + @Override + public final ProjectVersionRef getDeclaring() + { + return declaring; + } + + @Override + public final T getTarget() + { + return target; + } + + @Override + public abstract ArtifactRef getTargetArtifact(); + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ( ( declaring == null ) ? 0 : declaring.hashCode() ); + result = prime * result + ( ( target == null ) ? 0 : target.hashCode() ); + result = prime * result + ( ( type == null ) ? 0 : type.hashCode() ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( obj == null ) + { + return false; + } + if ( !(obj instanceof ProjectRelationship) ) + { + return false; + } + final ProjectRelationship other = (ProjectRelationship) obj; + if ( declaring == null ) + { + if ( other.getDeclaring() != null ) + { + return false; + } + } + else if ( !declaring.equals( other.getDeclaring() ) ) + { + return false; + } + if ( target == null ) + { + if ( other.getTarget() != null ) + { + return false; + } + } + else if ( !target.equals( other.getTarget() ) ) + { + return false; + } + return type == other.getType(); + } + + @Override + public final Set getSources() + { + return new HashSet( sources ); + } + + @Override + public final URI getPomLocation() + { + return pomLocation; + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/BomRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/BomRelationship.java new file mode 100644 index 00000000..49de5614 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/BomRelationship.java @@ -0,0 +1,40 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/24/15. + */ +public interface BomRelationship + extends ProjectRelationship,Serializable +{ + @Override + ArtifactRef getTargetArtifact(); + + @Override + BomRelationship selectDeclaring( ProjectVersionRef ref ); + + @Override + BomRelationship selectTarget( ProjectVersionRef ref ); + + @Override + BomRelationship cloneFor( ProjectVersionRef declaring ); +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/DependencyRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/DependencyRelationship.java new file mode 100644 index 00000000..bb7ee233 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/DependencyRelationship.java @@ -0,0 +1,51 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.DependencyScope; +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; +import java.util.Set; + +/** + * Created by jdcasey on 8/24/15. + */ +public interface DependencyRelationship + extends ProjectRelationship,Serializable +{ + DependencyScope getScope(); + + @Override + DependencyRelationship cloneFor( ProjectVersionRef projectRef ); + + @Override + ArtifactRef getTargetArtifact(); + + Set getExcludes(); + + @Override + DependencyRelationship selectDeclaring( ProjectVersionRef ref ); + + @Override + DependencyRelationship selectTarget( ProjectVersionRef ref ); + + boolean isBOM(); + + boolean isOptional(); +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ExtensionRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ExtensionRelationship.java new file mode 100644 index 00000000..fd580457 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ExtensionRelationship.java @@ -0,0 +1,40 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/24/15. + */ +public interface ExtensionRelationship + extends ProjectRelationship,Serializable +{ + @Override + ArtifactRef getTargetArtifact(); + + @Override + ExtensionRelationship selectDeclaring( ProjectVersionRef ref ); + + @Override + ExtensionRelationship selectTarget( ProjectVersionRef ref ); + + @Override + ExtensionRelationship cloneFor( ProjectVersionRef declaring ); +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ParentRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ParentRelationship.java new file mode 100644 index 00000000..e2f65350 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ParentRelationship.java @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/24/15. + */ +public interface ParentRelationship + extends ProjectRelationship,Serializable +{ + @Override + ArtifactRef getTargetArtifact(); + + boolean isTerminus(); + + @Override + ParentRelationship selectDeclaring( ProjectVersionRef ref ); + + @Override + ParentRelationship selectTarget( ProjectVersionRef ref ); + + @Override + ParentRelationship cloneFor( ProjectVersionRef declaring ); +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/PluginDependencyRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/PluginDependencyRelationship.java new file mode 100644 index 00000000..50b4d152 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/PluginDependencyRelationship.java @@ -0,0 +1,45 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/24/15. + */ +public interface PluginDependencyRelationship + extends ProjectRelationship,Serializable +{ + ProjectRef getPlugin(); + + @Override + PluginDependencyRelationship cloneFor( ProjectVersionRef projectRef ); + + @Override + ArtifactRef getTargetArtifact(); + + @Override + PluginDependencyRelationship selectDeclaring( ProjectVersionRef ref ); + + @Override + PluginDependencyRelationship selectTarget( ProjectVersionRef ref ); + + boolean isOptional(); +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/PluginRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/PluginRelationship.java new file mode 100644 index 00000000..9a29479e --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/PluginRelationship.java @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +import java.io.Serializable; + +/** + * Created by jdcasey on 8/24/15. + */ +public interface PluginRelationship + extends ProjectRelationship,Serializable +{ + boolean isReporting(); + + @Override + PluginRelationship cloneFor( ProjectVersionRef projectRef ); + + @Override + ArtifactRef getTargetArtifact(); + + @Override + PluginRelationship selectDeclaring( ProjectVersionRef ref ); + + @Override + PluginRelationship selectTarget( ProjectVersionRef ref ); +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ProjectRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ProjectRelationship.java new file mode 100644 index 00000000..ae18809e --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/ProjectRelationship.java @@ -0,0 +1,60 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import java.io.Serializable; +import java.net.URI; +import java.util.Collection; +import java.util.Set; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; + +public interface ProjectRelationship, T extends ProjectVersionRef> + extends Serializable +{ + + int getIndex(); + + RelationshipType getType(); + + ProjectVersionRef getDeclaring(); + + T getTarget(); + + ArtifactRef getTargetArtifact(); + + R cloneFor( final ProjectVersionRef projectRef ); + + R selectDeclaring( ProjectVersionRef ref ); + + R selectTarget( ProjectVersionRef ref ); + + boolean isManaged(); + + Set getSources(); + + R addSource( URI source ); + + R addSources( Collection sources ); + + URI getPomLocation(); + + boolean isInherited(); + + boolean isMixin(); + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipComparator.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipComparator.java new file mode 100644 index 00000000..b9b9a0e1 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipComparator.java @@ -0,0 +1,64 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import java.util.Comparator; + +public final class RelationshipComparator + implements Comparator> +{ + + public static final RelationshipComparator INSTANCE = new RelationshipComparator(); + + private RelationshipComparator() + { + } + + @Override + public int compare( final ProjectRelationship one, final ProjectRelationship two ) + { + if ( one.getType() == two.getType() ) + { + if ( one.getPomLocation() + .equals( RelationshipConstants.POM_ROOT_URI ) && !two.getPomLocation() + .equals( RelationshipConstants.POM_ROOT_URI ) ) + { + return -1; + } + else if ( !one.getPomLocation() + .equals( RelationshipConstants.POM_ROOT_URI ) && two.getPomLocation() + .equals( RelationshipConstants.POM_ROOT_URI ) ) + { + return 1; + } + + int res = one.getDeclaring().compareTo( two.getDeclaring() ); + if ( res == 0 ) + { + res = one.getIndex() - two.getIndex(); + } + + return res; + } + else + { + return one.getType() + .ordinal() - two.getType() + .ordinal(); + } + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipConstants.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipConstants.java new file mode 100644 index 00000000..910f8553 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipConstants.java @@ -0,0 +1,74 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * Created by ruhan on 12/6/16. + */ +public class RelationshipConstants { + + public static final URI UNKNOWN_SOURCE_URI; + + public static final URI POM_ROOT_URI; + + public static final URI ANY_SOURCE_URI; + + public static final URI TERMINAL_PARENT_SOURCE_URI; + + static + { + final String uri = "atlas:terminal-parent"; + try + { + TERMINAL_PARENT_SOURCE_URI = new URI( uri ); + } + catch ( final URISyntaxException e ) + { + throw new IllegalStateException( "Terminal-parent source URI constant is invalid: " + uri, e ); + } + + try + { + ANY_SOURCE_URI = new URI( "any:any" ); + } + catch ( final URISyntaxException e ) + { + throw new IllegalStateException( "Cannot construct any-source URI: 'any:any'" ); + } + + try + { + UNKNOWN_SOURCE_URI = new URI( "unknown:unknown" ); + } + catch ( final URISyntaxException e ) + { + throw new IllegalStateException( "Cannot construct unknown-source URI: 'unknown:unknown'" ); + } + + try + { + POM_ROOT_URI = new URI( "pom:root" ); + } + catch ( final URISyntaxException e ) + { + throw new IllegalStateException( "Cannot construct pom-root URI: 'pom:root'" ); + } + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipPathComparator.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipPathComparator.java similarity index 50% rename from relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipPathComparator.java rename to relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipPathComparator.java index 3d835f12..9b61cb66 100644 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipPathComparator.java +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipPathComparator.java @@ -1,20 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Comparator; import java.util.List; public class RelationshipPathComparator - implements Comparator>> + implements Comparator>> { public static RelationshipPathComparator INSTANCE = new RelationshipPathComparator(); @@ -26,8 +34,11 @@ private RelationshipPathComparator() } @Override - public int compare( final List> one, final List> two ) + public int compare( final List> one, final List> two ) { + Logger logger = LoggerFactory.getLogger( getClass() ); + logger.debug("Comparing:\nOne: {}\nTwo: {}", one, two); + final int commonLen = Math.min( one.size(), two.size() ); if ( one.size() > commonLen ) @@ -60,12 +71,12 @@ else if ( two.size() > commonLen ) return 0; } - private int compareRels( final ProjectRelationship one, final ProjectRelationship two ) + private int compareRels( final ProjectRelationship one, final ProjectRelationship two ) { return comp.compare( one, two ); } - private int compareRelTypes( final ProjectRelationship one, final ProjectRelationship two ) + private int compareRelTypes( final ProjectRelationship one, final ProjectRelationship two ) { return one.getType() .ordinal() - two.getType() diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipType.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipType.java new file mode 100644 index 00000000..9cfeb9fa --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/RelationshipType.java @@ -0,0 +1,70 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public enum RelationshipType +{ + + PARENT( "parent" ), BOM( "bom" ), DEPENDENCY( "dependency", "dep" ), PLUGIN( "plugin" ), PLUGIN_DEP( + "plugin-dependency", "plugin-dep", "plugin-level-dependency", "plugin-level-dep" ), EXTENSION( "extension", + "ext" ); + + private final Set names; + + RelationshipType( final String... names ) + { + this.names = Collections.unmodifiableSet( new HashSet( Arrays.asList( names ) ) ); + } + + public Set names() + { + return names; + } + + public static RelationshipType getType( String type ) + { + if ( type == null || type.trim() + .length() < 1 ) + { + return null; + } + + type = type.trim(); + for ( final RelationshipType rt : values() ) + { + if ( rt.name().equals(type)) + { + return rt; + } + + for ( final String name : rt.names() ) + { + if ( name.equalsIgnoreCase( type ) ) + { + return rt; + } + } + } + + return null; + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleBomRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleBomRelationship.java new file mode 100644 index 00000000..d7c8ced7 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleBomRelationship.java @@ -0,0 +1,135 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import java.net.URI; +import java.util.Collection; +import java.util.Set; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; + +/** NOTE: BOM relationships are actually marked as concrete. + * This may be somewhat counter-intuitive, but they are structural (like a parent POM). + * Therefore, managed isn't correct (despite Maven's unfortunate choice for location). + */ +public class SimpleBomRelationship + extends AbstractSimpleProjectRelationship + implements BomRelationship +{ + + private static final long serialVersionUID = 1L; + + public SimpleBomRelationship( final Collection sources, final ProjectVersionRef d, final ProjectVersionRef t, + final int index, final boolean inherited, final boolean mixin ) + { + // BOMs are actually marked as concrete...somewhat counter-intuitive, + // but they're structural, so managed isn't quite correct (despite + // Maven's unfortunate choice for location). + super( sources, RelationshipType.BOM, d, t, index, false, inherited, mixin ); + } + + public SimpleBomRelationship( final URI source, final ProjectVersionRef d, final ProjectVersionRef t, + final int index, final boolean inherited, final boolean mixin ) + { + // BOMs are actually marked as concrete...somewhat counter-intuitive, + // but they're structural, so managed isn't quite correct (despite + // Maven's unfortunate choice for location). + super( source, RelationshipType.BOM, d, t, index, false, inherited, mixin ); + } + + public SimpleBomRelationship( final Collection sources, final URI pomLocation, final ProjectVersionRef d, + final ProjectVersionRef t, final int index, final boolean inherited, final boolean mixin ) + { + // BOMs are actually marked as concrete...somewhat counter-intuitive, + // but they're structural, so managed isn't quite correct (despite + // Maven's unfortunate choice for location). + super( sources, pomLocation, RelationshipType.BOM, d, t, index, false, inherited, mixin ); + } + + public SimpleBomRelationship( final URI source, final URI pomLocation, final ProjectVersionRef d, + final ProjectVersionRef t, final int index, final boolean inherited, final boolean mixin ) + { + // BOMs are actually marked as concrete...somewhat counter-intuitive, + // but they're structural, so managed isn't quite correct (despite + // Maven's unfortunate choice for location). + super( source, pomLocation, RelationshipType.BOM, d, t, index, false, inherited, mixin ); + } + + public SimpleBomRelationship( final BomRelationship relationship ) + { + super( relationship ); + } + + @Override + protected ProjectVersionRef cloneTarget( final ProjectVersionRef target ) + { + return new SimpleProjectVersionRef( target ); + } + + @Override + public ArtifactRef getTargetArtifact() + { + return getTarget().asPomArtifact(); + } + + @Override + public BomRelationship selectDeclaring( final ProjectVersionRef ref ) + { + final ProjectVersionRef t = getTarget(); + + return new SimpleBomRelationship( getSources(), ref, t, getIndex(), isInherited(), isMixin() ); + } + + @Override + public BomRelationship selectTarget( final ProjectVersionRef ref ) + { + final ProjectVersionRef d = getDeclaring(); + + return new SimpleBomRelationship( getSources(), d, ref, getIndex(), isInherited(), isMixin() ); + } + + @Override + public BomRelationship cloneFor( final ProjectVersionRef declaring ) + { + return new SimpleBomRelationship( getSources(), getPomLocation(), declaring, getTarget(), getIndex(), isInherited(), isMixin() ); + } + + @Override + public BomRelationship addSource( final URI source ) + { + Set srcs = getSources(); + srcs.add( source ); + return new SimpleBomRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), + getIndex(), isInherited(), isMixin() ); + } + + @Override + public BomRelationship addSources( final Collection sources ) + { + Set srcs = getSources(); + srcs.addAll( sources ); + return new SimpleBomRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), + getIndex(), isInherited(), isMixin() ); + } + + @Override + public String toString() + { + return String.format( "BomRelationship [%s => %s]", getDeclaring(), getTarget() ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleDependencyRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleDependencyRelationship.java new file mode 100644 index 00000000..6bc3f10a --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleDependencyRelationship.java @@ -0,0 +1,215 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.DependencyScope; +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; + +import java.io.Serializable; +import java.net.URI; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +public final class SimpleDependencyRelationship + extends AbstractSimpleProjectRelationship + implements Serializable, DependencyRelationship +{ + + private static final long serialVersionUID = 1L; + + private final DependencyScope scope; + + private final Set excludes; + + private boolean optional; + + public SimpleDependencyRelationship( final URI source, final ProjectVersionRef declaring, final ArtifactRef target, + final DependencyScope scope, final int index, final boolean managed, + final boolean inherited, final boolean optional, final ProjectRef... excludes ) + { + super( source, RelationshipType.DEPENDENCY, declaring, target, index, managed, inherited, false ); + this.scope = scope == null ? DependencyScope.compile : scope; + this.optional = optional; + this.excludes = new HashSet( Arrays.asList( excludes ) ); + } + + public SimpleDependencyRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, + final ArtifactRef target, final DependencyScope scope, final int index, + final boolean managed, final boolean inherited, final boolean optional, + final ProjectRef... excludes ) + { + super( source, pomLocation, RelationshipType.DEPENDENCY, declaring, target, index, managed, inherited, false ); + this.scope = scope == null ? DependencyScope.compile : scope; + this.optional = optional; + this.excludes = new HashSet( Arrays.asList( excludes ) ); + } + + public SimpleDependencyRelationship( final Collection sources, final ProjectVersionRef declaring, + final ArtifactRef target, final DependencyScope scope, final int index, + final boolean managed, final boolean inherited, final boolean optional, + final ProjectRef... excludes ) + { + super( sources, RelationshipType.DEPENDENCY, declaring, target, index, managed, inherited, false ); + this.scope = scope == null ? DependencyScope.compile : scope; + this.optional = optional; + this.excludes = new HashSet( Arrays.asList( excludes ) ); + } + + public SimpleDependencyRelationship( final Collection sources, final URI pomLocation, + final ProjectVersionRef declaring, final ArtifactRef target, + final DependencyScope scope, final int index, final boolean managed, + final boolean inherited, final boolean optional, final ProjectRef... excludes ) + { + super( sources, pomLocation, RelationshipType.DEPENDENCY, declaring, target, index, managed, inherited, false ); + this.scope = scope == null ? DependencyScope.compile : scope; + this.optional = optional; + this.excludes = new HashSet( Arrays.asList( excludes ) ); + } + + public SimpleDependencyRelationship( final DependencyRelationship relationship ) + { + super( relationship ); + this.scope = relationship.getScope(); + this.optional = relationship.isOptional(); + this.excludes = new HashSet( relationship.getExcludes() ); + } + + @Override + public final DependencyScope getScope() + { + return scope; + } + + @Override + public boolean isOptional() + { + return optional; + } + + @Override + public synchronized DependencyRelationship cloneFor( final ProjectVersionRef projectRef ) + { + return new SimpleDependencyRelationship( getSources(), getPomLocation(), projectRef, getTarget(), scope, getIndex(), + isManaged(), isInherited(), optional ); + } + + @Override + public DependencyRelationship addSource( final URI source ) + { + Set srcs = getSources(); + srcs.add( source ); + return new SimpleDependencyRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), scope, getIndex(), + isManaged(), isInherited(), optional ); + } + + @Override + public DependencyRelationship addSources( final Collection sources ) + { + Set srcs = getSources(); + srcs.addAll( sources ); + return new SimpleDependencyRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), scope, getIndex(), + isManaged(), isInherited(), optional ); + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ( isManaged() ? 1231 : 1237 ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( !super.equals( obj ) ) + { + return false; + } + if ( !( obj instanceof DependencyRelationship ) ) + { + return false; + } + final DependencyRelationship other = (DependencyRelationship) obj; + return isManaged() == other.isManaged(); + } + + @Override + public String toString() + { + return String.format( "DependencyRelationship [%s => %s (managed=%s, scope=%s, index=%s)]", getDeclaring(), + getTarget(), isManaged(), scope, getIndex() ); + } + + @Override + protected ArtifactRef cloneTarget( final ArtifactRef target ) + { + return new SimpleArtifactRef( target ); + } + + @Override + public ArtifactRef getTargetArtifact() + { + return getTarget(); + } + + @Override + public Set getExcludes() + { + return excludes; + } + + @Override + public DependencyRelationship selectDeclaring( final ProjectVersionRef ref ) + { + final ArtifactRef t = getTarget(); + + Set var = getExcludes(); + return new SimpleDependencyRelationship( getSources(), getPomLocation(), ref, t, getScope(), getIndex(), isManaged(), + isInherited(), optional, var.toArray( new ProjectRef[var.size()] ) ); + } + + @Override + public DependencyRelationship selectTarget( final ProjectVersionRef ref ) + { + final ProjectVersionRef d = getDeclaring(); + ArtifactRef t = getTarget(); + t = + (ArtifactRef) ( ( ref instanceof ArtifactRef ) ? ref : new SimpleArtifactRef( ref, t.getType(), + t.getClassifier() ) ); + + Set var = getExcludes(); + return new SimpleDependencyRelationship( getSources(), getPomLocation(), d, t, getScope(), getIndex(), isManaged(), + isInherited(), optional, var.toArray( new ProjectRef[var.size()] ) ); + } + + @Override + public boolean isBOM() + { + return DependencyScope._import == getScope() && "pom".equals( getTargetArtifact().getType() ); + } + +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleExtensionRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleExtensionRelationship.java new file mode 100644 index 00000000..a7ee7aaa --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleExtensionRelationship.java @@ -0,0 +1,123 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; + +import java.io.Serializable; +import java.net.URI; +import java.util.Collection; +import java.util.Set; + +public final class SimpleExtensionRelationship + extends AbstractSimpleProjectRelationship + implements Serializable, ExtensionRelationship +{ + + private static final long serialVersionUID = 1L; + + public SimpleExtensionRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, final boolean inherited ) + { + super( source, pomLocation, RelationshipType.EXTENSION, declaring, target, index, inherited, false ); + } + + public SimpleExtensionRelationship( final Collection sources, final URI pomLocation, + final ProjectVersionRef declaring, final ProjectVersionRef target, + final int index, final boolean inherited ) + { + super( sources, pomLocation, RelationshipType.EXTENSION, declaring, target, index, inherited, false ); + } + + public SimpleExtensionRelationship( final URI source, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, + final boolean inherited ) + { + super( source, RelationshipConstants.POM_ROOT_URI, RelationshipType.EXTENSION, declaring, target, index, inherited, false ); + } + + public SimpleExtensionRelationship( final Collection sources, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, + final boolean inherited ) + { + super( sources, RelationshipConstants.POM_ROOT_URI, RelationshipType.EXTENSION, declaring, target, index, inherited, false ); + } + + public SimpleExtensionRelationship( final ExtensionRelationship relationship ) + { + super( relationship ); + } + + @Override + public String toString() + { + return String.format( "ExtensionRelationship [%s => %s (index=%s)]", getDeclaring(), getTarget(), getIndex() ); + } + + @Override + protected ProjectVersionRef cloneTarget( final ProjectVersionRef target ) + { + return new SimpleProjectVersionRef( target ); + } + + @Override + public ArtifactRef getTargetArtifact() + { + return new SimpleArtifactRef( getTarget(), null, null ); + } + + @Override + public ExtensionRelationship selectDeclaring( final ProjectVersionRef ref ) + { + final ProjectVersionRef t = getTarget(); + + // TODO + return new SimpleExtensionRelationship( getSources(), getPomLocation(), ref, t, getIndex(), isInherited() ); + } + + @Override + public ExtensionRelationship selectTarget( final ProjectVersionRef ref ) + { + final ProjectVersionRef d = getDeclaring(); + + return new SimpleExtensionRelationship( getSources(), getPomLocation(), d, ref, getIndex(), isInherited() ); + } + + @Override + public ExtensionRelationship cloneFor( final ProjectVersionRef declaring ) + { + return new SimpleExtensionRelationship( getSources(), getPomLocation(), declaring, getTarget(), getIndex(), isInherited() ); + } + + @Override + public ExtensionRelationship addSource( final URI source ) + { + Set srcs = getSources(); + srcs.add( source ); + return new SimpleExtensionRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), getIndex(), isInherited() ); + } + + @Override + public ExtensionRelationship addSources( final Collection sources ) + { + Set srcs = getSources(); + srcs.addAll( sources ); + return new SimpleExtensionRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), getIndex(), isInherited() ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleParentRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleParentRelationship.java new file mode 100644 index 00000000..5867876e --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimpleParentRelationship.java @@ -0,0 +1,131 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; + +import java.io.Serializable; +import java.net.URI; +import java.util.Collection; +import java.util.Set; + +public final class SimpleParentRelationship + extends AbstractSimpleProjectRelationship + implements Serializable, ParentRelationship +{ + + private static final long serialVersionUID = 1L; + + /** + * Ancestry terminus. This is to signify that the declaring project has NO parent relationship. + */ + public SimpleParentRelationship( final ProjectVersionRef declaring ) + { + super( RelationshipConstants.TERMINAL_PARENT_SOURCE_URI, RelationshipType.PARENT, declaring, declaring, 0, false, false ); + } + + /** + * Ancestry terminus. This is to signify that the declaring project has NO parent relationship. + * This form is deprecated. + * @see SimpleParentRelationship(ProjectVersionRef) + */ + @Deprecated + public SimpleParentRelationship( final URI unused, final ProjectVersionRef declaring ) + { + super( RelationshipConstants.TERMINAL_PARENT_SOURCE_URI, RelationshipType.PARENT, declaring, declaring, 0, false, false ); + } + + public SimpleParentRelationship( final URI source, final ProjectVersionRef declaring, + final ProjectVersionRef target ) + { + super( source, RelationshipType.PARENT, declaring, target, 0, false, false ); + } + + public SimpleParentRelationship( final Collection sources, final ProjectVersionRef declaring, + final ProjectVersionRef target ) + { + super( sources, RelationshipType.PARENT, declaring, target, 0, false, false ); + } + + public SimpleParentRelationship( final ParentRelationship relationship ) + { + super( relationship ); + } + + @Override + public String toString() + { + return String.format( "ParentRelationship [%s => %s]", getDeclaring(), getTarget() ); + } + + @Override + protected ProjectVersionRef cloneTarget( final ProjectVersionRef target ) + { + return new SimpleProjectVersionRef( target ); + } + + @Override + public ArtifactRef getTargetArtifact() + { + return new SimpleArtifactRef( getTarget(), "pom", null ); + } + + @Override + public boolean isTerminus() + { + return getDeclaring().equals( getTarget() ); + } + + @Override + public ParentRelationship selectDeclaring( final ProjectVersionRef ref ) + { + final ProjectVersionRef t = getTarget(); + + return new SimpleParentRelationship( getSources(), ref, t ); + } + + @Override + public ParentRelationship selectTarget( final ProjectVersionRef ref ) + { + final ProjectVersionRef d = getDeclaring(); + return new SimpleParentRelationship( getSources(), d, ref ); + } + + @Override + public ParentRelationship cloneFor( final ProjectVersionRef declaring ) + { + return new SimpleParentRelationship( getSources(), declaring, getTarget() ); + } + + @Override + public ParentRelationship addSource( final URI source ) + { + Set srcs = getSources(); + srcs.add( source ); + return new SimpleParentRelationship( srcs, getDeclaring(), getTarget() ); + } + + @Override + public ParentRelationship addSources( final Collection sources ) + { + Set srcs = getSources(); + srcs.addAll( sources ); + return new SimpleParentRelationship( srcs, getDeclaring(), getTarget() ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimplePluginDependencyRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimplePluginDependencyRelationship.java new file mode 100644 index 00000000..5203f328 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimplePluginDependencyRelationship.java @@ -0,0 +1,197 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectRef; + +import java.io.Serializable; +import java.net.URI; +import java.util.Collection; +import java.util.Set; + +public final class SimplePluginDependencyRelationship + extends AbstractSimpleProjectRelationship + implements Serializable, PluginDependencyRelationship +{ + + private static final long serialVersionUID = 1L; + + private final ProjectRef plugin; + + private boolean optional; + + public SimplePluginDependencyRelationship( final URI source, final ProjectVersionRef declaring, + final ProjectRef plugin, final ArtifactRef target, final int index, + final boolean managed, final boolean inherited ) + { + super( source, RelationshipType.PLUGIN_DEP, declaring, target, index, managed, inherited, false ); + this.plugin = plugin; + this.optional = optional; + } + + public SimplePluginDependencyRelationship( final URI source, final URI pomLocation, + final ProjectVersionRef declaring, final ProjectRef plugin, + final ArtifactRef target, final int index, final boolean managed, + final boolean inherited ) + { + super( source, pomLocation, RelationshipType.PLUGIN_DEP, declaring, target, index, managed, inherited, false ); + this.plugin = plugin; + this.optional = optional; + } + + public SimplePluginDependencyRelationship( final Collection sources, final URI pomLocation, + final ProjectVersionRef declaring, final ProjectRef plugin, + final ArtifactRef target, final int index, final boolean managed, + final boolean inherited ) + { + super( sources, pomLocation, RelationshipType.PLUGIN_DEP, declaring, target, index, managed, inherited, false ); + this.plugin = plugin; + this.optional = optional; + } + + public SimplePluginDependencyRelationship( final PluginDependencyRelationship relationship ) + { + super( relationship ); + this.plugin = new SimpleProjectRef( relationship.getPlugin() ); + this.optional = optional; + } + + @Override + public final ProjectRef getPlugin() + { + return plugin; + } + + @Override + public boolean isOptional() + { + return optional; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ( isManaged() ? 1231 : 1237 ); + result = prime * result + ( ( plugin == null ) ? 0 : plugin.hashCode() ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( !super.equals( obj ) ) + { + return false; + } + if ( !(obj instanceof PluginDependencyRelationship) ) + { + return false; + } + final PluginDependencyRelationship other = (PluginDependencyRelationship) obj; + if ( isManaged() != other.isManaged() ) + { + return false; + } + if ( plugin == null ) + { + if ( other.getPlugin() != null ) + { + return false; + } + } + else if ( !plugin.equals( other.getPlugin() ) ) + { + return false; + } + return true; + } + + @Override + public String toString() + { + return String.format( "PluginDependencyRelationship [%s -> (%s) => %s (managed=%s, index=%s)]", getDeclaring(), + plugin, getTarget(), isManaged(), getIndex() ); + } + + @Override + protected ArtifactRef cloneTarget( final ArtifactRef target ) + { + return new SimpleArtifactRef( target ); + } + + @Override + public ArtifactRef getTargetArtifact() + { + return getTarget(); + } + + @Override + public PluginDependencyRelationship selectDeclaring( final ProjectVersionRef ref ) + { + final ArtifactRef t = getTarget(); + + return new SimplePluginDependencyRelationship( getSources(), getPomLocation(), ref, getPlugin(), t, getIndex(), + isManaged(), isInherited() ); + } + + @Override + public PluginDependencyRelationship selectTarget( final ProjectVersionRef ref ) + { + final ProjectVersionRef d = getDeclaring(); + ArtifactRef t = getTarget(); + t = + (ArtifactRef) ( ( ref instanceof ArtifactRef ) ? ref : new SimpleArtifactRef( ref, t.getType(), + t.getClassifier() ) ); + + return new SimplePluginDependencyRelationship( getSources(), getPomLocation(), d, getPlugin(), t, getIndex(), + isManaged(), isInherited() ); + } + + @Override + public synchronized PluginDependencyRelationship cloneFor( final ProjectVersionRef projectRef ) + { + return new SimplePluginDependencyRelationship( getSources(), getPomLocation(), projectRef, plugin, getTarget(), + getIndex(), isManaged(), isInherited() ); + } + + @Override + public PluginDependencyRelationship addSource( final URI source ) + { + Set srcs = getSources(); + srcs.add( source ); + return new SimplePluginDependencyRelationship( srcs, getPomLocation(), getDeclaring(), plugin, getTarget(), + getIndex(), isManaged(), isInherited() ); + } + + @Override + public PluginDependencyRelationship addSources( final Collection sources ) + { + Set srcs = getSources(); + srcs.addAll( sources ); + return new SimplePluginDependencyRelationship( srcs, getPomLocation(), getDeclaring(), plugin, getTarget(), + getIndex(), isManaged(), isInherited() ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimplePluginRelationship.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimplePluginRelationship.java new file mode 100644 index 00000000..4afe3faf --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/rel/SimplePluginRelationship.java @@ -0,0 +1,174 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import java.io.Serializable; +import java.net.URI; +import java.util.Collection; +import java.util.Set; + +import org.commonjava.atlas.maven.ident.ref.ArtifactRef; +import org.commonjava.atlas.maven.ident.ref.SimpleArtifactRef; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; + +public final class SimplePluginRelationship + extends AbstractSimpleProjectRelationship + implements Serializable, PluginRelationship +{ + + private static final long serialVersionUID = 1L; + + private final boolean reporting; + + public SimplePluginRelationship( final URI source, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, final boolean managed, + final boolean inherited ) + { + this( source, declaring, target, index, managed, false, inherited ); + } + + public SimplePluginRelationship( final URI source, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, final boolean managed, + final boolean reporting, final boolean inherited ) + { + super( source, RelationshipType.PLUGIN, declaring, target, index, managed, inherited, false ); + this.reporting = reporting; + } + + public SimplePluginRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, final boolean managed, + final boolean inherited ) + { + this( source, pomLocation, declaring, target, index, managed, false, inherited ); + } + + public SimplePluginRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, + final ProjectVersionRef target, final int index, final boolean managed, + final boolean reporting, final boolean inherited ) + { + super( source, pomLocation, RelationshipType.PLUGIN, declaring, target, index, managed, inherited, false ); + this.reporting = reporting; + } + + public SimplePluginRelationship( final Collection sources, final URI pomLocation, + final ProjectVersionRef declaring, final ProjectVersionRef target, final int index, + final boolean managed, final boolean reporting, final boolean inherited ) + { + super( sources, pomLocation, RelationshipType.PLUGIN, declaring, target, index, managed, inherited, false ); + this.reporting = reporting; + } + + public SimplePluginRelationship( final PluginRelationship relationship ) + { + super( relationship ); + this.reporting = relationship.isReporting(); + } + + @Override + public final boolean isReporting() + { + return reporting; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ( isManaged() ? 1231 : 1237 ); + return result; + } + + @Override + public boolean equals( final Object obj ) + { + if ( this == obj ) + { + return true; + } + if ( !super.equals( obj ) ) + { + return false; + } + if ( !(obj instanceof PluginRelationship) ) + { + return false; + } + final PluginRelationship other = (PluginRelationship) obj; + return isManaged() == other.isManaged(); + } + + @Override + public String toString() + { + return String.format( "PluginRelationship [%s => %s (managed=%s, index=%s)]", getDeclaring(), getTarget(), + isManaged(), getIndex() ); + } + + @Override + protected ProjectVersionRef cloneTarget( final ProjectVersionRef target ) + { + return new SimpleProjectVersionRef( target ); + } + + @Override + public ArtifactRef getTargetArtifact() + { + return new SimpleArtifactRef( getTarget(), "maven-plugin", null ); + } + + @Override + public PluginRelationship selectDeclaring( final ProjectVersionRef ref ) + { + final ProjectVersionRef t = getTarget(); + + return new SimplePluginRelationship( getSources(), getPomLocation(), ref, t, getIndex(), isManaged(), isReporting(), isInherited() ); + } + + @Override + public PluginRelationship selectTarget( final ProjectVersionRef ref ) + { + final ProjectVersionRef d = getDeclaring(); + + return new SimplePluginRelationship( getSources(), getPomLocation(), d, ref, getIndex(), isManaged(), isReporting(), isInherited() ); + } + + @Override + public synchronized PluginRelationship cloneFor( final ProjectVersionRef projectRef ) + { + return new SimplePluginRelationship( getSources(), getPomLocation(), projectRef, getTarget(), getIndex(), + isManaged(), reporting, isInherited() ); + } + + @Override + public PluginRelationship addSource( final URI source ) + { + Set srcs = getSources(); + srcs.add( source ); + return new SimplePluginRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), getIndex(), + isManaged(), reporting, isInherited() ); + } + + @Override + public PluginRelationship addSources( final Collection sources ) + { + Set srcs = getSources(); + srcs.addAll( sources ); + return new SimplePluginRelationship( srcs, getPomLocation(), getDeclaring(), getTarget(), getIndex(), + isManaged(), reporting, isInherited() ); + } +} diff --git a/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/util/RelationshipUtils.java b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/util/RelationshipUtils.java new file mode 100644 index 00000000..8f75a222 --- /dev/null +++ b/relationships-api/src/main/java/org/commonjava/atlas/maven/graph/util/RelationshipUtils.java @@ -0,0 +1,165 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.util; + +import static org.commonjava.atlas.maven.graph.rel.RelationshipConstants.POM_ROOT_URI; +import static org.commonjava.atlas.maven.ident.util.IdentityUtils.artifact; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collection; +import java.util.Iterator; + +import org.commonjava.atlas.maven.graph.rel.DependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.ParentRelationship; +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleDependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleParentRelationship; +import org.commonjava.atlas.maven.ident.DependencyScope; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; + +public final class RelationshipUtils +{ + + public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, + final String version, final int index, final boolean inherited, final boolean optional ) + throws InvalidVersionSpecificationException + { + return dependency( source, owner, groupId, artifactId, version, null, null, optional, null, index, false, inherited ); + } + + public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, + final ProjectVersionRef dep, final int index, final boolean inherited, + final boolean optional ) + throws InvalidVersionSpecificationException + { + return dependency( source, owner, dep, null, null, optional, null, index, false, inherited ); + } + + public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, + final String version, final DependencyScope scope, final int index, final boolean managed, + final boolean inherited, final boolean optional ) + throws InvalidVersionSpecificationException + { + return dependency( source, owner, groupId, artifactId, version, null, null, optional, scope, index, managed, inherited ); + } + + public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final ProjectVersionRef dep, + final DependencyScope scope, final int index, final boolean managed, + final boolean inherited, final boolean optional ) + throws InvalidVersionSpecificationException + { + return new SimpleDependencyRelationship( source, owner, artifact( dep, null, null ), scope, index, managed, inherited, optional ); + } + + public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, + final String version, final String type, final String classifier, final boolean optional, + final DependencyScope scope, final int index, final boolean managed, final boolean inherited ) + throws InvalidVersionSpecificationException + { + return new SimpleDependencyRelationship( source, owner, artifact( groupId, artifactId, version, type, classifier ), scope, index, + managed, inherited, optional ); + } + + public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final ProjectVersionRef dep, final String type, + final String classifier, final boolean optional, final DependencyScope scope, final int index, + final boolean managed, final boolean inherited ) + throws InvalidVersionSpecificationException + { + return new SimpleDependencyRelationship( source, owner, artifact( dep, type, classifier ), scope, index, managed, inherited, optional ); + } + + public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, + final String artifactId, final String version, final int index, final boolean inherited, + final boolean optional ) + throws InvalidVersionSpecificationException + { + return dependency( source, pomLocation, owner, groupId, artifactId, version, null, null, optional, null, index, false, inherited ); + } + + public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, + final ProjectVersionRef dep, final int index, final boolean inherited, + final boolean optional ) + throws InvalidVersionSpecificationException + { + return dependency( source, pomLocation, owner, dep, null, null, optional, null, index, false, inherited ); + } + + public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, + final String artifactId, final String version, final DependencyScope scope, final int index, + final boolean managed, final boolean inherited, final boolean optional ) + throws InvalidVersionSpecificationException + { + return dependency( source, pomLocation, owner, groupId, artifactId, version, null, null, optional, scope, index, managed, inherited ); + } + + public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, + final ProjectVersionRef dep, final DependencyScope scope, final int index, + final boolean managed, final boolean inherited, final boolean optional ) + throws InvalidVersionSpecificationException + { + return new SimpleDependencyRelationship( source, pomLocation, owner, artifact( dep, null, null ), scope, index, managed, inherited, optional ); + } + + public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, + final String artifactId, final String version, final String type, final String classifier, + final boolean optional, final DependencyScope scope, final int index, final boolean managed, + final boolean inherited ) + throws InvalidVersionSpecificationException + { + return new SimpleDependencyRelationship( source, pomLocation, owner, artifact( groupId, artifactId, version, type, classifier ), scope, + index, managed, inherited, optional ); + } + + public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, + final ProjectVersionRef dep, final String type, final String classifier, final boolean optional, + final DependencyScope scope, final int index, final boolean managed, final boolean inherited ) + throws InvalidVersionSpecificationException + { + return new SimpleDependencyRelationship( source, pomLocation, owner, artifact( dep, type, classifier ), scope, index, managed, inherited, optional ); + } + + public static void filterTerminalParents( final Collection> rels ) + { + for (final Iterator> it = rels.iterator(); it.hasNext(); ) + { + final ProjectRelationship rel = it.next(); + if ( ( rel instanceof SimpleParentRelationship ) && ( (ParentRelationship) rel ).isTerminus() ) + { + it.remove(); + } + } + } + + public static URI profileLocation( final String profile ) + { + if ( profile == null || profile.trim() + .length() < 1 ) + { + return POM_ROOT_URI; + } + + try + { + return new URI( "pom:profile:" + profile ); + } + catch ( final URISyntaxException e ) + { + throw new IllegalStateException( "Cannot construct pom-profile URI: 'pom:profile:" + profile + "'" ); + } + } +} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/AbstractRelationshipGraphListener.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/AbstractRelationshipGraphListener.java deleted file mode 100644 index ed3e1e8e..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/AbstractRelationshipGraphListener.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.commonjava.maven.atlas.graph; - -import java.util.Collection; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public abstract class AbstractRelationshipGraphListener - implements RelationshipGraphListener -{ - - protected AbstractRelationshipGraphListener() - { - } - - @Override - public abstract int hashCode(); - - @Override - public abstract boolean equals( Object other ); - - @Override - public void storing( final RelationshipGraph graph, final Collection> relationships ) - throws RelationshipGraphException - { - // NOP - } - - @Override - public void stored( final RelationshipGraph graph, - final Collection> relationships, - final Collection> rejected ) - throws RelationshipGraphException - { - // NOP - } - - @Override - public void projectError( final RelationshipGraph graph, final ProjectVersionRef ref, - final Throwable error ) - throws RelationshipGraphException - { - // NOP - } - - @Override - public void closing( final RelationshipGraph graph ) - throws RelationshipGraphException - { - // NOP - } - - @Override - public void closed( final RelationshipGraph graph ) - throws RelationshipGraphException - { - // NOP - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraph.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraph.java deleted file mode 100644 index 9081bdf1..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraph.java +++ /dev/null @@ -1,681 +0,0 @@ -package org.commonjava.maven.atlas.graph; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.model.EProjectDirectRelationships; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.mutate.GraphMutator; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.traverse.RelationshipGraphTraversal; -import org.commonjava.maven.atlas.graph.traverse.TraversalType; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public final class RelationshipGraph -{ - - private static final String GROUP_ID = "groupId"; - - private static final String ARTIFACT_ID = "artifactId"; - - private static final String VERSION = "version"; - - private List listeners; - - private final ViewParams params; - - private RelationshipGraphConnection connection; - - RelationshipGraph( final ViewParams params, final RelationshipGraphConnection driver ) - { - this.params = params; - this.connection = driver; - } - - public ViewParams getParams() - { - return params; - } - - public void storeProjectError( final ProjectVersionRef ref, final Throwable error ) - throws RelationshipGraphException - { - connection.addProjectError( ref, error ); - - for ( final RelationshipGraphListener listener : listeners ) - { - listener.projectError( this, ref, error ); - } - } - - public Throwable getProjectError( final ProjectVersionRef ref ) - { - return connection.getProjectError( ref ); - } - - public boolean hasProjectError( final ProjectVersionRef ref ) - { - return connection.hasProjectError( ref ); - } - - public void clearProjectError( final ProjectVersionRef ref ) - throws RelationshipGraphException - { - connection.clearProjectError( ref ); - } - - public Set> storeRelationships( final ProjectRelationship... relationships ) - throws RelationshipGraphException - { - final List> rels = Arrays.asList( relationships ); - - for ( final RelationshipGraphListener listener : listeners ) - { - listener.storing( this, rels ); - } - - final Set> rejected = connection.addRelationships( relationships ); - - for ( final RelationshipGraphListener listener : listeners ) - { - listener.stored( this, rels, rejected ); - } - - return rejected; - } - - public Set> storeRelationships( final Collection> relationships ) - throws RelationshipGraphException - { - for ( final RelationshipGraphListener listener : listeners ) - { - listener.storing( this, relationships ); - } - - final Set> rejected = - connection.addRelationships( relationships.toArray( new ProjectRelationship[relationships.size()] ) ); - - for ( final RelationshipGraphListener listener : listeners ) - { - listener.stored( this, relationships, rejected ); - } - - return rejected; - } - - public void addListener( final RelationshipGraphListener listener ) - { - if ( listeners == null ) - { - listeners = new ArrayList(); - } - - listeners.add( listener ); - } - - public void removeListener( final RelationshipGraphListener listener ) - { - if ( listeners != null ) - { - listeners.remove( listener ); - } - } - - public void close() - throws RelationshipGraphException - { - if ( listeners != null ) - { - for ( final RelationshipGraphListener listener : listeners ) - { - listener.closing( this ); - } - } - - connection = null; - - if ( listeners != null ) - { - for ( final RelationshipGraphListener listener : listeners ) - { - listener.closed( this ); - } - } - - // try - // { - // connection.close(); - // } - // finally - // { - // if ( listeners != null ) - // { - // for ( final RelationshipGraphListener listener : listeners ) - // { - // listener.closed( this ); - // } - // } - // } - } - - // +++ IMPORTED FROM EProjectWeb... - - public Set> getAllRelationships() - { - return new HashSet>( connection.getAllRelationships( params ) ); - } - - public boolean isComplete() - { - return !connection.hasMissingProjects( params ); - } - - public boolean isConcrete() - { - return !connection.hasVariableProjects( params ); - } - - public Set getIncompleteSubgraphs() - { - return Collections.unmodifiableSet( connection.getMissingProjects( params ) ); - } - - public Set getVariableSubgraphs() - { - return Collections.unmodifiableSet( connection.getVariableProjects( params ) ); - } - - public Set> add( final EProjectDirectRelationships rels ) - throws RelationshipGraphException - { - return addAll( rels.getAllRelationships() ); - } - - public boolean add( final ProjectRelationship rel ) - throws RelationshipGraphException - { - if ( rel == null ) - { - return false; - } - - return connection.addRelationships( rel ) - .isEmpty(); - } - - public > Set addAll( final Collection rels ) - throws RelationshipGraphException - { - if ( rels == null ) - { - return null; - } - - final Set result = new HashSet( rels ); - - final Set> rejected = - connection.addRelationships( rels.toArray( new ProjectRelationship[] {} ) ); - result.removeAll( rejected ); - - if ( !result.isEmpty() ) - { - connection.recomputeIncompleteSubgraphs(); - } - - return result; - } - - public > Set addAll( final T... rels ) - throws RelationshipGraphException - { - if ( rels == null ) - { - return null; - } - - final Set result = new HashSet(); - for ( final T rel : rels ) - { - if ( add( rel ) ) - { - result.add( rel ); - } - } - - connection.recomputeIncompleteSubgraphs(); - - return result; - } - - public void traverse( final ProjectVersionRef start, final RelationshipGraphTraversal traversal, - final TraversalType type ) - throws RelationshipGraphException - { - connection.traverse( traversal, start, this, type ); - } - - public void traverse( final ProjectVersionRef start, final RelationshipGraphTraversal traversal ) - throws RelationshipGraphException - { - traverse( start, traversal, TraversalType.breadth_first ); - } - - public void traverse( final RelationshipGraphTraversal traversal, final TraversalType type ) - throws RelationshipGraphException - { - for ( final ProjectVersionRef root : params.getRoots() ) - { - connection.traverse( traversal, root, this, type ); - } - } - - public void traverse( final RelationshipGraphTraversal traversal ) - throws RelationshipGraphException - { - traverse( traversal, TraversalType.breadth_first ); - } - - public Set> getUserRelationships( final ProjectVersionRef ref ) - { - if ( !connection.containsProject( params, ref ) ) - { - return Collections.emptySet(); - } - - return new HashSet>( connection.getRelationshipsTargeting( params, ref ) ); - } - - public Set> getDirectRelationships( final ProjectVersionRef ref ) - { - if ( !connection.containsProject( params, ref ) ) - { - return Collections.emptySet(); - } - - return new HashSet>( connection.getRelationshipsDeclaredBy( params, ref ) ); - } - - public Set getRoots() - { - return params.getRoots(); - } - - public Set> getExactAllRelationships() - { - return getAllRelationships(); - } - - public boolean isCycleParticipant( final ProjectVersionRef ref ) - { - return connection.isCycleParticipant( params, ref ); - } - - public boolean isCycleParticipant( final ProjectRelationship rel ) - { - return connection.isCycleParticipant( params, rel ); - } - - public void addCycle( final EProjectCycle cycle ) - throws RelationshipGraphException - { - connection.addCycle( cycle ); - } - - public Set getCycles() - { - return connection.getCycles( params ); - } - - public Set> getRelationshipsTargeting( final ProjectVersionRef ref ) - { - final Collection> rels = - connection.getRelationshipsTargeting( params, ref.asProjectVersionRef() ); - if ( rels == null ) - { - return Collections.emptySet(); - } - - return new HashSet>( rels ); - } - - public RelationshipGraphConnection getDatabase() - { - return connection; - } - - public Set getAllProjects() - { - return connection.getAllProjects( params ); - } - - public void addMetadata( final ProjectVersionRef ref, final String name, final String value ) - throws RelationshipGraphException - { - connection.addMetadata( ref, name, value ); - } - - public void addMetadata( final ProjectVersionRef ref, final Map metadata ) - throws RelationshipGraphException - { - connection.setMetadata( ref, metadata ); - } - - public Set getProjectsWithMetadata( final String key ) - { - return connection.getProjectsWithMetadata( params, key ); - } - - public void reindex() - throws RelationshipGraphException - { - connection.reindex(); - } - - public void reindex( final ProjectVersionRef ref ) - throws RelationshipGraphConnectionException - { - connection.reindex( ref ); - } - - public Set>> getPathsTo( final ProjectVersionRef... projectVersionRefs ) - { - return connection.getAllPathsTo( params, projectVersionRefs ); - } - - public boolean introducesCycle( final ProjectRelationship rel ) - { - return connection.introducesCycle( params, rel ); - } - - public void addDisconnectedProject( final ProjectVersionRef ref ) - throws RelationshipGraphException - { - connection.addDisconnectedProject( ref ); - } - - public boolean isMissing( final ProjectVersionRef ref ) - { - return connection.isMissing( params, ref ); - } - - public Set getSources() - { - return params.getActiveSources(); - // final Set> rels = getAllRelationships(); - // final Set sources = new HashSet(); - // for ( final ProjectRelationship rel : rels ) - // { - // sources.addAll( rel.getSources() ); - // } - // - // return sources; - } - - public GraphMutator getMutator() - { - return params.getMutator(); - } - - public ProjectRelationshipFilter getFilter() - { - return params.getFilter(); - } - - public ViewParams addActivePomLocation( final URI location ) - { - return params.addActivePomLocation( location ); - } - - public ViewParams addActivePomLocations( final Collection locations ) - { - return params.addActivePomLocations( locations ); - } - - public ViewParams addActivePomLocations( final URI... locations ) - { - return params.addActivePomLocations( locations ); - } - - public ViewParams addActiveSources( final Collection sources ) - { - return params.addActiveSources( sources ); - } - - public ViewParams addActiveSources( final URI... sources ) - { - return params.addActiveSources( sources ); - } - - public ViewParams addActiveSource( final URI source ) - { - return params.addActiveSource( source ); - } - - public long getLastAccess() - { - return params.getLastAccess(); - } - - public String setProperty( final String key, final String value ) - { - return params.setProperty( key, value ); - } - - public String getProperty( final String key ) - { - return params.getProperty( key ); - } - - public String getProperty( final String key, final String def ) - { - return params.getProperty( key, def ); - } - - public final String getWorkspaceId() - { - return params.getWorkspaceId(); - } - - public final Set getActivePomLocations() - { - return params.getActivePomLocations(); - } - - public final Set getActiveSources() - { - return params.getActiveSources(); - } - - public final ProjectVersionRef getSelection( final ProjectRef ref ) - { - return params.getSelection( ref ); - } - - // --- IMPORTED FROM EProjectWeb - - // +++ IMPORTED FROM EGraphManager - public boolean containsGraph( final ProjectVersionRef ref ) - { - return connection.containsProject( params, ref ) && !connection.isMissing( params, ref ); - } - - public Set> findDirectRelationshipsTo( final ProjectVersionRef to, - final boolean includeManagedInfo, - final RelationshipType... types ) - { - return connection.getDirectRelationshipsTo( params, to, includeManagedInfo, true, types ); - } - - public Set> findDirectRelationshipsFrom( final ProjectVersionRef source, - final boolean managed, - final RelationshipType... types ) - { - return connection.getDirectRelationshipsFrom( params, source, managed, true, types ); - } - - public Set getAllIncompleteSubgraphs() - { - return connection.getMissingProjects( params ); - } - - public Set getAllVariableSubgraphs() - { - return connection.getVariableProjects( params ); - } - - public Map getMetadata( final ProjectVersionRef ref ) - { - final Map result = new HashMap(); - final Map metadata = connection.getMetadata( ref ); - if ( metadata != null ) - { - result.putAll( metadata ); - } - - result.put( GROUP_ID, ref.getGroupId() ); - result.put( ARTIFACT_ID, ref.getArtifactId() ); - result.put( VERSION, ref.getVersionString() ); - - return result; - } - - public Map getMetadata( final ProjectVersionRef ref, final Set keys ) - { - final Map result = new HashMap(); - final Map metadata = connection.getMetadata( ref, keys ); - if ( metadata != null ) - { - result.putAll( metadata ); - } - - if ( keys.contains( GROUP_ID ) ) - { - result.put( GROUP_ID, ref.getGroupId() ); - } - - if ( keys.contains( ARTIFACT_ID ) ) - { - result.put( ARTIFACT_ID, ref.getArtifactId() ); - } - - if ( keys.contains( VERSION ) ) - { - result.put( VERSION, ref.getVersionString() ); - } - - return result; - } - - public Map, Set> collateByMetadata( final Set refs, - final Set keys ) - { - final Map, Set> result = - new HashMap, Set>(); - for ( final ProjectVersionRef ref : refs ) - { - final Map metadata = getMetadata( ref, keys ); - Set collated = result.get( metadata ); - if ( collated == null ) - { - collated = new HashSet(); - result.put( metadata, collated ); - } - - collated.add( ref ); - } - - return result; - } - - public void setMetadata( final ProjectVersionRef project, final Map metadata ) - throws RelationshipGraphException - { - connection.setMetadata( project, metadata ); - } - - public void deleteRelationshipsDeclaredBy( final ProjectVersionRef ref ) - throws RelationshipGraphException - { - connection.deleteRelationshipsDeclaredBy( ref ); - } - - public Set getProjectsMatching( final ProjectRef projectRef ) - { - return connection.getProjectsMatching( params, projectRef ); - } - - public Map, GraphPathInfo> getPathMapTargeting( final Set refs ) - { - return connection.getPathMapTargeting( params, refs ); - } - - public ProjectVersionRef getPathTargetRef( final GraphPath path ) - { - return connection.getPathTargetRef( path ); - } - - public GraphPath createPath( final GraphPath parentPath, final ProjectRelationship relationship ) - { - return connection.createPath( parentPath, relationship ); - } - - public GraphPath createPath( final ProjectRelationship... relationships ) - { - return connection.createPath( relationships ); - } - - public List getPathRefs( final GraphPath path ) - { - return connection.getPathRefs( params, path ); - } - - RelationshipGraphConnection getConnection() - { - return connection; - } - - // --- IMPORTED FROM EGraphManager - - @Override - public String toString() - { - return "RelationshipGraph [params=" + params + "]"; - } - - public void printStats() - { - connection.printStats(); - } - - public Map getAllProjectErrors() - { - final Map errors = new HashMap(); - final Set projects = connection.getAllProjects( params ); - for ( final ProjectVersionRef ref : projects ) - { - final Throwable error = connection.getProjectError( ref ); - if ( error != null ) - { - errors.put( ref, error ); - } - } - - return errors; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphException.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphException.java deleted file mode 100644 index f4f4020e..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphException.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph; - -import java.util.IllegalFormatException; - -public class RelationshipGraphException - extends Exception -{ - - private static final long serialVersionUID = 1L; - - private final Object[] params; - - public RelationshipGraphException( final String message, final Throwable error, final Object... params ) - { - super( message, error ); - this.params = params; - } - - public RelationshipGraphException( final String message, final Object... params ) - { - super( message ); - this.params = params; - } - - @Override - public String getLocalizedMessage() - { - return getMessage(); - } - - @Override - public String getMessage() - { - String message = super.getMessage(); - if ( params != null && params.length > 0 ) - { - try - { - final String formatted = String.format( message, params ); - message = formatted; - } - catch ( final IllegalFormatException e ) - { - } - } - - return message; - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphFactory.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphFactory.java deleted file mode 100644 index 32f83c91..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphFactory.java +++ /dev/null @@ -1,211 +0,0 @@ -package org.commonjava.maven.atlas.graph; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; - -public final class RelationshipGraphFactory -{ - - private final RelationshipGraphConnectionFactory connectionManager; - - private final Map connectionCaches = new HashMap(); - - private final Set listenerFactories = - new HashSet(); - - private boolean closed; - - public RelationshipGraphFactory( final RelationshipGraphConnectionFactory connectionFactory, - final RelationshipGraphListenerFactory... listenerFactories ) - { - this.connectionManager = connectionFactory; - if ( listenerFactories.length > 0 ) - { - this.listenerFactories.addAll( Arrays.asList( listenerFactories ) ); - } - } - - public RelationshipGraph open( final ViewParams params, final boolean create ) - throws RelationshipGraphException - { - checkClosed(); - - final String wsid = params.getWorkspaceId(); - ConnectionCache cache = connectionCaches.get( wsid ); - if ( cache == null ) - { - if ( !create ) - { - throw new RelationshipGraphException( "No such workspace: %s", wsid ); - } - - final RelationshipGraphConnection connection = - connectionManager.openConnection( params.getWorkspaceId(), create ); - - cache = new ConnectionCache( connection ); - connectionCaches.put( wsid, cache ); - } - - RelationshipGraph graph = cache.getGraph( params ); - - if ( graph == null ) - { - graph = new RelationshipGraph( params, cache.getConnection() ); - graph.addListener( cache ); - cache.registerGraph( params, graph ); - } - - return graph; - } - - public Set listWorkspaces() - { - return connectionManager.listWorkspaces(); - } - - public void store( final RelationshipGraph graph ) - throws RelationshipGraphException - { - checkClosed(); - connectionManager.flush( graph.getConnection() ); - } - - public boolean deleteWorkspace( final String workspaceId ) - throws RelationshipGraphException - { - checkClosed(); - return connectionManager.delete( workspaceId ); - } - - private void checkClosed() - throws RelationshipGraphException - { - if ( closed ) - { - throw new RelationshipGraphException( "Graph factory is closed!" ); - } - } - - public void close() - throws RelationshipGraphException - { - closed = true; - - for ( final ConnectionCache cache : connectionCaches.values() ) - { - cache.close(); - } - - connectionCaches.clear(); - - connectionManager.close(); - } - - public boolean workspaceExists( final String workspaceId ) - { - return connectionManager.exists( workspaceId ); - } - - private static final class ConnectionCache - extends AbstractRelationshipGraphListener - implements Iterable - { - private final RelationshipGraphConnection connection; - - private final Map graphs = new HashMap(); - - ConnectionCache( final RelationshipGraphConnection connection ) - { - this.connection = connection; - } - - public void close() - throws RelationshipGraphException - { - graphs.clear(); - connection.close(); - } - - RelationshipGraph getGraph( final ViewParams params ) - { - return graphs.get( params ); - } - - RelationshipGraphConnection getConnection() - { - return connection; - } - - void registerGraph( final ViewParams params, final RelationshipGraph graph ) - { - graphs.put( params, graph ); - } - - void deregisterGraph( final ViewParams params ) - { - graphs.remove( params ); - } - - boolean isEmpty() - { - return graphs.isEmpty(); - } - - @Override - public Iterator iterator() - { - return graphs.values() - .iterator(); - } - - @Override - public void closed( final RelationshipGraph graph ) - throws RelationshipGraphException - { - // TODO: It'd be nice to be able to flush to disk without wrecking the connection for all other views on the - // same workspace... - - // factory.flush( cache.getConnection() ); - deregisterGraph( graph.getParams() ); - if ( isEmpty() ) - { - close(); - } - } - - @Override - public int hashCode() - { - return connection.getWorkspaceId() - .hashCode() + 13; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final ConnectionCache other = (ConnectionCache) obj; - return connection.getWorkspaceId() - .equals( other.connection.getWorkspaceId() ); - } - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphListener.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphListener.java deleted file mode 100644 index fedf4e6c..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphListener.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.commonjava.maven.atlas.graph; - -import java.util.Collection; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public interface RelationshipGraphListener -{ - - void projectError( RelationshipGraph graph, ProjectVersionRef ref, Throwable error ) - throws RelationshipGraphException; - - void storing( RelationshipGraph graph, Collection> relationships ) - throws RelationshipGraphException; - - void stored( RelationshipGraph graph, Collection> relationships, - Collection> rejected ) - throws RelationshipGraphException; - - void closing( RelationshipGraph graph ) - throws RelationshipGraphException; - - void closed( RelationshipGraph graph ) - throws RelationshipGraphException; - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphListenerFactory.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphListenerFactory.java deleted file mode 100644 index a71ecb8c..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/RelationshipGraphListenerFactory.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.commonjava.maven.atlas.graph; - -public interface RelationshipGraphListenerFactory -{ - - void addListeners( RelationshipGraph graph ); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/ViewParams.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/ViewParams.java deleted file mode 100644 index a6bb0c19..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/ViewParams.java +++ /dev/null @@ -1,551 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph; - -import static org.apache.commons.lang.StringUtils.join; - -import java.io.Serializable; -import java.net.URI; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.commons.codec.digest.DigestUtils; -import org.commonjava.maven.atlas.graph.filter.AnyFilter; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.mutate.GraphMutator; -import org.commonjava.maven.atlas.graph.mutate.ManagedDependencyMutator; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -/** - *

- * View of a graph database that may include a set of traversal root-nodes, - * a {@link ProjectRelationshipFilter}, and a {@link GraphMutator}. This view - * also supports selection of a GAV to override either all references to a GA, or - * references to a specific GAV. - *

- * - *

- * NOTE(1): Selections currently cannot be overridden or - * cleared once set, and root GAVs cannot be overridden with a selection. - *

- * - *

- * NOTE(2): If root nodes are unspecified, then neither filter nor mutator can be used! - *

- * - * @author jdcasey - */ -public class ViewParams - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - private static final Set DEFAULT_SOURCES = - Collections.unmodifiableSet( Collections.singleton( RelationshipUtils.UNKNOWN_SOURCE_URI ) ); - - private static final Set DEFAULT_POM_LOCATIONS = - Collections.unmodifiableSet( Collections.singleton( RelationshipUtils.POM_ROOT_URI ) ); - - private final Set roots = new HashSet(); - - private final ProjectRelationshipFilter filter; - - private final GraphMutator mutator; - - private Set activePomLocations; - - private Set activeSources; - - private long lastAccess = System.currentTimeMillis(); - - private Map properties; - - private final Map selections; - - private transient String longId; - - private transient String shortId; - - private final String workspaceId; - - public ViewParams( final String workspaceId, final ProjectRelationshipFilter filter, final GraphMutator mutator, - final Collection roots ) - { - this( workspaceId, filter, mutator, null, roots ); - } - - public ViewParams( final String workspaceId, final ProjectRelationshipFilter filter, final GraphMutator mutator, - final ProjectVersionRef... roots ) - { - this( workspaceId, filter, mutator, null, roots ); - } - - public ViewParams( final String workspaceId, final Collection roots ) - { - this( workspaceId, null, null, null, roots ); - } - - public ViewParams( final String workspaceId, final ProjectVersionRef... roots ) - { - this( workspaceId, null, null, null, roots ); - } - - public ViewParams( final String workspaceId, final ProjectRelationshipFilter filter, final GraphMutator mutator, - final Map selections, final Collection roots ) - { - this.workspaceId = workspaceId; - this.filter = filter; - this.selections = selections; - this.roots.addAll( roots ); - this.mutator = mutator; - } - - public ViewParams( final String workspaceId, final ProjectRelationshipFilter filter, final GraphMutator mutator, - final Map selections, final ProjectVersionRef... roots ) - { - this.workspaceId = workspaceId; - this.filter = filter; - this.selections = selections; - this.roots.addAll( Arrays.asList( roots ) ); - this.mutator = mutator; - } - - public ViewParams( final String workspaceId, final Map selections, - final Collection roots ) - { - this( workspaceId, null, null, selections, roots ); - } - - public ViewParams( final String workspaceId, final Map selections, - final ProjectVersionRef... roots ) - { - this( workspaceId, null, null, selections, roots ); - } - - public ViewParams( final String workspaceId, final ProjectRelationshipFilter filter, final GraphMutator mutator, - final Set activePomLocations, final Set activeSources, - final Map selections, final Map properties, - final Set roots ) - { - this.workspaceId = workspaceId; - this.filter = filter; - this.mutator = mutator; - this.activePomLocations = activePomLocations; - this.activeSources = activeSources; - this.selections = selections; - this.properties = properties; - this.roots.addAll( roots ); - } - - public GraphMutator getMutator() - { - return mutator == null ? new ManagedDependencyMutator() : mutator; - } - - public ProjectRelationshipFilter getFilter() - { - return filter == null ? AnyFilter.INSTANCE : filter; - } - - public Set getRoots() - { - return roots; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( filter == null ) ? 0 : filter.hashCode() ); - result = prime * result + ( ( roots == null ) ? 0 : roots.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final ViewParams other = (ViewParams) obj; - return getShortId().equals( other.getShortId() ); - } - - @Override - public String toString() - { - return getLongId() + " (shortId: " + getShortId() + ")"; - } - - public String getLongId() - { - if ( longId == null ) - { - final StringBuilder sb = new StringBuilder(); - final String abbreviatedPackage = getClass().getPackage() - .getName() - .replaceAll( "([a-zA-Z])[a-zA-Z]+", "$1" ); - - sb.append( abbreviatedPackage ) - .append( '.' ) - .append( getClass().getSimpleName() ) - .append( "(roots:" ) - .append( join( roots, "," ) ) - .append( ",filter:" ) - .append( filter == null ? "none" : filter.getLongId() ) - .append( ",mutator:" ) - .append( mutator == null ? "none" : mutator.getLongId() ) - .append( ",selections:\n " ) - .append( renderSelections() ); - - sb.append( ")" ); - - longId = sb.toString(); - } - - return longId; - } - - public String getShortId() - { - if ( shortId == null ) - { - shortId = DigestUtils.shaHex( getLongId() ); - } - - return shortId; - } - - public void touch() - { - lastAccess = System.currentTimeMillis(); - } - - public ViewParams addActivePomLocation( final URI location ) - { - if ( activePomLocations == null ) - { - activePomLocations = new HashSet(); - } - - activePomLocations.add( location ); - return this; - } - - public ViewParams addActivePomLocations( final Collection locations ) - { - if ( activePomLocations == null ) - { - activePomLocations = new HashSet(); - } - - activePomLocations.addAll( locations ); - return this; - } - - public ViewParams addActivePomLocations( final URI... locations ) - { - if ( activePomLocations == null ) - { - activePomLocations = new HashSet(); - } - - activePomLocations.addAll( Arrays.asList( locations ) ); - return this; - } - - public ViewParams addActiveSources( final Collection sources ) - { - if ( activeSources == null ) - { - activeSources = new HashSet(); - } - - activeSources.addAll( sources ); - return this; - } - - public ViewParams addActiveSources( final URI... sources ) - { - if ( activeSources == null ) - { - activeSources = new HashSet(); - } - - activeSources.addAll( Arrays.asList( sources ) ); - return this; - } - - public ViewParams addActiveSource( final URI source ) - { - if ( activeSources == null ) - { - activeSources = new HashSet(); - } - - activeSources.add( source ); - return this; - } - - public long getLastAccess() - { - return lastAccess; - } - - public String setProperty( final String key, final String value ) - { - if ( properties == null ) - { - properties = new HashMap(); - } - - return properties.put( key, value ); - } - - public String removeProperty( final String key ) - { - return properties == null ? null : properties.remove( key ); - } - - public String getProperty( final String key ) - { - return properties == null ? null : properties.get( key ); - } - - public String getProperty( final String key, final String def ) - { - final String val = properties == null ? null : properties.get( key ); - return val == null ? def : val; - } - - public final String getWorkspaceId() - { - return workspaceId; - } - - public final Set getActivePomLocations() - { - return activePomLocations == null ? DEFAULT_POM_LOCATIONS : activePomLocations; - } - - public final Set getActiveSources() - { - return activeSources == null ? DEFAULT_SOURCES : activeSources; - } - - public final Iterable activePomLocations() - { - return activePomLocations; - } - - public final Iterable activeSources() - { - return activeSources; - } - - public final ProjectVersionRef getSelection( final ProjectRef ref ) - { - if ( selections == null ) - { - return null; - } - - ProjectVersionRef selected = selections.get( ref ); - if ( selected == null ) - { - selected = selections.get( ref.asProjectRef() ); - } - - return selected; - } - - public boolean hasSelection( final ProjectVersionRef ref ) - { - return selections == null ? false : selections.containsKey( ref ) - || selections.containsKey( ref.asProjectRef() ); - } - - public String renderSelections() - { - if ( selections == null ) - { - return ""; - } - - final StringBuilder sb = new StringBuilder(); - for ( final Entry entry : selections.entrySet() ) - { - final ProjectRef key = entry.getKey(); - final ProjectVersionRef value = entry.getValue(); - - sb.append( "\n " ) - .append( key ) - .append( " => " ) - .append( value ); - } - - return sb.toString(); - } - - public boolean hasSelections() - { - return selections != null && !selections.isEmpty(); - } - - public static final class Builder - { - private final Set roots; - - private ProjectRelationshipFilter filter; - - private GraphMutator mutator; - - private final Set activePomLocations; - - private final Set activeSources; - - private final Map properties; - - private final Map selections; - - private final String workspaceId; - - public Builder( final String workspaceId, final ProjectVersionRef... roots ) - { - this.workspaceId = workspaceId; - this.roots = new HashSet( Arrays.asList( roots ) ); - this.activePomLocations = new HashSet(); - this.activeSources = new HashSet(); - this.properties = new HashMap(); - this.selections = new HashMap(); - this.filter = AnyFilter.INSTANCE; - this.mutator = new ManagedDependencyMutator(); - } - - public Builder( final String workspaceId, final Collection roots ) - { - this.workspaceId = workspaceId; - this.roots = new HashSet( roots ); - this.activePomLocations = new HashSet(); - this.activeSources = new HashSet(); - this.properties = new HashMap(); - this.selections = new HashMap(); - this.filter = AnyFilter.INSTANCE; - this.mutator = new ManagedDependencyMutator(); - } - - public Builder( final ViewParams params ) - { - this.workspaceId = params.getWorkspaceId(); - this.roots = - params.roots == null ? new HashSet() : new HashSet( params.roots ); - this.filter = params.filter; - this.mutator = params.mutator; - this.activePomLocations = - params.activePomLocations == null ? new HashSet() : new HashSet( params.activePomLocations ); - this.activeSources = - params.activeSources == null ? new HashSet() : new HashSet( params.activeSources ); - this.properties = - params.properties == null ? new HashMap() - : new HashMap( params.properties ); - this.selections = - params.selections == null ? new HashMap() - : new HashMap( params.selections ); - } - - public Builder withRoots( final ProjectVersionRef... roots ) - { - this.roots.clear(); - this.roots.addAll( Arrays.asList( roots ) ); - return this; - } - - public Builder withFilter( final ProjectRelationshipFilter filter ) - { - this.filter = filter; - return this; - } - - public Builder withMutator( final GraphMutator mutator ) - { - this.mutator = mutator; - return this; - } - - public Builder withSelections( final Map selections ) - { - this.selections.clear(); - this.selections.putAll( selections ); - return this; - } - - public Builder withProperties( final Map properties ) - { - this.properties.clear(); - this.properties.putAll( properties ); - return this; - } - - public Builder withActivePomLocations( final Set activePomLocations ) - { - this.activePomLocations.clear(); - this.activePomLocations.addAll( activePomLocations ); - return this; - } - - public Builder withActiveSources( final Set activeSources ) - { - this.activeSources.clear(); - this.activeSources.addAll( activeSources ); - return this; - } - - public ViewParams build() - { - return new ViewParams( workspaceId, filter, mutator, activePomLocations, activeSources, selections, - properties, roots ); - } - - public Builder withSelection( final ProjectRef target, final ProjectVersionRef selection ) - { - selections.put( target, selection ); - return this; - } - - public Builder withRoots( final Collection roots ) - { - this.roots.clear(); - this.roots.addAll( roots ); - return this; - } - - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AbstractAggregatingFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AbstractAggregatingFilter.java deleted file mode 100644 index 1a88dc26..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AbstractAggregatingFilter.java +++ /dev/null @@ -1,241 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.codec.digest.DigestUtils; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public abstract class AbstractAggregatingFilter - implements ProjectRelationshipFilter, Iterable -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - private final List filters; - - private transient String longId; - - private transient String shortId; - - protected AbstractAggregatingFilter( final Collection filters ) - { - this.filters = new ArrayList( filters ); - } - - protected AbstractAggregatingFilter( final ProjectRelationshipFilter... filters ) - { - this.filters = new ArrayList( Arrays.asList( filters ) ); - } - - public final List getFilters() - { - return filters; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - final List childFilters = new ArrayList(); - for ( final ProjectRelationshipFilter filter : getFilters() ) - { - // if ( filter.accept( parent ) ) - // { - childFilters.add( filter.getChildFilter( parent ) ); - // } - } - - if ( getFilters().equals( childFilters ) ) - { - return this; - } - - // TODO: Optimize to ensure we're only creating a new instance when it's critical to... - return newChildFilter( childFilters ); - } - - protected abstract AbstractAggregatingFilter newChildFilter( List childFilters ); - - @Override - public Iterator iterator() - { - return new ArrayList( filters ).iterator(); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( filters == null ) ? 0 : filters.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final AbstractAggregatingFilter other = (AbstractAggregatingFilter) obj; - - return filtersEqual( other.filters ); - } - - protected final boolean filtersEqual( final Collection otherFilters ) - { - if ( filters == null ) - { - if ( otherFilters != null ) - { - return false; - } - } - else if ( otherFilters != null ) - { - // if ( orderMatters ) - // { - return filters.equals( otherFilters ); - // } - // else - // { - // for ( final ProjectRelationshipFilter filter : filters ) - // { - // if ( !otherFilters.contains( filter ) ) - // { - // return false; - // } - // } - // - // for ( final ProjectRelationshipFilter filter : otherFilters ) - // { - // if ( !filters.contains( filter ) ) - // { - // return false; - // } - // } - // } - } - - return true; - } - - @Override - public String getLongId() - { - if ( longId == null ) - { - final StringBuilder sb = new StringBuilder(); - final List filters = getFilters(); - final String abbreviatedPackage = getClass().getPackage() - .getName() - .replaceAll( "([a-zA-Z])[a-zA-Z]+", "$1" ); - - sb.append( abbreviatedPackage ) - .append( '.' ) - .append( getClass().getSimpleName() ) - .append( '(' ); - - boolean first = true; - for ( final ProjectRelationshipFilter filter : filters ) - { - if ( !first ) - { - sb.append( ',' ); - } - - first = false; - sb.append( filter.getLongId() ); - } - sb.append( ')' ); - - longId = sb.toString(); - } - - return longId; - } - - @Override - public String toString() - { - return getLongId(); - } - - @Override - public String getCondensedId() - { - if ( shortId == null ) - { - shortId = DigestUtils.shaHex( getLongId() ); - } - - return shortId; - } - - @Override - public boolean includeManagedRelationships() - { - for ( final ProjectRelationshipFilter filter : filters ) - { - if ( filter.includeManagedRelationships() ) - { - return true; - } - } - - return false; - } - - @Override - public boolean includeConcreteRelationships() - { - for ( final ProjectRelationshipFilter filter : filters ) - { - if ( filter.includeConcreteRelationships() ) - { - return true; - } - } - - return false; - } - - @Override - public Set getAllowedTypes() - { - final Set result = new HashSet(); - for ( final ProjectRelationshipFilter filter : filters ) - { - result.addAll( filter.getAllowedTypes() ); - } - - return result; - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AbstractTypedFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AbstractTypedFilter.java deleted file mode 100644 index 6d8d3b0f..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AbstractTypedFilter.java +++ /dev/null @@ -1,309 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import static org.apache.commons.lang.StringUtils.join; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.codec.digest.DigestUtils; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public abstract class AbstractTypedFilter - implements ProjectRelationshipFilter -{ - - // private final Logger logger = new Logger( getClass() ); - - /** - * - */ - private static final long serialVersionUID = 1L; - - private final Set types; - - private final Set descendantTypes; - - private final boolean includeManagedInfo; - - private final boolean includeConcreteInfo; - - private transient String longId; - - private transient String shortId; - - protected AbstractTypedFilter( final RelationshipType type, final RelationshipType descendantType, final boolean includeManagedInfo, - final boolean includeConcreteInfo ) - { - this.types = Collections.unmodifiableSet( Collections.singleton( type ) ); - this.descendantTypes = Collections.unmodifiableSet( Collections.singleton( descendantType ) ); - this.includeManagedInfo = includeManagedInfo; - this.includeConcreteInfo = includeConcreteInfo; - } - - protected AbstractTypedFilter( final RelationshipType type, final Collection descendantTypes, final boolean includeManagedInfo, - final boolean includeConcreteInfo ) - { - if ( type == null ) - { - this.types = Collections.unmodifiableSet( new HashSet( Arrays.asList( RelationshipType.values() ) ) ); - } - else - { - this.types = Collections.unmodifiableSet( Collections.singleton( type ) ); - } - - if ( descendantTypes == null || descendantTypes.isEmpty() ) - { - this.descendantTypes = Collections.unmodifiableSet( new HashSet( Arrays.asList( RelationshipType.values() ) ) ); - } - else - { - this.descendantTypes = Collections.unmodifiableSet( new HashSet( descendantTypes ) ); - } - - this.includeManagedInfo = includeManagedInfo; - this.includeConcreteInfo = includeConcreteInfo; - } - - protected AbstractTypedFilter( final Collection types, final Collection descendantTypes, - final boolean includeManagedInfo, final boolean includeConcreteInfo ) - { - if ( types == null || types.isEmpty() ) - { - this.types = Collections.unmodifiableSet( new HashSet( Arrays.asList( RelationshipType.values() ) ) ); - } - else - { - this.types = Collections.unmodifiableSet( new HashSet( types ) ); - } - - if ( descendantTypes == null || descendantTypes.isEmpty() ) - { - this.descendantTypes = Collections.unmodifiableSet( new HashSet( Arrays.asList( RelationshipType.values() ) ) ); - } - else - { - this.descendantTypes = Collections.unmodifiableSet( new HashSet( descendantTypes ) ); - } - - this.includeManagedInfo = includeManagedInfo; - this.includeConcreteInfo = includeConcreteInfo; - } - - protected AbstractTypedFilter( final RelationshipType type, final boolean hasDescendants, final boolean includeManagedInfo, - final boolean includeConcreteInfo ) - { - if ( type == null ) - { - this.types = Collections.unmodifiableSet( new HashSet( Arrays.asList( RelationshipType.values() ) ) ); - } - else - { - this.types = Collections.unmodifiableSet( Collections.singleton( type ) ); - } - - if ( hasDescendants ) - { - this.descendantTypes = types; - } - else - { - this.descendantTypes = Collections.unmodifiableSet( Collections. emptySet() ); - } - - this.includeManagedInfo = includeManagedInfo; - this.includeConcreteInfo = includeConcreteInfo; - } - - @Override - public final boolean accept( final ProjectRelationship rel ) - { - if ( types.contains( rel.getType() ) ) - { - final boolean accepted = doAccept( rel ); - if ( accepted ) - { - // logger.info( "ACCEPT relationship: %s. Type is in: %s, and was accepted in second-level analysis", rel, - // types ); - } - else - { - // logger.info( "REJECT relationship: %s. Type is in: %s but was rejected by second-level analysis.", rel, - // types ); - } - - return accepted; - } - // else - // { - // logger.info( "REJECT relationship: %s. Type is not in: %s", rel, types ); - // } - - return false; - } - - public Set getRelationshipTypes() - { - return types; - } - - public Set getDescendantRelationshipTypes() - { - return descendantTypes; - } - - protected boolean doAccept( final ProjectRelationship rel ) - { - // base functionality is only to check that the type is appropriate. - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( descendantTypes == null ) ? 0 : descendantTypes.hashCode() ); - result = prime * result + ( includeConcreteInfo ? 1231 : 1237 ); - result = prime * result + ( includeManagedInfo ? 1231 : 1237 ); - result = prime * result + ( ( types == null ) ? 0 : types.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final AbstractTypedFilter other = (AbstractTypedFilter) obj; - if ( descendantTypes == null ) - { - if ( other.descendantTypes != null ) - { - return false; - } - } - else if ( !descendantTypes.equals( other.descendantTypes ) ) - { - return false; - } - if ( includeConcreteInfo != other.includeConcreteInfo ) - { - return false; - } - if ( includeManagedInfo != other.includeManagedInfo ) - { - return false; - } - if ( types == null ) - { - if ( other.types != null ) - { - return false; - } - } - else if ( !types.equals( other.types ) ) - { - return false; - } - return true; - } - - @Override - public String getLongId() - { - if ( longId == null ) - { - final StringBuilder sb = new StringBuilder(); - final String abbreviatedPackage = getClass().getPackage() - .getName() - .replaceAll( "([a-zA-Z])[a-zA-Z]+", "$1" ); - - sb.append( abbreviatedPackage ) - .append( '.' ) - .append( getClass().getSimpleName() ) - .append( "[types:{" ) - .append( join( types, "," ) ) - .append( "}, next-types:{" ) - .append( join( descendantTypes, "," ) ) - .append( "}, concrete:" ) - .append( includeConcreteInfo ) - .append( ", managed:" ) - .append( includeManagedInfo ); - - renderIdAttributes( sb ); - sb.append( ']' ); - - longId = sb.toString(); - } - - return longId; - } - - protected void renderIdAttributes( final StringBuilder sb ) - { - } - - @Override - public String toString() - { - return getLongId(); - } - - @Override - public String getCondensedId() - { - if ( shortId == null ) - { - shortId = DigestUtils.shaHex( getLongId() ); - } - - return shortId; - } - - @Override - public boolean includeManagedRelationships() - { - return includeManagedInfo; - } - - @Override - public boolean includeConcreteRelationships() - { - return includeConcreteInfo; - } - - @Override - public Set getAllowedTypes() - { - final Set result = new HashSet(); - result.addAll( types ); - result.addAll( descendantTypes ); - - return result; - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AndFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AndFilter.java deleted file mode 100644 index 8ded9e4e..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AndFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.Collection; -import java.util.List; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; - -public class AndFilter - extends AbstractAggregatingFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public AndFilter( final Collection filters ) - { - super( filters ); - } - - public AndFilter( final T... filters ) - { - super( filters ); - } - - @Override - public boolean accept( final ProjectRelationship rel ) - { - boolean accepted = true; - for ( final ProjectRelationshipFilter filter : getFilters() ) - { - accepted = accepted && filter.accept( rel ); - if ( !accepted ) - { - break; - } - } - - return accepted; - } - - @Override - protected AbstractAggregatingFilter newChildFilter( final List childFilters ) - { - if ( !filtersEqual( childFilters ) ) - { - return new AndFilter( childFilters ); - } - - return this; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AnyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AnyFilter.java deleted file mode 100644 index 5aafc13b..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/AnyFilter.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public class AnyFilter - implements ProjectRelationshipFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final AnyFilter INSTANCE = new AnyFilter(); - - private AnyFilter() - { - } - - @Override - public boolean accept( final ProjectRelationship rel ) - { - return true; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return this; - } - - @Override - public String getLongId() - { - return "ANY"; - } - - @Override - public String toString() - { - return getLongId(); - } - - @Override - public boolean equals( final Object obj ) - { - return obj instanceof AnyFilter; - } - - @Override - public int hashCode() - { - return AnyFilter.class.hashCode() + 1; - } - - @Override - public String getCondensedId() - { - return getLongId(); - } - - @Override - public boolean includeManagedRelationships() - { - return true; - } - - @Override - public boolean includeConcreteRelationships() - { - return true; - } - - @Override - public Set getAllowedTypes() - { - return new HashSet( Arrays.asList( RelationshipType.values() ) ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/BomFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/BomFilter.java deleted file mode 100644 index ee44f4b8..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/BomFilter.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public class BomFilter - extends AbstractTypedFilter -{ - - private static final long serialVersionUID = 1L; - - public static final BomFilter INSTANCE = new BomFilter(); - - private BomFilter() - { - // BOMs are actually marked as concrete...somewhat counter-intuitive, - // but they're structural, so managed isn't quite correct (despite - // Maven's unfortunate choice for location). - super( RelationshipType.BOM, true, false, true ); - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - return true; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return this; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/DependencyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/DependencyFilter.java deleted file mode 100644 index 6390e741..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/DependencyFilter.java +++ /dev/null @@ -1,226 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ScopeTransitivity; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; - -public class DependencyFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - private final DependencyScope scope; - - private final ScopeTransitivity scopeTransitivity; - - private final Set excludes = new HashSet(); - - private final boolean useImpliedScopes; - - public DependencyFilter() - { - this( DependencyScope.test, ScopeTransitivity.maven, false, true, true, null ); - } - - public DependencyFilter( final DependencyScope scope ) - { - this( scope, ScopeTransitivity.maven, false, true, true, null ); - } - - public DependencyFilter( final DependencyScope scope, final ScopeTransitivity scopeTransitivity, final boolean includeManaged, - final boolean includeConcrete, final Set excludes ) - { - this( scope, scopeTransitivity, includeManaged, includeConcrete, true, excludes ); - } - - public DependencyFilter( final DependencyScope scope, final ScopeTransitivity scopeTransitivity, final boolean includeManaged, - final boolean includeConcrete, final boolean useImpliedScopes, final Set excludes ) - { - super( RelationshipType.DEPENDENCY, true, includeManaged, includeConcrete ); - this.useImpliedScopes = useImpliedScopes; - this.scope = scope == null ? DependencyScope.test : scope; - this.scopeTransitivity = scopeTransitivity; - if ( excludes != null ) - { - for ( final ProjectRef pr : excludes ) - { - this.excludes.add( pr.asProjectRef() ); - } - } - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - final DependencyRelationship dr = (DependencyRelationship) rel; - if ( RelationshipUtils.isExcluded( dr.getTarget(), excludes ) ) - { - return false; - } - - if ( scope != null ) - { - if ( useImpliedScopes && !scope.implies( dr.getScope() ) ) - { - return false; - } - else if ( !useImpliedScopes && scope != dr.getScope() ) - { - return false; - } - } - - if ( !includeManagedRelationships() && dr.isManaged() ) - { - return false; - } - else if ( !includeConcreteRelationships() && !dr.isManaged() ) - { - return false; - } - - return true; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - DependencyRelationship dr = null; - if ( ( parent instanceof DependencyRelationship ) ) - { - dr = (DependencyRelationship) parent; - } - - final DependencyScope nextScope = scopeTransitivity.getChildFor( scope ); - Set newExcludes = dr == null ? null : dr.getExcludes(); - if ( nextScope != scope || ( newExcludes != null && !newExcludes.isEmpty() ) ) - { - if ( excludes != null ) - { - final Set ex = new HashSet( excludes ); - - if ( newExcludes != null && !newExcludes.isEmpty() ) - { - ex.addAll( newExcludes ); - } - - newExcludes = ex; - } - - return new DependencyFilter( nextScope, scopeTransitivity, includeManagedRelationships(), includeConcreteRelationships(), - useImpliedScopes, newExcludes ); - } - - return this; - } - - public boolean isUseImpliedScopes() - { - return useImpliedScopes; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( ( excludes == null ) ? 0 : excludes.hashCode() ); - result = prime * result + ( ( scope == null ) ? 0 : scope.hashCode() ); - result = prime * result + ( ( scopeTransitivity == null ) ? 0 : scopeTransitivity.hashCode() ); - result = prime * result + ( useImpliedScopes ? 1231 : 1237 ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final DependencyFilter other = (DependencyFilter) obj; - if ( excludes == null ) - { - if ( other.excludes != null ) - { - return false; - } - } - else if ( !excludes.equals( other.excludes ) ) - { - return false; - } - if ( scope != other.scope ) - { - return false; - } - if ( scopeTransitivity != other.scopeTransitivity ) - { - return false; - } - if ( useImpliedScopes != other.useImpliedScopes ) - { - return false; - } - return true; - } - - @Override - protected void renderIdAttributes( final StringBuilder sb ) - { - sb.append( ", scope:" ); - sb.append( scope.realName() ); - sb.append( ", transitivity:" ) - .append( scopeTransitivity.name() ); - sb.append( ", implied-scopes:" ) - .append( isUseImpliedScopes() ); - - if ( excludes != null && !excludes.isEmpty() ) - { - sb.append( ", excludes:{" ); - boolean first = true; - for ( final ProjectRef exclude : excludes ) - { - if ( !first ) - { - sb.append( ',' ); - } - - first = false; - sb.append( exclude ); - } - - sb.append( "}" ); - } - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/DependencyOnlyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/DependencyOnlyFilter.java deleted file mode 100644 index 8054a20c..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/DependencyOnlyFilter.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import static org.apache.commons.lang.StringUtils.join; - -import java.util.Arrays; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.DependencyScope; - -public class DependencyOnlyFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - // if unspecified, include all dependencies. - private final DependencyScope[] scopes; - - private final boolean useImpliedScope; - - public DependencyOnlyFilter() - { - this( false, true, true, DependencyScope.test ); - } - - public DependencyOnlyFilter( final DependencyScope... scopes ) - { - this( false, true, true, scopes ); - } - - public DependencyOnlyFilter( final boolean includeManaged, final boolean includeConcrete, final boolean useImpliedScope, - final DependencyScope... scopes ) - { - super( RelationshipType.DEPENDENCY, false, includeManaged, includeConcrete ); - - this.scopes = scopes; - this.useImpliedScope = useImpliedScope; - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - if ( this.scopes == null || this.scopes.length < 1 ) - { - return true; - } - - final DependencyRelationship dr = (DependencyRelationship) rel; - final DependencyScope scope = dr.getScope(); - for ( final DependencyScope s : this.scopes ) - { - if ( scope == s || ( useImpliedScope && s.implies( scope ) ) ) - { - if ( ( dr.isManaged() && includeManagedRelationships() ) || ( !dr.isManaged() && includeConcreteRelationships() ) ) - { - return true; - } - } - } - - return false; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return NoneFilter.INSTANCE; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode( scopes ); - result = prime * result + ( useImpliedScope ? 1231 : 1237 ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final DependencyOnlyFilter other = (DependencyOnlyFilter) obj; - if ( !Arrays.equals( scopes, other.scopes ) ) - { - return false; - } - if ( useImpliedScope != other.useImpliedScope ) - { - return false; - } - return true; - } - - @Override - protected void renderIdAttributes( final StringBuilder sb ) - { - sb.append( ",scopes:{" ) - .append( join( scopes, "," ) ) - .append( ",implied-scopes: " ) - .append( useImpliedScope ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ExtensionFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ExtensionFilter.java deleted file mode 100644 index bd1d3de2..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ExtensionFilter.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.ExtensionRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.DependencyScope; - -// TODO: Do we need to consider excludes in the extensions? -public class ExtensionFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public ExtensionFilter() - { - super( RelationshipType.EXTENSION, RelationshipType.DEPENDENCY, false, true ); - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - if ( parent instanceof ExtensionRelationship ) - { - return new OrFilter( new DependencyFilter( DependencyScope.runtime ), ParentFilter.EXCLUDE_TERMINAL_PARENTS ); - } - else - { - return NoneFilter.INSTANCE; - } - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ExtensionOnlyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ExtensionOnlyFilter.java deleted file mode 100644 index 99464254..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ExtensionOnlyFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public class ExtensionOnlyFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public ExtensionOnlyFilter() - { - super( RelationshipType.EXTENSION, false, false, true ); - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return NoneFilter.INSTANCE; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/NoneFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/NoneFilter.java deleted file mode 100644 index f4df52ec..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/NoneFilter.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.Collections; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public class NoneFilter - implements ProjectRelationshipFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final NoneFilter INSTANCE = new NoneFilter(); - - private NoneFilter() - { - } - - @Override - public boolean accept( final ProjectRelationship rel ) - { - return false; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return this; - } - - @Override - public String getLongId() - { - return "NONE"; - } - - @Override - public String toString() - { - return getLongId(); - } - - @Override - public boolean equals( final Object obj ) - { - return obj instanceof NoneFilter; - } - - @Override - public int hashCode() - { - return NoneFilter.class.hashCode() + 1; - } - - @Override - public String getCondensedId() - { - return getLongId(); - } - - @Override - public boolean includeManagedRelationships() - { - return false; - } - - @Override - public boolean includeConcreteRelationships() - { - return false; - } - - @Override - public Set getAllowedTypes() - { - return Collections.emptySet(); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/OrFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/OrFilter.java deleted file mode 100644 index 5a8d096c..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/OrFilter.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.Collection; -import java.util.List; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; - -public class OrFilter - extends AbstractAggregatingFilter -{ - - // private final Logger logger = new Logger( getClass() ); - - /** - * - */ - private static final long serialVersionUID = 1L; - - public OrFilter( final Collection filters ) - { - super( filters ); - } - - public OrFilter( final T... filters ) - { - super( filters ); - } - - @Override - public boolean accept( final ProjectRelationship rel ) - { - boolean accepted = false; - for ( final ProjectRelationshipFilter filter : getFilters() ) - { - accepted = accepted || filter.accept( rel ); - if ( accepted ) - { - // logger.info( "ACCEPTed: %s, by sub-filter: %s", rel, filter ); - break; - } - } - - return accepted; - } - - @Override - protected AbstractAggregatingFilter newChildFilter( final List childFilters ) - { - if ( !filtersEqual( childFilters ) ) - { - return new OrFilter( childFilters ); - } - - return this; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ParentFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ParentFilter.java deleted file mode 100644 index 0bc8c5e0..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ParentFilter.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public class ParentFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final ParentFilter EXCLUDE_TERMINAL_PARENTS = new ParentFilter( false ); - - public static final ParentFilter INCLUDE_TERMINAL_PARENTS = new ParentFilter( true ); - - private final boolean allowTerminalParent; - - private ParentFilter( final boolean allowTerminalParent ) - { - super( RelationshipType.PARENT, true, false, true ); - this.allowTerminalParent = allowTerminalParent; - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - if ( allowTerminalParent || !( (ParentRelationship) rel ).isTerminus() ) - { - return true; - } - - return false; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return this; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( allowTerminalParent ? 1231 : 1237 ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final ParentFilter other = (ParentFilter) obj; - if ( allowTerminalParent != other.allowTerminalParent ) - { - return false; - } - return true; - } - - @Override - protected void renderIdAttributes( final StringBuilder sb ) - { - sb.append( ",terminalParent:" ) - .append( allowTerminalParent ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginDependencyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginDependencyFilter.java deleted file mode 100644 index d5f9e020..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginDependencyFilter.java +++ /dev/null @@ -1,126 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.PluginDependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; - -// TODO: Do we need to consider excludes in the direct plugin-level dependency? -public class PluginDependencyFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - private final ProjectRef plugin; - - public PluginDependencyFilter( final PluginRelationship plugin ) - { - this( plugin, false, true ); - } - - public PluginDependencyFilter( final PluginRelationship plugin, final boolean includeManaged, final boolean includeConcrete ) - { - super( RelationshipType.PLUGIN_DEP, RelationshipType.DEPENDENCY, includeManaged, includeConcrete ); - - this.plugin = plugin == null ? null : plugin.getTarget() - .asProjectRef(); - } - - public PluginDependencyFilter() - { - this( null, false, true ); - } - - public PluginDependencyFilter( final boolean includeManaged, final boolean includeConcrete ) - { - this( null, includeManaged, includeConcrete ); - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - final PluginDependencyRelationship pdr = (PluginDependencyRelationship) rel; - if ( plugin == null || plugin.equals( pdr.getPlugin() ) ) - { - if ( includeManagedRelationships() && pdr.isManaged() ) - { - return true; - } - else if ( includeConcreteRelationships() && !pdr.isManaged() ) - { - return true; - } - } - - return false; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return new DependencyFilter( DependencyScope.runtime ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( ( plugin == null ) ? 0 : plugin.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final PluginDependencyFilter other = (PluginDependencyFilter) obj; - if ( plugin == null ) - { - if ( other.plugin != null ) - { - return false; - } - } - else if ( !plugin.equals( other.plugin ) ) - { - return false; - } - return true; - } - - @Override - protected void renderIdAttributes( final StringBuilder sb ) - { - sb.append( ",plugin:" ) - .append( plugin ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginDependencyOnlyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginDependencyOnlyFilter.java deleted file mode 100644 index f991ceee..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginDependencyOnlyFilter.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.PluginDependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; - -public class PluginDependencyOnlyFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - private final ProjectRef plugin; - - public PluginDependencyOnlyFilter( final PluginRelationship plugin ) - { - this( plugin, false, true ); - } - - public PluginDependencyOnlyFilter( final PluginRelationship plugin, final boolean includeManaged, final boolean includeConcrete ) - { - super( RelationshipType.PLUGIN_DEP, false, includeManaged, includeConcrete ); - - this.plugin = plugin.getTarget() - .asProjectRef(); - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - final PluginDependencyRelationship pdr = (PluginDependencyRelationship) rel; - if ( plugin.equals( pdr.getPlugin() ) ) - { - if ( includeManagedRelationships() && pdr.isManaged() ) - { - return true; - } - else if ( includeConcreteRelationships() && !pdr.isManaged() ) - { - return true; - } - } - - return false; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return NoneFilter.INSTANCE; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( ( plugin == null ) ? 0 : plugin.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final PluginDependencyOnlyFilter other = (PluginDependencyOnlyFilter) obj; - if ( plugin == null ) - { - if ( other.plugin != null ) - { - return false; - } - } - else if ( !plugin.equals( other.plugin ) ) - { - return false; - } - return true; - } - - @Override - protected void renderIdAttributes( final StringBuilder sb ) - { - sb.append( ",plugin:" ) - .append( plugin ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginOnlyFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginOnlyFilter.java deleted file mode 100644 index 3f2aa5ff..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginOnlyFilter.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public class PluginOnlyFilter - extends AbstractTypedFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public PluginOnlyFilter() - { - this( false, true ); - } - - public PluginOnlyFilter( final boolean includeManaged, final boolean includeConcrete ) - { - super( RelationshipType.PLUGIN, false, includeManaged, includeConcrete ); - } - - @Override - public boolean doAccept( final ProjectRelationship rel ) - { - final PluginRelationship pr = (PluginRelationship) rel; - if ( includeManagedRelationships() && pr.isManaged() ) - { - return true; - } - else if ( includeConcreteRelationships() && !pr.isManaged() ) - { - return true; - } - - return false; - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return NoneFilter.INSTANCE; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginRuntimeFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginRuntimeFilter.java deleted file mode 100644 index 1c67140f..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/PluginRuntimeFilter.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.DependencyScope; - -public class PluginRuntimeFilter - implements ProjectRelationshipFilter -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public PluginRuntimeFilter() - { - } - - @Override - public boolean accept( final ProjectRelationship rel ) - { - return ( rel instanceof PluginRelationship ) && !( (PluginRelationship) rel ).isManaged(); - } - - // TODO: Optimize to minimize new instance creation... - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - ProjectRelationshipFilter child; - if ( parent instanceof PluginRelationship ) - { - final PluginRelationship plugin = (PluginRelationship) parent; - - child = - new OrFilter( new DependencyFilter( DependencyScope.runtime ), new PluginDependencyFilter( plugin, true, true ), - ParentFilter.EXCLUDE_TERMINAL_PARENTS ); - } - else - { - child = NoneFilter.INSTANCE; - } - - return child; - } - - @Override - public String getLongId() - { - return "PLUGIN-RUNTIME"; - } - - @Override - public String toString() - { - return getLongId(); - } - - @Override - public String getCondensedId() - { - return getLongId(); - } - - @Override - public boolean includeManagedRelationships() - { - return false; - } - - @Override - public boolean includeConcreteRelationships() - { - return true; - } - - @Override - public Set getAllowedTypes() - { - final Set result = new HashSet(); - result.add( RelationshipType.PLUGIN ); - - // for descendants - result.add( RelationshipType.PARENT ); - result.add( RelationshipType.DEPENDENCY ); - result.add( RelationshipType.PLUGIN_DEP ); - - return result; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ProjectRelationshipFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ProjectRelationshipFilter.java deleted file mode 100644 index 5085b644..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/ProjectRelationshipFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import java.io.Serializable; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -/** - * Filter used to determine which paths in a dependency graph to traverse (or discover). - * The full dependency graph (relation dependency, not just maven-style dependency) - * will be QUITE extensive, so a filter should be used in NEARLY ALL cases. - * - * @author jdcasey - */ -public interface ProjectRelationshipFilter - extends Serializable -{ - - /** - * Determine whether the given relationship should be traversed. - * - * @param rel The relationship in question - * @return true to allow traversal, false otherwise. - */ - boolean accept( ProjectRelationship rel ); - - /** - * Return the filter used to handle the next wave of relationships after the - * given one is traversed. - * - * @param parent The parent relationship for the set of relationships to which - * the return filter from this method will be applied - * - * @return This instance WHENEVER POSSIBLE, but possibly a different filter - * if the relationship demands a shift in logic. - */ - ProjectRelationshipFilter getChildFilter( ProjectRelationship parent ); - - /** - * Retrieve a human-readable string that uniquely identifies the logic in this filter, - * along with any state stored in this instance. - */ - String getLongId(); - - /** - * Retrieve a condensed version of the human-readable identity given in {@link #getLongId()}. - * If the human-readable identity is sufficiently short (eg. "ANY"), then no - * hashing is required. - */ - String getCondensedId(); - - boolean includeManagedRelationships(); - - boolean includeConcreteRelationships(); - - Set getAllowedTypes(); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/StructuralRelationshipsFilter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/StructuralRelationshipsFilter.java deleted file mode 100644 index 417be73c..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/filter/StructuralRelationshipsFilter.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.commonjava.maven.atlas.graph.filter; - -import static org.commonjava.maven.atlas.graph.rel.RelationshipType.BOM; -import static org.commonjava.maven.atlas.graph.rel.RelationshipType.PARENT; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; - -public final class StructuralRelationshipsFilter - extends AbstractTypedFilter -{ - - private static final Collection TYPES = - Collections.unmodifiableCollection( Arrays.asList( PARENT, BOM ) ); - - private static final long serialVersionUID = 1L; - - public static final StructuralRelationshipsFilter INSTANCE = new StructuralRelationshipsFilter(); - - private StructuralRelationshipsFilter() - { - super( TYPES, TYPES, false, true ); - } - - @Override - public ProjectRelationshipFilter getChildFilter( final ProjectRelationship parent ) - { - return this; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectCycle.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectCycle.java deleted file mode 100644 index 832a9c51..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectCycle.java +++ /dev/null @@ -1,252 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.model; - -import static org.apache.commons.lang.StringUtils.join; -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.filterTerminalParents; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipComparator; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class EProjectCycle - implements Iterable>, EProjectRelationshipCollection -{ - - private static final long serialVersionUID = 1L; - - private List> participants = new ArrayList>(); - - public static final class Builder - { - private final List> participants; - - public Builder( final ProjectRelationship... rels ) - { - participants = new ArrayList>( Arrays.asList( rels ) ); - } - - public Builder( final List> rels ) - { - participants = new ArrayList>( rels ); - } - - public Builder( final Builder builder ) - { - participants = new ArrayList>( builder.participants ); - } - - public Builder( final Builder builder, final int start ) - { - participants = new ArrayList>( builder.participants ); - for ( int i = 0; i < start; i++ ) - { - participants.remove( 0 ); - } - } - - public Builder with( final ProjectRelationship rel ) - { - participants.add( rel ); - return this; - } - - public Builder withoutLast() - { - participants.remove( participants.size() - 1 ); - return this; - } - - public EProjectCycle build() - { - return new EProjectCycle( participants ); - } - - public int indexOf( final ProjectVersionRef ref ) - { - return build().indexOf( ref ); - } - - public int indexOf( final ProjectRelationship rel ) - { - return build().indexOf( rel ); - } - - public boolean contains( final ProjectVersionRef ref ) - { - return build().contains( ref ); - } - - public boolean contains( final ProjectRelationship rel ) - { - return build().contains( rel ); - } - } - - public EProjectCycle( final List> cycle ) - { - this.participants = new ArrayList>( cycle ); - } - - public boolean contains( final ProjectRelationship rel ) - { - return participants.contains( rel ); - } - - public boolean contains( final ProjectVersionRef ref ) - { - for ( final ProjectRelationship rel : participants ) - { - if ( rel.getDeclaring() - .equals( ref ) ) - { - return true; - } - } - - return false; - } - - public int indexOf( final ProjectRelationship rel ) - { - return participants.indexOf( rel ); - } - - public int indexOf( final ProjectVersionRef ref ) - { - int targetIdx = -1; - for ( int i = 0; i < participants.size(); i++ ) - { - final ProjectRelationship rel = participants.get( i ); - if ( rel.getDeclaring() - .equals( ref ) ) - { - return i; - } - - // if we find the ref we're after as a TARGET, log it. - // if, at the end, we haven't found it as a DECLARING ref, return - // the index of the relationship that lists it as a target. - if ( targetIdx < 0 && rel.getTarget() - .asProjectVersionRef() - .equals( ref ) ) - { - targetIdx = i; - } - } - - return targetIdx; - } - - @Override - public Iterator> iterator() - { - return participants.iterator(); - } - - @Override - public Collection> getAllRelationships() - { - final Collection> rels = getExactAllRelationships(); - filterTerminalParents( rels ); - - return rels; - } - - @Override - public Collection> getExactAllRelationships() - { - return new ArrayList>( participants ); - } - - public Set getAllParticipatingProjects() - { - final Set refs = new HashSet(); - for ( final ProjectRelationship rel : participants ) - { - refs.add( rel.getDeclaring() ); - refs.add( rel.getTarget() - .asProjectVersionRef() ); - } - - return refs; - } - - @Override - public String toString() - { - return String.format( "Project cycle: [%s]", join( participants, " -> " ) ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - - final List> sorted = new ArrayList>( participants ); - Collections.sort( sorted, RelationshipComparator.INSTANCE ); - - result = prime * result + sorted.hashCode(); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final EProjectCycle other = (EProjectCycle) obj; - if ( participants == null ) - { - if ( other.participants != null ) - { - return false; - } - } - else - { - - final Set> cycle = new HashSet>( this.participants ); - final Set> otherCycle = new HashSet>( other.participants ); - - for ( final ProjectRelationship rel : cycle ) - { - if ( !otherCycle.contains( rel ) ) - { - return false; - } - } - } - - return true; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectRelationshipCollection.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectRelationshipCollection.java deleted file mode 100644 index 6d6f5307..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/EProjectRelationshipCollection.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.model; - -import java.io.Serializable; -import java.util.Collection; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; - -public interface EProjectRelationshipCollection - extends Serializable -{ - - Collection> getAllRelationships(); - - Collection> getExactAllRelationships(); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/GraphPath.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/GraphPath.java deleted file mode 100644 index 2229d2d3..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/GraphPath.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.model; - -public interface GraphPath - extends Iterable -{ - String getKey(); -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/GraphPathInfo.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/GraphPathInfo.java deleted file mode 100644 index 013210d2..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/model/GraphPathInfo.java +++ /dev/null @@ -1,158 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.model; - -import java.io.Serializable; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.mutate.GraphMutator; -import org.commonjava.maven.atlas.graph.mutate.VersionManagerMutator; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; - -public final class GraphPathInfo - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - private final ProjectRelationshipFilter filter; - - private final GraphMutator mutator; - - private transient RelationshipGraphConnection connection; - - private transient ViewParams params; - - public GraphPathInfo( final RelationshipGraphConnection connection, final ViewParams params ) - { - this.connection = connection; - this.params = params; - filter = params.getFilter(); - mutator = params.getMutator() == null ? new VersionManagerMutator() : params.getMutator(); - } - - public GraphPathInfo( final ProjectRelationshipFilter filter, final GraphMutator mutator, - final RelationshipGraphConnection connection, final ViewParams params ) - { - this.connection = connection; - this.params = params; - this.filter = filter; - this.mutator = mutator; - } - - public ProjectRelationshipFilter getFilter() - { - return filter; - } - - public GraphMutator getMutator() - { - return mutator; - } - - public ProjectRelationship selectRelationship( ProjectRelationship next, final GraphPath path ) - { - if ( filter != null && !filter.accept( next ) ) - { - return null; - } - - if ( mutator != null ) - { - next = mutator.selectFor( next, path, connection, params ); - } - - return next; - } - - public GraphPathInfo getChildPathInfo( final ProjectRelationship rel ) - { - final ProjectRelationshipFilter nextFilter = filter == null ? null : filter.getChildFilter( rel ); - final GraphMutator nextMutator = mutator == null ? null : mutator.getMutatorFor( rel, connection, params ); - if ( nextFilter == filter && nextMutator == mutator ) - { - return this; - } - - return new GraphPathInfo( nextFilter, nextMutator, connection, params ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( filter == null ) ? 0 : filter.hashCode() ); - result = prime * result + ( ( mutator == null ) ? 0 : mutator.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final GraphPathInfo other = (GraphPathInfo) obj; - if ( filter == null ) - { - if ( other.filter != null ) - { - return false; - } - } - else if ( !filter.equals( other.filter ) ) - { - return false; - } - if ( mutator == null ) - { - if ( other.mutator != null ) - { - return false; - } - } - else if ( !mutator.equals( other.mutator ) ) - { - return false; - } - return true; - } - - public String getKey() - { - return ( filter == null ? "none" : filter.getCondensedId() ) + "/" + ( mutator == null ? "none" : mutator.getCondensedId() ); - } - - public void reattach( final RelationshipGraphConnection connection, final ViewParams params ) - { - this.connection = connection; - this.params = params; - } - - @Override - public String toString() - { - return String.format( "GraphPathInfo [filter=%s, mutator=%s, view=%s]", filter, mutator, params.getShortId() ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/GraphMutator.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/GraphMutator.java deleted file mode 100644 index 716a8907..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/GraphMutator.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.mutate; - -import java.io.Serializable; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; - -/** - * Mechanism for selecting alternative relationships (especially by changing the - * target artifact/project), usually making use of version-management information - * injected by the user or accumulated during graph traversal. - * - * Child instances allow for shifts in mutator logic according to encounters with - * different types of relationships. They also allow incorporation of new - * version-management information by embedding new instances of - * {@link VersionManager}. - * - * @author jdcasey - */ -public interface GraphMutator - extends Serializable -{ - - /** - * Alter the relationship to be traversed next, using whatever mutation logic - * this class incorporates. For example, managed versions (a la <dependencyManagement/>) - * - * @param rel The relationship to process. - * @param path The path leading to this selection, which may contain management information, etc. - * @param connection The db connection for this graph - * @param params The parameters for the context "view" of this operation - * @return The alternative relationship, or the given one if no mutation - * takes place. - */ - ProjectRelationship selectFor( ProjectRelationship rel, GraphPath path, - RelationshipGraphConnection connection, ViewParams params ); - - /** - * If necessary, create a new mutator instance to handle the next wave of - * relationships resulting from traversal of the given relationship. - * - * @param rel The relationship that will be traversed next, for which mutator logic is needed. - * @param connection The db connection for this graph - * @param params The parameters for the context "view" of this operation - * - * @return This instance WHEREVER POSSIBLE, or a new mutator instance to - * encapsulate changing logic or metadata. NEVER Null. Decisions about - * whether to proceed should be handled via {@link ProjectRelationshipFilter}, - * not here. - */ - GraphMutator getMutatorFor( ProjectRelationship rel, RelationshipGraphConnection connection, ViewParams params ); - - /** - * Retrieve a human-readable string that uniquely identifies the logic in this mutator, - * along with any state stored in this instance. - */ - String getLongId(); - - /** - * Retrieve a condensed version of the human-readable identity given in {@link #getLongId()}. - * If the human-readable identity is sufficiently short (eg. "ANY"), then no - * hashing is required. - */ - String getCondensedId(); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/ManagedDependencyMutator.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/ManagedDependencyMutator.java deleted file mode 100644 index 94865159..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/ManagedDependencyMutator.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.mutate; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class ManagedDependencyMutator - extends VersionManagerMutator - implements GraphMutator -{ - - private static final long serialVersionUID = 1L; - - @Override - public ProjectRelationship selectFor( final ProjectRelationship rel, final GraphPath path, - final RelationshipGraphConnection connection, final ViewParams params ) - { - if ( rel.getType() != RelationshipType.DEPENDENCY ) // TODO: BOM types?? - { - // logger.debug( "No selections for relationships of type: {}", rel.getType() ); - return rel; - } - - ProjectRelationship mutated = super.selectFor( rel, path, connection, params ); - if ( mutated == null || mutated == rel ) - { - final ProjectVersionRef managed = - connection - .getManagedTargetFor( rel.getTarget(), path, RelationshipType.DEPENDENCY ); - if ( managed != null ) - { - mutated = rel.selectTarget( managed ); - } - } - - return mutated == null ? rel : mutated; - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/NoOpGraphMutator.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/NoOpGraphMutator.java deleted file mode 100644 index f6f8f6b1..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/NoOpGraphMutator.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.mutate; - -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; - -public class NoOpGraphMutator - implements GraphMutator -{ - - private static final long serialVersionUID = 1L; - - public static final NoOpGraphMutator INSTANCE = new NoOpGraphMutator(); - - private NoOpGraphMutator() - { - } - - @Override - public ProjectRelationship selectFor( final ProjectRelationship rel, final GraphPath path, - final RelationshipGraphConnection connection, final ViewParams params ) - { - return rel; - } - - @Override - public GraphMutator getMutatorFor( final ProjectRelationship rel, final RelationshipGraphConnection connection, - final ViewParams params ) - { - return this; - } - - @Override - public String getLongId() - { - return "NOP"; - } - - @Override - public String getCondensedId() - { - return getLongId(); - } - - @Override - public String toString() - { - return getLongId(); - } - - @Override - public int hashCode() - { - return NoOpGraphMutator.class.hashCode() + 1; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - return true; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/VersionManagerMutator.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/VersionManagerMutator.java deleted file mode 100644 index ed6cb868..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/mutate/VersionManagerMutator.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.mutate; - -import org.apache.commons.codec.digest.DigestUtils; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class VersionManagerMutator - implements GraphMutator -{ - - private static final long serialVersionUID = 1L; - - private transient String longId; - - private transient String shortId; - - @Override - public ProjectRelationship selectFor( final ProjectRelationship rel, final GraphPath path, - final RelationshipGraphConnection connection, final ViewParams params ) - { - final ProjectRef target = rel.getTarget() - .asProjectRef(); - - if ( params != null ) - { - final ProjectVersionRef ref = params.getSelection( target ); - if ( ref != null ) - { - return rel.selectTarget( ref ); - } - } - - return rel; - } - - @Override - public GraphMutator getMutatorFor( final ProjectRelationship rel, final RelationshipGraphConnection connection, - final ViewParams params ) - { - return this; - } - - @Override - public int hashCode() - { - return getClass().hashCode() + 1; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - return true; - } - - @Override - public String getLongId() - { - if ( longId == null ) - { - final StringBuilder sb = new StringBuilder(); - final String abbreviatedPackage = getClass().getPackage() - .getName() - .replaceAll( "([a-zA-Z])[a-zA-Z]+", "$1" ); - - sb.append( abbreviatedPackage ) - .append( '.' ) - .append( getClass().getSimpleName() ); - - longId = sb.toString(); - } - - return longId; - } - - @Override - public String getCondensedId() - { - if ( shortId == null ) - { - shortId = DigestUtils.shaHex( getLongId() ); - } - - return shortId; - } - - @Override - public String toString() - { - return getLongId(); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/AbstractProjectRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/AbstractProjectRelationship.java deleted file mode 100644 index cfa73b5a..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/AbstractProjectRelationship.java +++ /dev/null @@ -1,264 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.POM_ROOT_URI; - -import java.io.Serializable; -import java.lang.reflect.Constructor; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public abstract class AbstractProjectRelationship - implements ProjectRelationship, Serializable -{ - - private static final long serialVersionUID = 1L; - - private final List sources = new ArrayList(); - - private final RelationshipType type; - - private final ProjectVersionRef declaring; - - private final T target; - - private final int index; - - private boolean managed = false; - - @SuppressWarnings( "rawtypes" ) - private transient Constructor cloneCtor; - - private URI pomLocation; - - private final boolean cloneUsesLocation = true; - - protected AbstractProjectRelationship( final URI source, final RelationshipType type, - final ProjectVersionRef declaring, final T target, final int index ) - { - this( Collections.singleton( source ), POM_ROOT_URI, type, declaring, target, index, false ); - } - - protected AbstractProjectRelationship( final Collection sources, final RelationshipType type, - final ProjectVersionRef declaring, final T target, final int index ) - { - this( sources, POM_ROOT_URI, type, declaring, target, index, false ); - } - - protected AbstractProjectRelationship( final URI source, final RelationshipType type, - final ProjectVersionRef declaring, final T target, final int index, - final boolean managed ) - { - this( Collections.singleton( source ), POM_ROOT_URI, type, declaring, target, index, managed ); - } - - protected AbstractProjectRelationship( final Collection sources, final RelationshipType type, - final ProjectVersionRef declaring, final T target, final int index, - final boolean managed ) - { - this( sources, POM_ROOT_URI, type, declaring, target, index, managed ); - } - - protected AbstractProjectRelationship( final URI source, final URI pomLocation, final RelationshipType type, - final ProjectVersionRef declaring, final T target, final int index ) - { - this( Collections.singleton( source ), pomLocation, type, declaring, target, index, false ); - } - - protected AbstractProjectRelationship( final Collection sources, final URI pomLocation, - final RelationshipType type, final ProjectVersionRef declaring, - final T target, final int index ) - { - this( sources, pomLocation, type, declaring, target, index, false ); - } - - protected AbstractProjectRelationship( final URI source, final URI pomLocation, final RelationshipType type, - final ProjectVersionRef declaring, final T target, final int index, - final boolean managed ) - { - this( Collections.singleton( source ), pomLocation, type, declaring, target, index, managed ); - } - - protected AbstractProjectRelationship( final Collection sources, final URI pomLocation, - final RelationshipType type, final ProjectVersionRef declaring, - final T target, final int index, final boolean managed ) - { - if ( sources == null ) - { - throw new NullPointerException( "Source URIs cannot be null" ); - } - - for ( final URI source : sources ) - { - addSource( source ); - } - - this.pomLocation = pomLocation; - if ( declaring == null || target == null ) - { - throw new NullPointerException( "Neither declaring ref (" + declaring + ") nor target ref (" + target - + ") can be null!" ); - } - - this.type = type; - this.declaring = declaring; - this.target = target; - this.index = index; - this.managed = managed; - } - - @Override - public final boolean isManaged() - { - return managed; - } - - @Override - public final int getIndex() - { - return index; - } - - @Override - public final RelationshipType getType() - { - return type; - } - - @Override - public final ProjectVersionRef getDeclaring() - { - return declaring; - } - - @Override - public final T getTarget() - { - return target; - } - - @Override - public abstract ArtifactRef getTargetArtifact(); - - @Override - public abstract ProjectRelationship cloneFor( final ProjectVersionRef declaring ); - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( declaring == null ) ? 0 : declaring.hashCode() ); - result = prime * result + ( ( target == null ) ? 0 : target.hashCode() ); - result = prime * result + ( ( type == null ) ? 0 : type.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( obj == null ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final AbstractProjectRelationship other = (AbstractProjectRelationship) obj; - if ( declaring == null ) - { - if ( other.declaring != null ) - { - return false; - } - } - else if ( !declaring.equals( other.declaring ) ) - { - return false; - } - if ( target == null ) - { - if ( other.target != null ) - { - return false; - } - } - else if ( !target.equals( other.target ) ) - { - return false; - } - if ( type != other.type ) - { - return false; - } - return true; - } - - @Override - public final void addSource( final URI source ) - { - if ( source == null ) - { - return; - } - - if ( !sources.contains( source ) ) - { - this.sources.add( source ); - } - } - - @Override - public final void addSources( final Collection sources ) - { - if ( sources == null ) - { - return; - } - - for ( final URI source : sources ) - { - if ( source == null ) - { - continue; - } - - addSource( source ); - } - } - - @Override - public final Set getSources() - { - return new HashSet( sources ); - } - - @Override - public final URI getPomLocation() - { - return pomLocation; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/BomRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/BomRelationship.java deleted file mode 100644 index 4032249b..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/BomRelationship.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.net.URI; -import java.util.Set; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -/** NOTE: BOM relationships are actually marked as concrete. - * This may be somewhat counter-intuitive, but they are structural (like a parent POM). - * Therefore, managed isn't correct (despite Maven's unfortunate choice for location). - */ -public class BomRelationship - extends AbstractProjectRelationship -{ - - private static final long serialVersionUID = 1L; - - public BomRelationship( final Set sources, final ProjectVersionRef d, final ProjectVersionRef t, - final int index ) - { - // BOMs are actually marked as concrete...somewhat counter-intuitive, - // but they're structural, so managed isn't quite correct (despite - // Maven's unfortunate choice for location). - super( sources, RelationshipType.BOM, d, t, index, false ); - } - - public BomRelationship( final URI source, final ProjectVersionRef d, final ProjectVersionRef t, final int index ) - { - // BOMs are actually marked as concrete...somewhat counter-intuitive, - // but they're structural, so managed isn't quite correct (despite - // Maven's unfortunate choice for location). - super( source, RelationshipType.BOM, d, t, index, false ); - } - - public BomRelationship( final Set sources, final URI pomLocation, final ProjectVersionRef d, - final ProjectVersionRef t, final int index ) - { - // BOMs are actually marked as concrete...somewhat counter-intuitive, - // but they're structural, so managed isn't quite correct (despite - // Maven's unfortunate choice for location). - super( sources, pomLocation, RelationshipType.BOM, d, t, index, false ); - } - - public BomRelationship( final URI source, final URI pomLocation, final ProjectVersionRef d, - final ProjectVersionRef t, final int index ) - { - // BOMs are actually marked as concrete...somewhat counter-intuitive, - // but they're structural, so managed isn't quite correct (despite - // Maven's unfortunate choice for location). - super( source, pomLocation, RelationshipType.BOM, d, t, index, false ); - } - - @Override - public ArtifactRef getTargetArtifact() - { - return getTarget().asPomArtifact(); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version ) - { - return selectDeclaring( version, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring().selectVersion( version, force ); - final ProjectVersionRef t = getTarget(); - - return new BomRelationship( getSources(), d, t, getIndex() ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version ) - { - return selectTarget( version, false ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring(); - final ProjectVersionRef t = getTarget().selectVersion( version, force ); - - return new BomRelationship( getSources(), d, t, getIndex() ); - } - - @Override - public ProjectRelationship selectDeclaring( final ProjectVersionRef ref ) - { - final ProjectVersionRef t = getTarget(); - - return new BomRelationship( getSources(), ref, t, getIndex() ); - } - - @Override - public ProjectRelationship selectTarget( final ProjectVersionRef ref ) - { - final ProjectVersionRef d = getDeclaring(); - - return new BomRelationship( getSources(), d, ref, getIndex() ); - } - - @Override - public ProjectRelationship cloneFor( final ProjectVersionRef declaring ) - { - return new BomRelationship( getSources(), getPomLocation(), declaring, getTarget(), getIndex() ); - } - - @Override - public String toString() - { - return String.format( "BomRelationship [%s => %s]", getDeclaring(), getTarget() ); - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/DependencyRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/DependencyRelationship.java deleted file mode 100644 index e2004091..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/DependencyRelationship.java +++ /dev/null @@ -1,188 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.io.Serializable; -import java.net.URI; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -public final class DependencyRelationship - extends AbstractProjectRelationship - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - private final DependencyScope scope; - - private final Set excludes; - - public DependencyRelationship( final URI source, final ProjectVersionRef declaring, final ArtifactRef target, final DependencyScope scope, - final int index, final boolean managed, final ProjectRef... excludes ) - { - super( source, RelationshipType.DEPENDENCY, declaring, target, index, managed ); - this.scope = scope == null ? DependencyScope.compile : scope; - this.excludes = new HashSet( Arrays.asList( excludes ) ); - } - - public DependencyRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, final ArtifactRef target, - final DependencyScope scope, final int index, final boolean managed, final ProjectRef... excludes ) - { - super( source, pomLocation, RelationshipType.DEPENDENCY, declaring, target, index, managed ); - this.scope = scope == null ? DependencyScope.compile : scope; - this.excludes = new HashSet( Arrays.asList( excludes ) ); - } - - public DependencyRelationship( final Collection sources, final ProjectVersionRef declaring, final ArtifactRef target, - final DependencyScope scope, final int index, final boolean managed, final ProjectRef... excludes ) - { - super( sources, RelationshipType.DEPENDENCY, declaring, target, index, managed ); - this.scope = scope == null ? DependencyScope.compile : scope; - this.excludes = new HashSet( Arrays.asList( excludes ) ); - } - - public DependencyRelationship( final Collection sources, final URI pomLocation, final ProjectVersionRef declaring, final ArtifactRef target, - final DependencyScope scope, final int index, final boolean managed, final ProjectRef... excludes ) - { - super( sources, pomLocation, RelationshipType.DEPENDENCY, declaring, target, index, managed ); - this.scope = scope == null ? DependencyScope.compile : scope; - this.excludes = new HashSet( Arrays.asList( excludes ) ); - } - - public final DependencyScope getScope() - { - return scope; - } - - @Override - public synchronized ProjectRelationship cloneFor( final ProjectVersionRef projectRef ) - { - return new DependencyRelationship( getSources(), getPomLocation(), projectRef, getTarget(), scope, getIndex(), isManaged() ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( isManaged() ? 1231 : 1237 ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final DependencyRelationship other = (DependencyRelationship) obj; - if ( isManaged() != other.isManaged() ) - { - return false; - } - return true; - } - - @Override - public String toString() - { - return String.format( "DependencyRelationship [%s => %s (managed=%s, scope=%s, index=%s)]", getDeclaring(), getTarget(), isManaged(), scope, - getIndex() ); - } - - @Override - public ArtifactRef getTargetArtifact() - { - return getTarget(); - } - - public Set getExcludes() - { - return excludes; - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version ) - { - return selectDeclaring( version, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring().selectVersion( version, force ); - final ArtifactRef t = getTarget(); - - return new DependencyRelationship( getSources(), getPomLocation(), d, t, getScope(), getIndex(), isManaged(), - getExcludes().toArray( new ProjectRef[] {} ) ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version ) - { - return selectTarget( version, false ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring(); - ArtifactRef t = getTarget(); - t = new ArtifactRef( t.selectVersion( version, force ), t.getType(), t.getClassifier(), t.isOptional() ); - - return new DependencyRelationship( getSources(), getPomLocation(), d, t, getScope(), getIndex(), isManaged(), - getExcludes().toArray( new ProjectRef[] {} ) ); - } - - @Override - public ProjectRelationship selectDeclaring( final ProjectVersionRef ref ) - { - final ArtifactRef t = getTarget(); - - return new DependencyRelationship( getSources(), getPomLocation(), ref, t, getScope(), getIndex(), isManaged(), - getExcludes().toArray( new ProjectRef[] {} ) ); - } - - @Override - public ProjectRelationship selectTarget( final ProjectVersionRef ref ) - { - final ProjectVersionRef d = getDeclaring(); - ArtifactRef t = getTarget(); - t = (ArtifactRef) ( ( ref instanceof ArtifactRef ) ? ref : new ArtifactRef( ref, t.getType(), t.getClassifier(), t.isOptional() ) ); - - return new DependencyRelationship( getSources(), getPomLocation(), d, t, getScope(), getIndex(), isManaged(), - getExcludes().toArray( new ProjectRef[] {} ) ); - } - - public boolean isBOM() - { - return DependencyScope._import == getScope() && "pom".equals( getTargetArtifact().getType() ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ExtensionRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ExtensionRelationship.java deleted file mode 100644 index 0c9f83ea..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ExtensionRelationship.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.io.Serializable; -import java.net.URI; -import java.util.Collection; - -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -public final class ExtensionRelationship - extends AbstractProjectRelationship - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - public ExtensionRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, - final ProjectVersionRef target, final int index ) - { - super( source, pomLocation, RelationshipType.EXTENSION, declaring, target, index ); - } - - public ExtensionRelationship( final Collection sources, final URI pomLocation, - final ProjectVersionRef declaring, final ProjectVersionRef target, final int index ) - { - super( sources, pomLocation, RelationshipType.EXTENSION, declaring, target, index ); - } - - public ExtensionRelationship( final URI source, final ProjectVersionRef declaring, final ProjectVersionRef target, - final int index ) - { - super( source, RelationshipUtils.POM_ROOT_URI, RelationshipType.EXTENSION, declaring, target, index ); - } - - public ExtensionRelationship( final Collection sources, final ProjectVersionRef declaring, - final ProjectVersionRef target, final int index ) - { - super( sources, RelationshipUtils.POM_ROOT_URI, RelationshipType.EXTENSION, declaring, target, index ); - } - - @Override - public String toString() - { - return String.format( "ExtensionRelationship [%s => %s (index=%s)]", getDeclaring(), getTarget(), getIndex() ); - } - - @Override - public ArtifactRef getTargetArtifact() - { - return new ArtifactRef( getTarget(), null, null, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version ) - { - return selectDeclaring( version, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring().selectVersion( version, force ); - final ProjectVersionRef t = getTarget(); - - return new ExtensionRelationship( getSources(), getPomLocation(), d, t, getIndex() ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version ) - { - return selectTarget( version, false ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring(); - final ProjectVersionRef t = getTarget().selectVersion( version, force ); - - return new ExtensionRelationship( getSources(), getPomLocation(), d, t, getIndex() ); - } - - @Override - public ProjectRelationship selectDeclaring( final ProjectVersionRef ref ) - { - final ProjectVersionRef t = getTarget(); - - return new ExtensionRelationship( getSources(), getPomLocation(), ref, t, getIndex() ); - } - - @Override - public ProjectRelationship selectTarget( final ProjectVersionRef ref ) - { - final ProjectVersionRef d = getDeclaring(); - - return new ExtensionRelationship( getSources(), getPomLocation(), d, ref, getIndex() ); - } - - @Override - public ProjectRelationship cloneFor( final ProjectVersionRef declaring ) - { - return new ExtensionRelationship( getSources(), getPomLocation(), declaring, getTarget(), getIndex() ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ParentRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ParentRelationship.java deleted file mode 100644 index d10e9670..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ParentRelationship.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.io.Serializable; -import java.net.URI; -import java.util.Collection; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -public final class ParentRelationship - extends AbstractProjectRelationship - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - /** - * Ancestry terminus. This is to signify that the declaring project has NO parent relationship. - */ - public ParentRelationship( final URI source, final ProjectVersionRef declaring ) - { - super( source, RelationshipType.PARENT, declaring, declaring, 0 ); - } - - public ParentRelationship( final URI source, final ProjectVersionRef declaring, final ProjectVersionRef target ) - { - super( source, RelationshipType.PARENT, declaring, target, 0 ); - } - - public ParentRelationship( final Collection sources, final ProjectVersionRef declaring, final ProjectVersionRef target ) - { - super( sources, RelationshipType.PARENT, declaring, target, 0 ); - } - - @Override - public String toString() - { - return String.format( "ParentRelationship [%s => %s]", getDeclaring(), getTarget() ); - } - - @Override - public ArtifactRef getTargetArtifact() - { - return new ArtifactRef( getTarget(), "pom", null, false ); - } - - public boolean isTerminus() - { - return getDeclaring().equals( getTarget() ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version ) - { - return selectDeclaring( version, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version, final boolean force ) - { - ProjectVersionRef d = getDeclaring(); - final ProjectVersionRef t = getTarget(); - final boolean self = d.equals( t ); - - d = d.selectVersion( version, force ); - - return new ParentRelationship( getSources(), d, self ? d : t ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version ) - { - return selectTarget( version, false ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring(); - ProjectVersionRef t = getTarget(); - final boolean self = d.equals( t ); - - t = t.selectVersion( version, force ); - - return new ParentRelationship( getSources(), self ? t : d, t ); - } - - @Override - public ProjectRelationship selectDeclaring( final ProjectVersionRef ref ) - { - final ProjectVersionRef t = getTarget(); - - return new ParentRelationship( getSources(), ref, t ); - } - - @Override - public ProjectRelationship selectTarget( final ProjectVersionRef ref ) - { - final ProjectVersionRef d = getDeclaring(); - return new ParentRelationship( getSources(), d, ref ); - } - - @Override - public ProjectRelationship cloneFor( final ProjectVersionRef declaring ) - { - return new ParentRelationship( getSources(), declaring, getTarget() ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/PluginDependencyRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/PluginDependencyRelationship.java deleted file mode 100644 index b5ffd528..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/PluginDependencyRelationship.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.io.Serializable; -import java.net.URI; -import java.util.Collection; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -public final class PluginDependencyRelationship - extends AbstractProjectRelationship - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - private final ProjectRef plugin; - - public PluginDependencyRelationship( final URI source, final ProjectVersionRef declaring, final ProjectRef plugin, final ArtifactRef target, - final int index, final boolean managed ) - { - super( source, RelationshipType.PLUGIN_DEP, declaring, target, index, managed ); - this.plugin = plugin; - } - - public PluginDependencyRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, final ProjectRef plugin, - final ArtifactRef target, final int index, final boolean managed ) - { - super( source, pomLocation, RelationshipType.PLUGIN_DEP, declaring, target, index, managed ); - this.plugin = plugin; - } - - public PluginDependencyRelationship( final Collection sources, final URI pomLocation, final ProjectVersionRef declaring, - final ProjectRef plugin, final ArtifactRef target, final int index, final boolean managed ) - { - super( sources, pomLocation, RelationshipType.PLUGIN_DEP, declaring, target, index, managed ); - this.plugin = plugin; - } - - public final ProjectRef getPlugin() - { - return plugin; - } - - @Override - public synchronized ProjectRelationship cloneFor( final ProjectVersionRef projectRef ) - { - return new PluginDependencyRelationship( getSources(), getPomLocation(), projectRef, plugin, getTarget(), getIndex(), isManaged() ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( isManaged() ? 1231 : 1237 ); - result = prime * result + ( ( plugin == null ) ? 0 : plugin.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final PluginDependencyRelationship other = (PluginDependencyRelationship) obj; - if ( isManaged() != other.isManaged() ) - { - return false; - } - if ( plugin == null ) - { - if ( other.plugin != null ) - { - return false; - } - } - else if ( !plugin.equals( other.plugin ) ) - { - return false; - } - return true; - } - - @Override - public String toString() - { - return String.format( "PluginDependencyRelationship [%s -> (%s) => %s (managed=%s, index=%s)]", getDeclaring(), plugin, getTarget(), - isManaged(), getIndex() ); - } - - @Override - public ArtifactRef getTargetArtifact() - { - return getTarget(); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version ) - { - return selectDeclaring( version, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring().selectVersion( version, force ); - final ArtifactRef t = getTarget(); - - return new PluginDependencyRelationship( getSources(), getPomLocation(), d, getPlugin(), t, getIndex(), isManaged() ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version ) - { - return selectTarget( version, false ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring(); - ArtifactRef t = getTarget(); - t = new ArtifactRef( t.selectVersion( version, force ), t.getType(), t.getClassifier(), t.isOptional() ); - - return new PluginDependencyRelationship( getSources(), getPomLocation(), d, getPlugin(), t, getIndex(), isManaged() ); - } - - @Override - public ProjectRelationship selectDeclaring( final ProjectVersionRef ref ) - { - final ArtifactRef t = getTarget(); - - return new PluginDependencyRelationship( getSources(), getPomLocation(), ref, getPlugin(), t, getIndex(), isManaged() ); - } - - @Override - public ProjectRelationship selectTarget( final ProjectVersionRef ref ) - { - final ProjectVersionRef d = getDeclaring(); - ArtifactRef t = getTarget(); - t = (ArtifactRef) ( ( ref instanceof ArtifactRef ) ? ref : new ArtifactRef( ref, t.getType(), t.getClassifier(), t.isOptional() ) ); - - return new PluginDependencyRelationship( getSources(), getPomLocation(), d, getPlugin(), t, getIndex(), isManaged() ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/PluginRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/PluginRelationship.java deleted file mode 100644 index 9a86a7dd..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/PluginRelationship.java +++ /dev/null @@ -1,164 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.io.Serializable; -import java.net.URI; -import java.util.Collection; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -public final class PluginRelationship - extends AbstractProjectRelationship - implements Serializable -{ - - private static final long serialVersionUID = 1L; - - private final boolean reporting; - - public PluginRelationship( final URI source, final ProjectVersionRef declaring, final ProjectVersionRef target, final int index, - final boolean managed ) - { - this( source, declaring, target, index, managed, false ); - } - - public PluginRelationship( final URI source, final ProjectVersionRef declaring, final ProjectVersionRef target, final int index, - final boolean managed, final boolean reporting ) - { - super( source, RelationshipType.PLUGIN, declaring, target, index, managed ); - this.reporting = reporting; - } - - public PluginRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, final ProjectVersionRef target, - final int index, final boolean managed ) - { - this( source, pomLocation, declaring, target, index, managed, false ); - } - - public PluginRelationship( final URI source, final URI pomLocation, final ProjectVersionRef declaring, final ProjectVersionRef target, - final int index, final boolean managed, final boolean reporting ) - { - super( source, pomLocation, RelationshipType.PLUGIN, declaring, target, index, managed ); - this.reporting = reporting; - } - - public PluginRelationship( final Collection sources, final URI pomLocation, final ProjectVersionRef declaring, - final ProjectVersionRef target, final int index, final boolean managed, final boolean reporting ) - { - super( sources, pomLocation, RelationshipType.PLUGIN, declaring, target, index, managed ); - this.reporting = reporting; - } - - public final boolean isReporting() - { - return reporting; - } - - @Override - public synchronized ProjectRelationship cloneFor( final ProjectVersionRef projectRef ) - { - return new PluginRelationship( getSources(), getPomLocation(), projectRef, getTarget(), getIndex(), isManaged(), reporting ); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( isManaged() ? 1231 : 1237 ); - return result; - } - - @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { - return true; - } - if ( !super.equals( obj ) ) - { - return false; - } - if ( getClass() != obj.getClass() ) - { - return false; - } - final PluginRelationship other = (PluginRelationship) obj; - if ( isManaged() != other.isManaged() ) - { - return false; - } - return true; - } - - @Override - public String toString() - { - return String.format( "PluginRelationship [%s => %s (managed=%s, index=%s)]", getDeclaring(), getTarget(), isManaged(), getIndex() ); - } - - @Override - public ArtifactRef getTargetArtifact() - { - return new ArtifactRef( getTarget(), "maven-plugin", null, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version ) - { - return selectDeclaring( version, false ); - } - - @Override - public ProjectRelationship selectDeclaring( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring().selectVersion( version, force ); - final ProjectVersionRef t = getTarget(); - - return new PluginRelationship( getSources(), getPomLocation(), d, t, getIndex(), isManaged(), isReporting() ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version ) - { - return selectTarget( version, false ); - } - - @Override - public ProjectRelationship selectTarget( final SingleVersion version, final boolean force ) - { - final ProjectVersionRef d = getDeclaring(); - final ProjectVersionRef t = getTarget().selectVersion( version, force ); - - return new PluginRelationship( getSources(), getPomLocation(), d, t, getIndex(), isManaged(), isReporting() ); - } - - @Override - public ProjectRelationship selectDeclaring( final ProjectVersionRef ref ) - { - final ProjectVersionRef t = getTarget(); - - return new PluginRelationship( getSources(), getPomLocation(), ref, t, getIndex(), isManaged(), isReporting() ); - } - - @Override - public ProjectRelationship selectTarget( final ProjectVersionRef ref ) - { - final ProjectVersionRef d = getDeclaring(); - - return new PluginRelationship( getSources(), getPomLocation(), d, ref, getIndex(), isManaged(), isReporting() ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ProjectRelationship.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ProjectRelationship.java deleted file mode 100644 index 33067b8b..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/ProjectRelationship.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.io.Serializable; -import java.net.URI; -import java.util.Collection; -import java.util.Set; - -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.SingleVersion; - -public interface ProjectRelationship - extends Serializable -{ - - int getIndex(); - - RelationshipType getType(); - - ProjectVersionRef getDeclaring(); - - T getTarget(); - - ArtifactRef getTargetArtifact(); - - ProjectRelationship cloneFor( final ProjectVersionRef projectRef ); - - @Deprecated - ProjectRelationship selectDeclaring( SingleVersion version ); - - @Deprecated - ProjectRelationship selectDeclaring( SingleVersion version, boolean force ); - - @Deprecated - ProjectRelationship selectTarget( SingleVersion version ); - - @Deprecated - ProjectRelationship selectTarget( SingleVersion version, boolean force ); - - ProjectRelationship selectDeclaring( ProjectVersionRef ref ); - - ProjectRelationship selectTarget( ProjectVersionRef ref ); - - boolean isManaged(); - - Set getSources(); - - void addSource( URI source ); - - void addSources( Collection sources ); - - URI getPomLocation(); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipComparator.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipComparator.java deleted file mode 100644 index 60e9bcba..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipComparator.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.POM_ROOT_URI; - -import java.util.Comparator; - -public final class RelationshipComparator - implements Comparator> -{ - - public static final RelationshipComparator INSTANCE = new RelationshipComparator(); - - private RelationshipComparator() - { - } - - @Override - public int compare( final ProjectRelationship one, final ProjectRelationship two ) - { - if ( one.getType() == two.getType() ) - { - if ( one.getPomLocation() - .equals( POM_ROOT_URI ) && !two.getPomLocation() - .equals( POM_ROOT_URI ) ) - { - return -1; - } - else if ( !one.getPomLocation() - .equals( POM_ROOT_URI ) && two.getPomLocation() - .equals( POM_ROOT_URI ) ) - { - return 1; - } - - if ( one.getTarget() - .asProjectVersionRef() - .equals( two.getDeclaring() ) ) - { - return -1; - } - else if ( one.getDeclaring() - .equals( two.getTarget() - .asProjectVersionRef() ) ) - { - return 1; - } - else if ( one.getDeclaring() - .equals( two.getDeclaring() ) ) - { - return one.getIndex() - two.getIndex(); - } - } - else - { - return one.getType() - .ordinal() - two.getType() - .ordinal(); - } - - return 0; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipType.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipType.java deleted file mode 100644 index e4761d17..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/rel/RelationshipType.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -public enum RelationshipType -{ - - PARENT( "parent" ), BOM( "bom" ), DEPENDENCY( "dependency", "dep" ), PLUGIN( "plugin" ), PLUGIN_DEP( "plugin-dependency", "plugin-dep", - "plugin-level-dependency", "plugin-level-dep" ), EXTENSION( "extension", "ext" ); - - private final Set names; - - private RelationshipType( final String... names ) - { - this.names = Collections.unmodifiableSet( new HashSet( Arrays.asList( names ) ) ); - } - - public Set names() - { - return names; - } - - public static RelationshipType getType( String type ) - { - if ( type == null || type.trim() - .length() < 1 ) - { - return null; - } - - type = type.trim(); - for ( final RelationshipType rt : values() ) - { - for ( final String name : rt.names() ) - { - if ( name.equalsIgnoreCase( type ) ) - { - return rt; - } - } - } - - return null; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnection.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnection.java deleted file mode 100644 index a037fdc5..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnection.java +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.model.GraphPathInfo; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.graph.traverse.RelationshipGraphTraversal; -import org.commonjava.maven.atlas.graph.traverse.TraversalType; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public interface RelationshipGraphConnection -{ - - /* - * ######################### - * Mutations are viewless - * ######################### - */ - - boolean addCycle( EProjectCycle cycle ) - throws RelationshipGraphConnectionException; - - void addDisconnectedProject( ProjectVersionRef ref ) - throws RelationshipGraphConnectionException; - - void addMetadata( ProjectVersionRef ref, String key, String value ) - throws RelationshipGraphConnectionException; - - void setMetadata( ProjectVersionRef ref, Map metadata ) - throws RelationshipGraphConnectionException; - - void deleteRelationshipsDeclaredBy( ProjectVersionRef root ) - throws RelationshipGraphConnectionException; - - /** - * Add the given relationships. Skip/return those that introduce cycles. - * - * @return The set of relationships that were NOT added because they introduce cycles. NEVER null, but maybe empty. - */ - Set> addRelationships( ProjectRelationship... rel ) - throws RelationshipGraphConnectionException; - - void addProjectError( ProjectVersionRef ref, Throwable error ) - throws RelationshipGraphConnectionException; - - void clearProjectError( ProjectVersionRef ref ) - throws RelationshipGraphConnectionException; - - void recomputeIncompleteSubgraphs() - throws RelationshipGraphConnectionException; - - void reindex() - throws RelationshipGraphConnectionException; - - void reindex( final ProjectVersionRef ref ) - throws RelationshipGraphConnectionException; - - /* - * ################################################ - * Queries require a view - * --- - * View param is first to support vararg methods - * ################################################ - */ - - Throwable getProjectError( ProjectVersionRef ref ); - - Collection> getRelationshipsDeclaredBy( ViewParams params, ProjectVersionRef root ); - - Collection> getRelationshipsTargeting( ViewParams params, ProjectVersionRef root ); - - Collection> getAllRelationships( ViewParams params ); - - Set>> getAllPathsTo( ViewParams params, ProjectVersionRef... projectVersionRefs ); - - boolean introducesCycle( ViewParams params, ProjectRelationship rel ); - - Set getAllProjects( ViewParams params ); - - void traverse( RelationshipGraphTraversal traversal, ProjectVersionRef root, RelationshipGraph graph, - TraversalType type ) - throws RelationshipGraphConnectionException; - - boolean containsProject( ViewParams params, ProjectVersionRef ref ); - - boolean containsRelationship( ViewParams params, ProjectRelationship rel ); - - boolean isMissing( ViewParams params, ProjectVersionRef project ); - - boolean hasMissingProjects( ViewParams params ); - - boolean hasProjectError( ProjectVersionRef ref ); - - Set getMissingProjects( ViewParams params ); - - boolean hasVariableProjects( ViewParams params ); - - Set getVariableProjects( ViewParams params ); - - Set getCycles( ViewParams params ); - - boolean isCycleParticipant( ViewParams params, ProjectRelationship rel ); - - boolean isCycleParticipant( ViewParams params, ProjectVersionRef ref ); - - Map getMetadata( ProjectVersionRef ref ); - - Map getMetadata( ProjectVersionRef ref, Set keys ); - - Set getProjectsWithMetadata( ViewParams params, String key ); - - /** - * @deprecated Use {@link #getDirectRelationshipsFrom(GraphView,ProjectVersionRef,boolean,boolean,RelationshipType...)} instead - */ - @Deprecated - Set> getDirectRelationshipsFrom( ViewParams params, ProjectVersionRef from, - boolean includeManagedInfo, RelationshipType... types ); - - /** - * @deprecated Use {@link #getDirectRelationshipsTo(GraphView,ProjectVersionRef,boolean,boolean,RelationshipType...)} instead - */ - @Deprecated - Set> getDirectRelationshipsTo( ViewParams params, ProjectVersionRef to, - boolean includeManagedInfo, RelationshipType... types ); - - Set> getDirectRelationshipsFrom( ViewParams params, ProjectVersionRef from, - boolean includeManagedInfo, boolean includeConcreteInfo, - RelationshipType... types ); - - Set> getDirectRelationshipsTo( ViewParams params, ProjectVersionRef to, - boolean includeManagedInfo, boolean includeConcreteInfo, - RelationshipType... types ); - - Set getProjectsMatching( ViewParams params, ProjectRef projectRef ); - - void printStats(); - - ProjectVersionRef getManagedTargetFor( ProjectVersionRef target, GraphPath path, RelationshipType type ); - - GraphPath createPath( ProjectRelationship... relationships ); - - GraphPath createPath( GraphPath parent, ProjectRelationship relationship ); - - boolean registerView( ViewParams params ); - - void registerViewSelection( ViewParams params, ProjectRef ref, ProjectVersionRef projectVersionRef ); - - Map, GraphPathInfo> getPathMapTargeting( ViewParams params, Set refs ); - - ProjectVersionRef getPathTargetRef( GraphPath path ); - - List getPathRefs( ViewParams params, GraphPath path ); - - void close() - throws RelationshipGraphConnectionException; - - String getWorkspaceId(); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnectionException.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnectionException.java deleted file mode 100644 index 18d186d1..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnectionException.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.spi; - -import org.commonjava.maven.atlas.graph.RelationshipGraphException; - -public class RelationshipGraphConnectionException - extends RelationshipGraphException -{ - - private static final long serialVersionUID = 1L; - - public RelationshipGraphConnectionException( final String message, final Throwable error, final Object... params ) - { - super( message, error, params ); - } - - public RelationshipGraphConnectionException( final String message, final Object... params ) - { - super( message, params ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnectionFactory.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnectionFactory.java deleted file mode 100644 index 76fea29d..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/spi/RelationshipGraphConnectionFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.commonjava.maven.atlas.graph.spi; - -import java.util.Set; - -public interface RelationshipGraphConnectionFactory -{ - - RelationshipGraphConnection openConnection( String workspaceId, boolean create ) - throws RelationshipGraphConnectionException; - - Set listWorkspaces(); - - void flush( RelationshipGraphConnection connection ) - throws RelationshipGraphConnectionException; - - boolean delete( String workspaceId ) - throws RelationshipGraphConnectionException; - - void close() - throws RelationshipGraphConnectionException; - - boolean exists( String workspaceId ); - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AbstractFilteringTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AbstractFilteringTraversal.java deleted file mode 100644 index a1894bdf..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AbstractFilteringTraversal.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.List; - -import org.commonjava.maven.atlas.graph.filter.AnyFilter; -import org.commonjava.maven.atlas.graph.filter.NoneFilter; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; - -public abstract class AbstractFilteringTraversal - extends AbstractTraversal -{ - - private final ProjectRelationshipFilter rootFilter; - - protected AbstractFilteringTraversal() - { - rootFilter = AnyFilter.INSTANCE; - } - - protected AbstractFilteringTraversal( final ProjectRelationshipFilter filter ) - { - rootFilter = filter; - } - - protected abstract boolean shouldTraverseEdge( ProjectRelationship relationship, - List> path ); - - protected void edgeTraversalFinished( final ProjectRelationship relationship, - final List> path ) - { - } - - public final ProjectRelationshipFilter getRootFilter() - { - return rootFilter; - } - - @Override - public final void edgeTraversed( final ProjectRelationship relationship, final List> path ) - { - edgeTraversalFinished( relationship, path ); - } - - @Override - public final boolean traverseEdge( final ProjectRelationship relationship, - final List> path ) - { - if ( !preCheck( relationship, path ) ) - { - return false; - } - - // seen.add( relationship ); - - final boolean ok = shouldTraverseEdge( relationship, path ); - - return ok; - } - - @Override - public boolean preCheck( final ProjectRelationship relationship, final List> path ) - { - boolean result = true; - - final ProjectRelationshipFilter filter = constructFilter( path ); - if ( result && filter != null && !filter.accept( relationship ) ) - { - result = false; - } - - return result; - } - - private ProjectRelationshipFilter constructFilter( final List> path ) - { - if ( rootFilter == null ) - { - return null; - } - - ProjectRelationshipFilter filter = rootFilter; - for ( final ProjectRelationship rel : path ) - { - if ( !filter.accept( rel ) ) - { - return NoneFilter.INSTANCE; - } - else - { - filter = filter.getChildFilter( rel ); - } - } - - return filter; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AbstractTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AbstractTraversal.java deleted file mode 100644 index 94334d0f..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AbstractTraversal.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.List; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; - -public abstract class AbstractTraversal - implements RelationshipGraphTraversal -{ - - - @Override - public void startTraverse( final RelationshipGraph graph ) - throws RelationshipGraphConnectionException - { - } - - @Override - public void endTraverse( final RelationshipGraph graph ) - throws RelationshipGraphConnectionException - { - } - - @Override - public void edgeTraversed( final ProjectRelationship relationship, final List> path ) - { - } - - @Override - public boolean traverseEdge( final ProjectRelationship relationship, final List> path ) - { - return preCheck( relationship, path ); - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AncestryTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AncestryTraversal.java deleted file mode 100644 index 55022d1c..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/AncestryTraversal.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.List; - -import org.commonjava.maven.atlas.graph.filter.ParentFilter; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class AncestryTraversal - extends FilteringTraversal -{ - - public AncestryTraversal() - { - super( ParentFilter.EXCLUDE_TERMINAL_PARENTS, true ); - } - - public List getAncestry() - { - return getCapturedProjects( true ); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/BuildOrderTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/BuildOrderTraversal.java deleted file mode 100644 index ba2b267f..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/BuildOrderTraversal.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.filter.OrFilter; -import org.commonjava.maven.atlas.graph.filter.ParentFilter; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.traverse.model.BuildOrder; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class BuildOrderTraversal - extends AbstractFilteringTraversal -{ - - private final List order = new ArrayList(); - - private Set cycles; - - public BuildOrderTraversal() - { - } - - public BuildOrderTraversal( final ProjectRelationshipFilter filter ) - { - super( new OrFilter( filter, ParentFilter.EXCLUDE_TERMINAL_PARENTS ) ); - } - - public BuildOrder getBuildOrder() - { - return new BuildOrder( order, cycles ); - } - - @Override - protected boolean shouldTraverseEdge( final ProjectRelationship relationship, - final List> path ) - { - final ProjectVersionRef decl = relationship.getDeclaring(); - - ProjectVersionRef target = relationship.getTarget(); - if ( target instanceof ArtifactRef ) - { - target = ( (ArtifactRef) target ).asProjectVersionRef(); - } - - final ProjectRef baseDecl = new ProjectRef( decl.getGroupId(), decl.getArtifactId() ); - final ProjectRef baseTgt = new ProjectRef( target.getGroupId(), target.getArtifactId() ); - - int declIdx = order.indexOf( baseDecl ); - final int tgtIdx = order.indexOf( baseTgt ); - if ( declIdx < 0 ) - { - declIdx = order.size(); - order.add( baseDecl ); - } - - if ( tgtIdx < 0 ) - { - order.add( declIdx, baseTgt ); - } - - return true; - } - - @Override - public void endTraverse( final RelationshipGraph graph ) - throws RelationshipGraphConnectionException - { - super.endTraverse( graph ); - - Set cycles = graph.getCycles(); - if ( cycles != null ) - { - cycles = new HashSet( cycles ); - for ( final Iterator iterator = cycles.iterator(); iterator.hasNext(); ) - { - final EProjectCycle eProjectCycle = iterator.next(); - ProjectRelationshipFilter filter = getRootFilter(); - - boolean include = true; - for ( final ProjectRelationship rel : eProjectCycle ) - { - if ( !filter.accept( rel ) ) - { - include = false; - break; - } - - filter = filter.getChildFilter( rel ); - } - - if ( !include ) - { - iterator.remove(); - } - } - - } - - this.cycles = cycles; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/FilteringTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/FilteringTraversal.java deleted file mode 100644 index 34655d5d..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/FilteringTraversal.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.ArrayList; -import java.util.List; - -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class FilteringTraversal - extends AbstractFilteringTraversal -{ - - private final List> captured = new ArrayList>(); - - private final boolean doCapture; - - public FilteringTraversal( final ProjectRelationshipFilter filter ) - { - this( filter, false ); - } - - public FilteringTraversal( final ProjectRelationshipFilter filter, final boolean doCapture ) - { - super( filter ); - this.doCapture = doCapture; - } - - public List> getCapturedRelationships() - { - return captured; - } - - public List getCapturedProjects( final boolean unique ) - { - final List refs = new ArrayList(); - for ( final ProjectRelationship rel : captured ) - { - final ProjectVersionRef d = rel.getDeclaring(); - final ProjectVersionRef t = rel.getTarget() - .asProjectVersionRef(); - - if ( !unique || !refs.contains( d ) ) - { - refs.add( d ); - } - - if ( !unique || !refs.contains( t ) ) - { - refs.add( t ); - } - } - - return refs; - } - - @Override - protected boolean shouldTraverseEdge( final ProjectRelationship relationship, - final List> path ) - { - if ( doCapture ) - { - captured.add( relationship ); - } - return true; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/ImpactTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/ImpactTraversal.java deleted file mode 100644 index 6fac6b24..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/ImpactTraversal.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class ImpactTraversal - extends AbstractTraversal -{ - - private final Map>>> impactedPaths = - new HashMap>>>(); - - private final boolean includeManagedInfo; - - public ImpactTraversal( final ProjectVersionRef... targets ) - { - this( false, targets ); - } - - public ImpactTraversal( final boolean includeManagedInfo, final ProjectVersionRef... targets ) - { - this.includeManagedInfo = includeManagedInfo; - for ( final ProjectVersionRef target : targets ) - { - impactedPaths.put( target, new HashSet>>() ); - } - } - - public ImpactTraversal( final Set targets ) - { - this( false, targets ); - } - - public ImpactTraversal( final boolean includeManagedInfo, final Set targets ) - { - this.includeManagedInfo = includeManagedInfo; - for ( final ProjectVersionRef target : targets ) - { - impactedPaths.put( target, new HashSet>>() ); - } - } - - public Map>>> getImpactedPaths() - { - return impactedPaths; - } - - @Override - public boolean traverseEdge( final ProjectRelationship relationship, final List> path ) - { - if ( !preCheck( relationship, path ) ) - { - return false; - } - - final ProjectVersionRef target = relationship.getTarget() - .asProjectVersionRef(); - final Set>> paths = impactedPaths.get( target ); - final ArrayList> p = new ArrayList>( path ); - p.add( relationship ); - - paths.add( p ); - - // we may yet encounter the impact targets, so allow this traverse to proceed. - return true; - } - - @Override - public boolean preCheck( final ProjectRelationship relationship, final List> path ) - { - if ( !includeManagedInfo ) - { - if ( relationship instanceof DependencyRelationship - && ( (DependencyRelationship) relationship ).isManaged() ) - { - return false; - } - - if ( relationship instanceof PluginRelationship && ( (PluginRelationship) relationship ).isManaged() ) - { - return false; - } - } - - final Set>> paths = impactedPaths.get( relationship.getTarget() - .asProjectVersionRef() ); - if ( paths != null && paths.isEmpty() ) - { - // we've seen an impact target, we don't need to go further. - - // TODO: huh?? - return false; - } - - return true; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/RelationshipGraphTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/RelationshipGraphTraversal.java deleted file mode 100644 index eadf8bf4..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/RelationshipGraphTraversal.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.List; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; - -public interface RelationshipGraphTraversal -{ - - void startTraverse( RelationshipGraph graph ) - throws RelationshipGraphConnectionException; - - void endTraverse( RelationshipGraph graph ) - throws RelationshipGraphConnectionException; - - boolean traverseEdge( ProjectRelationship relationship, List> path ); - - void edgeTraversed( ProjectRelationship relationship, List> path ); - - boolean preCheck( ProjectRelationship relationship, List> path ); -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/TransitiveDependencyTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/TransitiveDependencyTraversal.java deleted file mode 100644 index ab086c7a..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/TransitiveDependencyTraversal.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.commonjava.maven.atlas.graph.filter.DependencyFilter; -import org.commonjava.maven.atlas.graph.filter.OrFilter; -import org.commonjava.maven.atlas.graph.filter.ParentFilter; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.VersionlessArtifactRef; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TransitiveDependencyTraversal - extends AbstractFilteringTraversal -{ - - private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final Map artifacts = new HashMap(); - - private final Map seenArtifacts = new HashMap(); - - public TransitiveDependencyTraversal() - { - this( DependencyScope.runtime ); - } - - public TransitiveDependencyTraversal( final ProjectRelationshipFilter filter ) - { - super( filter ); - } - - public TransitiveDependencyTraversal( final DependencyScope scope ) - { - super( new OrFilter( new DependencyFilter( scope ), ParentFilter.EXCLUDE_TERMINAL_PARENTS ) ); - } - - public List getArtifacts() - { - return Collections.unmodifiableList( new ArrayList( artifacts.values() ) ); - } - - @Override - public boolean shouldTraverseEdge( final ProjectRelationship relationship, - final List> path ) - { - boolean result = false; - if ( relationship instanceof DependencyRelationship ) - { - final ArtifactRef target = (ArtifactRef) relationship.getTarget(); - final VersionlessArtifactRef versionlessTarget = new VersionlessArtifactRef( target ); - - logger.debug( "Checking for seen versionless GA[TC]: {}", versionlessTarget ); - final Integer distance = seenArtifacts.get( versionlessTarget ); - if ( distance == null || distance > path.size() ) - { - logger.debug( "Adding: {} ({})", target, versionlessTarget ); - artifacts.put( versionlessTarget, target ); - seenArtifacts.put( versionlessTarget, path.size() ); - result = true; - } - } - else if ( relationship instanceof ParentRelationship ) - { - result = true; - } - - return result; - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/TraversalType.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/TraversalType.java deleted file mode 100644 index 07e21d08..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/TraversalType.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse; - -public enum TraversalType -{ - - depth_first, breadth_first; - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/model/BuildOrder.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/model/BuildOrder.java deleted file mode 100644 index 16bbbe7e..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/model/BuildOrder.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.model; - -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; - -public final class BuildOrder -{ - - private final List order; - - private final Set cycles; - - public BuildOrder( final List order, final Set cycles ) - { - this.order = Collections.unmodifiableList( order ); - this.cycles = cycles == null ? null : Collections.unmodifiableSet( cycles ); - } - - public List getOrder() - { - return order; - } - - public Set getCycles() - { - return cycles; - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/DependencyTreeRelationshipPrinter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/DependencyTreeRelationshipPrinter.java deleted file mode 100644 index d194ca80..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/DependencyTreeRelationshipPrinter.java +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.print; - -import java.io.PrintWriter; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class DependencyTreeRelationshipPrinter - implements StructureRelationshipPrinter -{ - - private final Set missing; - - public DependencyTreeRelationshipPrinter() - { - missing = null; - } - - public DependencyTreeRelationshipPrinter( final Set missing ) - { - this.missing = missing; - } - - @Override - public void print( final ProjectRelationship relationship, final ProjectVersionRef selectedTarget, - final PrintWriter writer, final Map> labels, final int depth, - final String indent ) - { - indent( writer, depth, indent ); - - final RelationshipType type = relationship.getType(); - - final ProjectVersionRef originalTarget = relationship.getTarget() - .asProjectVersionRef(); - - ProjectVersionRef target = null; - ArtifactRef targetArtifact = relationship.getTargetArtifact(); - - if ( selectedTarget == null ) - { - target = originalTarget; - } - else - { - target = selectedTarget; - targetArtifact = selectedTarget.asArtifactRef( targetArtifact.getTypeAndClassifier() ); - } - - final Set localLabels = new HashSet(); - - String suffix = null; - if ( type == RelationshipType.DEPENDENCY ) - { - final DependencyRelationship dr = (DependencyRelationship) relationship; - suffix = ":" + dr.getScope() - .name(); - - if ( dr.getTargetArtifact() - .isOptional() ) - { - localLabels.add( "OPTIONAL" ); - } - - // writer.print( " [idx: " ) - // .append( relationship.getIndex() ) - // .append( ']' ); - } - else - { - localLabels.add( type.name() ); - } - - printProjectVersionRef( targetArtifact, writer, suffix, labels, localLabels ); - - if ( !target.equals( originalTarget ) ) - { - writer.print( " [was: " ); - writer.print( originalTarget ); - writer.print( "]" ); - } - - if ( missing != null && missing.contains( target ) ) - { - writer.print( '\n' ); - indent( writer, depth + 1, indent ); - writer.print( "???" ); - } - } - - @Override - public void printProjectVersionRef( final ProjectVersionRef targetArtifact, final PrintWriter writer, - final String targetSuffix, final Map> labels, - final Set localLabels ) - { - // the original could be an artifact ref! - final ProjectVersionRef target = targetArtifact.asProjectVersionRef(); - - writer.print( targetArtifact ); - if ( targetSuffix != null ) - { - writer.print( targetSuffix ); - } - - boolean hasLabel = false; - if ( localLabels != null && !localLabels.isEmpty() ) - { - hasLabel = true; - writer.print( " (" ); - - boolean first = true; - for ( final String label : localLabels ) - { - if ( first ) - { - first = false; - } - else - { - writer.print( ", " ); - } - - writer.print( label ); - } - } - - for ( final Entry> entry : labels.entrySet() ) - { - final String label = entry.getKey(); - final Set refs = entry.getValue(); - - if ( refs.contains( target ) ) - { - if ( !hasLabel ) - { - hasLabel = true; - writer.print( " (" ); - } - else - { - writer.print( ", " ); - } - - writer.print( label ); - } - - } - - if ( hasLabel ) - { - writer.print( ')' ); - } - } - - private void indent( final PrintWriter writer, final int depth, final String indent ) - { - for ( int i = 0; i < depth; i++ ) - { - writer.print( indent ); - } - } -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/ListPrinter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/ListPrinter.java deleted file mode 100644 index 64c1e4cd..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/ListPrinter.java +++ /dev/null @@ -1,161 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.print; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class ListPrinter -{ - - // private final Logger logger = new Logger( getClass() ); - - private final StructureRelationshipPrinter relationshipPrinter; - - // private final Set seen = new HashSet(); - - public ListPrinter() - { - this.relationshipPrinter = new TargetRefPrinter(); - } - - public ListPrinter( final StructureRelationshipPrinter relationshipPrinter ) - { - this.relationshipPrinter = relationshipPrinter; - } - - public void printStructure( final ProjectVersionRef from, - final Map>> links, - final Map> labels, PrintWriter writer ) - { - printStructure( from, links, null, null, labels, writer ); - } - - public void printStructure( final ProjectVersionRef from, - final Map>> links, final String header, - final String footer, final Map> labels, - PrintWriter writer ) - { - if ( header != null ) - { - writer.print( header ); - } - - writer.print( " " ); - relationshipPrinter.printProjectVersionRef( from, writer, null, labels, null ); - // writer.print( from ); - - final Set lines = new LinkedHashSet(); - - printLinks( from, lines, links, labels, new HashSet(), new Stack() ); - - final List sorted = new ArrayList( lines ); - Collections.sort( sorted ); - - for ( final String line : sorted ) - { - writer.print( "\n " ); - writer.print( line ); - } - writer.print( "\n" ); - - if ( footer != null ) - { - writer.print( footer ); - } - } - - private void printLinks( final ProjectVersionRef from, final Set lines, final Map>> links, - final Map> labels, final Set excluded, - final Stack inPath ) - { - inPath.push( from ); - - final List> outbound = links.get( from ); - if ( outbound != null ) - { - StringWriter sw; - for ( final ProjectRelationship out : outbound ) - { - sw = new StringWriter(); - - ProjectVersionRef outRef = out.getTarget() - .asProjectVersionRef(); - if ( inPath.contains( outRef ) ) - { - continue; - } - - if ( excluded.contains( outRef ) ) - { - continue; - } - // TODO: Reinstate transitive collapse IF we can find a way to make output consistent. - // else if ( !seen.add( out.getTarget() - // .asProjectRef() ) ) - // { - // return; - // } - - - relationshipPrinter.print( out, null, new PrintWriter( sw ), labels, 0, "" ); - lines.add( sw.toString() ); - - if ( !from.equals( out.getTarget() - .asProjectRef() ) ) - { - Set newExcluded = null; - if ( out instanceof DependencyRelationship ) - { - final Set excludes = ( (DependencyRelationship) out ).getExcludes(); - if ( excludes != null && !excludes.isEmpty() ) - { - newExcluded = new HashSet(); - for ( final ProjectRef ref : excludes ) - { - if ( !RelationshipUtils.isExcluded( ref, excluded ) ) - { - newExcluded.add( ref ); - excluded.add( ref ); - } - } - } - } - - printLinks( out.getTarget() - .asProjectVersionRef(), lines, links, labels, excluded, inPath ); - - if ( newExcluded != null && !newExcluded.isEmpty() ) - { - excluded.removeAll( newExcluded ); - } - } - } - } - - inPath.pop(); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/StructurePrintingTraversal.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/StructurePrintingTraversal.java deleted file mode 100644 index 118b7103..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/StructurePrintingTraversal.java +++ /dev/null @@ -1,220 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.print; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionException; -import org.commonjava.maven.atlas.graph.traverse.RelationshipGraphTraversal; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -// TODO: Replace with getAllRelationships(), map to declaring GAV, and then printStructure based on that. -// Letting the filter in the graph view shape what's in getAllRelationships()... -public class StructurePrintingTraversal - implements RelationshipGraphTraversal -{ - - // private final Logger logger = new Logger( getClass() ); - - private final RelationshipGraphTraversal traversal; - - private final StructureRelationshipPrinter relationshipPrinter; - - private final Map>> outboundLinks = new HashMap>>(); - - public StructurePrintingTraversal() - { - this.traversal = null; - this.relationshipPrinter = new TargetRefPrinter(); - } - - public StructurePrintingTraversal( final RelationshipGraphTraversal traversal ) - { - this.traversal = traversal; - this.relationshipPrinter = new TargetRefPrinter(); - } - - public StructurePrintingTraversal( final StructureRelationshipPrinter relationshipPrinter ) - { - this.traversal = null; - this.relationshipPrinter = relationshipPrinter; - } - - public StructurePrintingTraversal( final RelationshipGraphTraversal traversal, final StructureRelationshipPrinter relationshipPrinter ) - { - this.traversal = traversal; - this.relationshipPrinter = relationshipPrinter; - } - - @Override - public boolean traverseEdge( final ProjectRelationship relationship, final List> path ) - { - if ( traversal == null || traversal.traverseEdge( relationship, path ) ) - { - List> outbound = outboundLinks.get( relationship.getDeclaring() ); - if ( outbound == null ) - { - outbound = new ArrayList>(); - outboundLinks.put( relationship.getDeclaring(), outbound ); - } - - if ( !outbound.contains( relationship ) ) - { - outbound.add( relationship ); - } - - return true; - } - - return false; - } - - public void printStructure( final ProjectVersionRef from, final Map> labels, - final PrintWriter writer ) - { - printStructure( from, null, null, " ", labels, writer ); - } - - public void printStructure( final ProjectVersionRef from, final String indent, - final Map> labels, final PrintWriter writer ) - { - printStructure( from, null, null, indent, labels, writer ); - } - - public void printStructure( final ProjectVersionRef from, final String header, final String footer, - final String indent, final Map> labels, - final PrintWriter writer ) - { - if ( header != null ) - { - writer.print( header ); - } - - writer.print( "\n" ); - writer.print( from ); - - printLinks( from, writer, indent, 1, labels, new HashSet(), new Stack() ); - writer.print( "\n" ); - - if ( footer != null ) - { - writer.print( footer ); - } - } - - private void printLinks( final ProjectVersionRef from, final PrintWriter writer, final String indent, - final int depth, final Map> labels, - final Set excluded, final Stack inPath ) - { - inPath.push( from ); - final List> outbound = outboundLinks.get( from ); - if ( outbound != null ) - { - for ( final ProjectRelationship out : outbound ) - { - final ProjectVersionRef outRef = out.getTarget() - .asProjectVersionRef(); - if ( inPath.contains( outRef ) ) - { - continue; - } - - if ( excluded.contains( outRef ) ) - { - continue; - } - - writer.append( "\n" ); - - relationshipPrinter.print( out, null, writer, labels, depth, indent ); - - if ( !from.equals( out.getTarget() - .asProjectVersionRef() ) ) - { - Set newExcluded = null; - if ( out instanceof DependencyRelationship ) - { - final Set excludes = ( (DependencyRelationship) out ).getExcludes(); - if ( excludes != null && !excludes.isEmpty() ) - { - newExcluded = new HashSet(); - for ( final ProjectRef ref : excludes ) - { - if ( !RelationshipUtils.isExcluded( ref, excluded ) ) - { - newExcluded.add( ref ); - excluded.add( ref ); - } - } - } - } - - printLinks( out.getTarget() - .asProjectVersionRef(), writer, indent, depth + 1, labels, excluded, inPath ); - - if ( newExcluded != null && !newExcluded.isEmpty() ) - { - excluded.removeAll( newExcluded ); - } - } - } - } - inPath.pop(); - } - - @Override - public boolean preCheck( final ProjectRelationship relationship, final List> path ) - { - return traversal == null || traversal.preCheck( relationship, path ); - } - - @Override - public void startTraverse( final RelationshipGraph graph ) - throws RelationshipGraphConnectionException - { - if ( traversal != null ) - { - traversal.startTraverse( graph ); - } - } - - @Override - public void endTraverse( final RelationshipGraph graph ) - throws RelationshipGraphConnectionException - { - if ( traversal != null ) - { - traversal.endTraverse( graph ); - } - } - - @Override - public void edgeTraversed( final ProjectRelationship relationship, final List> path ) - { - if ( traversal != null ) - { - traversal.edgeTraversed( relationship, path ); - } - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/StructureRelationshipPrinter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/StructureRelationshipPrinter.java deleted file mode 100644 index 0db660dc..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/StructureRelationshipPrinter.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.print; - -import java.io.PrintWriter; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public interface StructureRelationshipPrinter -{ - void print( ProjectRelationship relationship, ProjectVersionRef targetOverride, PrintWriter writer, - Map> labels, int depth, String indent ); - - void printProjectVersionRef( ProjectVersionRef targetArtifact, PrintWriter writer, String targetSuffix, - Map> labels, Set localLabels ); -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/TargetRefPrinter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/TargetRefPrinter.java deleted file mode 100644 index ae5ec198..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/TargetRefPrinter.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.print; - -import java.io.PrintWriter; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public final class TargetRefPrinter - implements StructureRelationshipPrinter -{ - - @Override - public void print( final ProjectRelationship relationship, final ProjectVersionRef selectedTarget, - final PrintWriter writer, - final Map> labels, final int depth, final String indent ) - { - for ( int i = 0; i < depth; i++ ) - { - writer.print( indent ); - } - - final ProjectVersionRef originalTarget = relationship.getTarget() - .asProjectVersionRef(); - final ProjectVersionRef target = selectedTarget == null ? originalTarget : selectedTarget; - - printProjectVersionRef( target, writer, null, labels, null ); - - if ( target != originalTarget ) - { - writer.print( " [was: " ); - writer.print( originalTarget ); - writer.print( "]" ); - } - } - - @Override - public void printProjectVersionRef( final ProjectVersionRef target, final PrintWriter writer, - final String targetSuffix, - final Map> labels, final Set localLabels ) - { - writer.print( target ); - if ( targetSuffix != null ) - { - writer.print( targetSuffix ); - } - - boolean hasLabel = false; - for ( final Entry> entry : labels.entrySet() ) - { - final String label = entry.getKey(); - final Set refs = entry.getValue(); - - if ( refs.contains( target ) ) - { - if ( !hasLabel ) - { - hasLabel = true; - writer.print( " (" ); - } - else - { - writer.print( ", " ); - } - - writer.print( label ); - } - - } - - if ( hasLabel ) - { - writer.print( ')' ); - } - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/TreePrinter.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/TreePrinter.java deleted file mode 100644 index d285eeb9..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/traverse/print/TreePrinter.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.traverse.print; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; - -public class TreePrinter -{ - - // private final Logger logger = LoggerFactory.getLogger( getClass() ); - - private final StructureRelationshipPrinter relationshipPrinter; - - // private final boolean collapseTransitives; - - // private final Set seen = new HashSet(); - - private final Map selected = new HashMap(); - - public TreePrinter() - { - this.relationshipPrinter = new TargetRefPrinter(); - // this.collapseTransitives = true; - } - - public TreePrinter( final StructureRelationshipPrinter relationshipPrinter ) - { - this.relationshipPrinter = relationshipPrinter; - } - - // TODO: Reinstate transitive collapse IF we can find a way to make output consistent. - // public TreePrinter( final StructureRelationshipPrinter relationshipPrinter, final boolean collapseTransitives ) - // { - // this.relationshipPrinter = relationshipPrinter; - // this.collapseTransitives = collapseTransitives; - // } - - public void printStructure( final ProjectVersionRef from, - final Map>> links, - final Map> labels, final PrintWriter writer ) - { - printStructure( from, links, null, null, " ", labels, writer ); - } - - public void printStructure( final ProjectVersionRef from, - final Map>> links, - final String indent, - final Map> labels, final PrintWriter writer ) - { - printStructure( from, links, null, null, indent, labels, writer ); - } - - public void printStructure( final ProjectVersionRef from, - final Map>> links, - final String header, final String footer, final String indent, - final Map> labels, final PrintWriter writer ) - { - if ( header != null ) - { - writer.print( header ); - } - - writer.print( "\n" ); - relationshipPrinter.printProjectVersionRef( from, writer, null, labels, null ); - // writer.print( from ); - - printLinks( from, writer, indent, 1, links, labels, new HashSet(), new Stack() ); - writer.print( "\n" ); - - if ( footer != null ) - { - writer.print( footer ); - } - } - - private void printLinks( final ProjectVersionRef from, final PrintWriter writer, final String indent, - final int depth, final Map>> links, - final Map> labels, final Set excluded, - final Stack inPath ) - { - inPath.push( from ); - selected.put( from.asProjectRef(), from ); - - final List> outbound = links.get( from ); - if ( outbound != null ) - { - for ( final ProjectRelationship out : outbound ) - { - final ProjectVersionRef outRef = out.getTarget() - .asProjectVersionRef(); - if ( inPath.contains( outRef ) ) - { - continue; - } - - if ( excluded.contains( out.getTarget() - .asProjectVersionRef() ) ) - { - continue; - } - - // TODO: Reinstate transitive collapse IF we can find a way to make output consistent. - // else if ( collapseTransitives && !seen.add( out.getTarget() - // .asProjectRef() ) ) - // { - // return; - // } - - writer.append( "\n" ); - - final ProjectVersionRef selection = selected.get( out.getTarget() - .asProjectRef() ); - - if ( selection == null ) - { - selected.put( out.getTarget() - .asProjectRef(), selection ); - } - - relationshipPrinter.print( out, selection, writer, labels, depth, indent ); - - if ( ( selection == null || selection.equals( out.getTarget() - .asProjectVersionRef() ) ) - && !from.equals( out.getTarget() - .asProjectVersionRef() ) ) - { - Set newExcluded = null; - if ( out instanceof DependencyRelationship ) - { - final Set excludes = ( (DependencyRelationship) out ).getExcludes(); - if ( excludes != null && !excludes.isEmpty() ) - { - newExcluded = new HashSet(); - for ( final ProjectRef ref : excludes ) - { - if ( !RelationshipUtils.isExcluded( ref, excluded ) ) - { - newExcluded.add( ref ); - excluded.add( ref ); - } - } - } - } - - printLinks( out.getTarget() - .asProjectVersionRef(), writer, indent, depth + 1, links, labels, excluded, inPath ); - - if ( newExcluded != null && !newExcluded.isEmpty() ) - { - excluded.removeAll( newExcluded ); - } - } - } - } - - inPath.pop(); - } - -} diff --git a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/util/RelationshipUtils.java b/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/util/RelationshipUtils.java deleted file mode 100644 index 7dadd885..00000000 --- a/relationships-api/src/main/java/org/commonjava/maven/atlas/graph/util/RelationshipUtils.java +++ /dev/null @@ -1,509 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.util; - -import static org.commonjava.maven.atlas.ident.util.IdentityUtils.artifact; -import static org.commonjava.maven.atlas.ident.util.IdentityUtils.projectVersion; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.filter.AbstractAggregatingFilter; -import org.commonjava.maven.atlas.graph.filter.AbstractTypedFilter; -import org.commonjava.maven.atlas.graph.filter.AnyFilter; -import org.commonjava.maven.atlas.graph.filter.ProjectRelationshipFilter; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ExtensionRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginDependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.rel.RelationshipType; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.util.JoinString; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class RelationshipUtils -{ - - private RelationshipUtils() - { - } - - public static final URI UNKNOWN_SOURCE_URI; - - public static final URI POM_ROOT_URI; - - public static URI ANY_SOURCE_URI; - - static - { - try - { - ANY_SOURCE_URI = new URI( "any:any" ); - } - catch ( final URISyntaxException e ) - { - throw new IllegalStateException( "Cannot construct any-source URI: 'any:any'" ); - } - - try - { - UNKNOWN_SOURCE_URI = new URI( "unknown:unknown" ); - } - catch ( final URISyntaxException e ) - { - throw new IllegalStateException( "Cannot construct unknown-source URI: 'unknown:unknown'" ); - } - - try - { - POM_ROOT_URI = new URI( "pom:root" ); - } - catch ( final URISyntaxException e ) - { - throw new IllegalStateException( "Cannot construct pom-root URI: 'pom:root'" ); - } - } - - public static boolean isExcluded( final ProjectRef ref, final Collection excludes ) - { - if ( excludes == null || excludes.isEmpty() ) - { - return false; - } - - for ( final ProjectRef ex : excludes ) - { - if ( ex == null ) - { - continue; - } - - if ( ex.matches( ref ) ) - { - return true; - } - } - - return false; - } - - public static Map>> mapByDeclaring( final Collection> relationships ) - { - final Logger logger = LoggerFactory.getLogger( RelationshipUtils.class ); - logger.debug( "Mapping {} relationships by declaring GAV:\n\n {}\n\n", relationships.size(), new JoinString( "\n ", relationships ) ); - final Map>> result = new HashMap>>(); - for ( final ProjectRelationship rel : relationships ) - { - final ProjectVersionRef declaring = rel.getDeclaring(); - List> outbound = result.get( declaring ); - if ( outbound == null ) - { - outbound = new ArrayList>(); - result.put( rel.getDeclaring(), outbound ); - } - - if ( !outbound.contains( rel ) ) - { - outbound.add( rel ); - } - } - - return result; - - } - - public static URI profileLocation( final String profile ) - { - if ( profile == null || profile.trim() - .length() < 1 ) - { - return POM_ROOT_URI; - } - - try - { - return new URI( "pom:profile:" + profile ); - } - catch ( final URISyntaxException e ) - { - throw new IllegalStateException( "Cannot construct pom-profile URI: 'pom:profile:" + profile + "'" ); - } - } - - public static void filterTerminalParents( final Collection> rels ) - { - for ( final Iterator> it = rels.iterator(); it.hasNext(); ) - { - final ProjectRelationship rel = it.next(); - if ( ( rel instanceof ParentRelationship ) && ( (ParentRelationship) rel ).isTerminus() ) - { - it.remove(); - } - } - } - - public static void filter( final Set> rels, final RelationshipType... types ) - { - if ( rels == null || rels.isEmpty() ) - { - return; - } - - if ( types == null || types.length < 1 ) - { - return; - } - - Arrays.sort( types ); - for ( final Iterator> iterator = rels.iterator(); iterator.hasNext(); ) - { - final ProjectRelationship rel = iterator.next(); - if ( Arrays.binarySearch( types, rel.getType() ) < 0 ) - { - iterator.remove(); - } - } - } - - public static void filter( final Set> rels, final ProjectRelationshipFilter filter ) - { - if ( filter == null || filter instanceof AnyFilter ) - { - return; - } - - if ( rels == null || rels.isEmpty() ) - { - return; - } - - for ( final Iterator> iterator = rels.iterator(); iterator.hasNext(); ) - { - final ProjectRelationship rel = iterator.next(); - if ( !filter.accept( rel ) ) - { - iterator.remove(); - } - } - } - - public static Set declarers( final ProjectRelationship... relationships ) - { - return declarers( Arrays.asList( relationships ) ); - } - - public static Set declarers( final Collection> relationships ) - { - final Set results = new HashSet(); - for ( final ProjectRelationship rel : relationships ) - { - results.add( rel.getDeclaring() ); - } - - return results; - } - - public static Set targets( final ProjectRelationship... relationships ) - { - return targets( Arrays.asList( relationships ) ); - } - - public static Set targets( final Collection> relationships ) - { - if ( relationships == null ) - { - return null; - } - - final Set results = new HashSet(); - for ( final ProjectRelationship rel : relationships ) - { - results.add( rel.getTarget() ); - } - - return results; - } - - public static Set gavs( final ProjectRelationship... relationships ) - { - return gavs( Arrays.asList( relationships ) ); - } - - public static Set gavs( final Collection> relationships ) - { - final Set results = new HashSet(); - for ( final ProjectRelationship rel : relationships ) - { - results.add( rel.getDeclaring() - .asProjectVersionRef() ); - - results.add( rel.getTarget() - .asProjectVersionRef() ); - } - - return results; - } - - public static ExtensionRelationship extension( final URI source, final URI pomLocation, - final ProjectVersionRef owner, final String groupId, - final String artifactId, - final String version, final int index ) - throws InvalidVersionSpecificationException - { - return new ExtensionRelationship( source, pomLocation, owner, projectVersion( groupId, artifactId, version ), - index ); - } - - public static PluginRelationship plugin( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, - final String artifactId, final String version, final int index ) - throws InvalidVersionSpecificationException - { - return plugin( source, pomLocation, owner, groupId, artifactId, version, index, false ); - } - - public static PluginRelationship plugin( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, - final String artifactId, final String version, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginRelationship( source, pomLocation, owner, projectVersion( groupId, artifactId, version ), index, managed ); - } - - public static PluginRelationship plugin( final URI source, final URI pomLocation, final ProjectVersionRef owner, final ProjectVersionRef plugin, - final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginRelationship( source, pomLocation, owner, plugin, index, managed ); - } - - public static PluginRelationship plugin( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, - final String version, final int index ) - throws InvalidVersionSpecificationException - { - return plugin( source, owner, groupId, artifactId, version, index, false ); - } - - public static PluginRelationship plugin( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, - final String version, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginRelationship( source, owner, projectVersion( groupId, artifactId, version ), index, managed ); - } - - public static PluginRelationship plugin( final URI source, final ProjectVersionRef owner, final ProjectVersionRef plugin, final int index, - final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginRelationship( source, owner, plugin, index, managed ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final ProjectVersionRef owner, final ProjectRef plugin, - final String groupId, final String artifactId, final String version, final int index ) - throws InvalidVersionSpecificationException - { - return pluginDependency( source, owner, plugin, groupId, artifactId, version, null, null, index, false ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final ProjectVersionRef owner, final ProjectRef plugin, - final String groupId, final String artifactId, final String version, - final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return pluginDependency( source, owner, plugin, groupId, artifactId, version, null, null, index, managed ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final ProjectVersionRef owner, final ProjectRef plugin, - final String groupId, final String artifactId, final String version, - final String type, final String classifier, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginDependencyRelationship( source, owner, plugin, artifact( groupId, artifactId, version, type, classifier, false ), index, - managed ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final ProjectVersionRef owner, final ProjectRef plugin, - final ProjectVersionRef dep, final String type, final String classifier, - final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginDependencyRelationship( source, owner, plugin, artifact( dep, type, classifier, false ), index, managed ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectRef plugin, final String groupId, final String artifactId, - final String version, final int index ) - throws InvalidVersionSpecificationException - { - return pluginDependency( source, pomLocation, owner, plugin, groupId, artifactId, version, null, null, index, false ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectRef plugin, final String groupId, final String artifactId, - final String version, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return pluginDependency( source, pomLocation, owner, plugin, groupId, artifactId, version, null, null, index, managed ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectRef plugin, final String groupId, final String artifactId, - final String version, final String type, final String classifier, final int index, - final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginDependencyRelationship( source, pomLocation, owner, plugin, - artifact( groupId, artifactId, version, type, classifier, false ), index, managed ); - } - - public static PluginDependencyRelationship pluginDependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectRef plugin, final ProjectVersionRef dep, final String type, - final String classifier, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new PluginDependencyRelationship( source, pomLocation, owner, plugin, artifact( dep, type, classifier, false ), index, managed ); - } - - public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, - final String version, final int index ) - throws InvalidVersionSpecificationException - { - return dependency( source, owner, groupId, artifactId, version, null, null, false, null, index, false ); - } - - public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final ProjectVersionRef dep, final int index ) - throws InvalidVersionSpecificationException - { - return dependency( source, owner, dep, null, null, false, null, index, false ); - } - - public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, - final String version, final DependencyScope scope, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return dependency( source, owner, groupId, artifactId, version, null, null, false, scope, index, managed ); - } - - public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final ProjectVersionRef dep, - final DependencyScope scope, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new DependencyRelationship( source, owner, artifact( dep, null, null, false ), scope, index, managed ); - } - - public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final String groupId, final String artifactId, - final String version, final String type, final String classifier, final boolean optional, - final DependencyScope scope, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new DependencyRelationship( source, owner, artifact( groupId, artifactId, version, type, classifier, optional ), null, index, false ); - } - - public static DependencyRelationship dependency( final URI source, final ProjectVersionRef owner, final ProjectVersionRef dep, final String type, - final String classifier, final boolean optional, final DependencyScope scope, final int index, - final boolean managed ) - throws InvalidVersionSpecificationException - { - return new DependencyRelationship( source, owner, artifact( dep, type, classifier, optional ), null, index, false ); - } - - public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, - final String artifactId, final String version, final int index ) - throws InvalidVersionSpecificationException - { - return dependency( source, pomLocation, owner, groupId, artifactId, version, null, null, false, null, index, false ); - } - - public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectVersionRef dep, final int index ) - throws InvalidVersionSpecificationException - { - return dependency( source, pomLocation, owner, dep, null, null, false, null, index, false ); - } - - public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, - final String artifactId, final String version, final DependencyScope scope, final int index, - final boolean managed ) - throws InvalidVersionSpecificationException - { - return dependency( source, pomLocation, owner, groupId, artifactId, version, null, null, false, scope, index, managed ); - } - - public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectVersionRef dep, final DependencyScope scope, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new DependencyRelationship( source, pomLocation, owner, artifact( dep, null, null, false ), scope, index, managed ); - } - - public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, final String groupId, - final String artifactId, final String version, final String type, final String classifier, - final boolean optional, final DependencyScope scope, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new DependencyRelationship( source, pomLocation, owner, artifact( groupId, artifactId, version, type, classifier, optional ), null, - index, false ); - } - - public static DependencyRelationship dependency( final URI source, final URI pomLocation, final ProjectVersionRef owner, - final ProjectVersionRef dep, final String type, final String classifier, final boolean optional, - final DependencyScope scope, final int index, final boolean managed ) - throws InvalidVersionSpecificationException - { - return new DependencyRelationship( source, pomLocation, owner, artifact( dep, type, classifier, optional ), null, index, false ); - } - - public static Set getRelationshipTypes( final ProjectRelationshipFilter filter ) - { - if ( filter == null ) - { - return new HashSet( Arrays.asList( RelationshipType.values() ) ); - } - - final Set result = new HashSet(); - - if ( filter instanceof AbstractTypedFilter ) - { - final AbstractTypedFilter typedFilter = (AbstractTypedFilter) filter; - result.addAll( typedFilter.getRelationshipTypes() ); - result.addAll( typedFilter.getDescendantRelationshipTypes() ); - } - else if ( filter instanceof AbstractAggregatingFilter ) - { - final List filters = ( (AbstractAggregatingFilter) filter ).getFilters(); - - for ( final ProjectRelationshipFilter f : filters ) - { - result.addAll( getRelationshipTypes( f ) ); - } - } - else - { - result.addAll( Arrays.asList( RelationshipType.values() ) ); - } - - return result; - } - -} diff --git a/relationships-api/src/site/site.xml b/relationships-api/src/site/site.xml index 92932c60..6214a864 100644 --- a/relationships-api/src/site/site.xml +++ b/relationships-api/src/site/site.xml @@ -1,13 +1,20 @@ result = mapper.readValue( json, ProjectRelationship.class ); + + assertThat( (ParentRelationship) result, equalTo( rel ) ); + } + + @Test + public void roundTrip_ParentRelationship() + throws Exception + { + ParentRelationship rel = new SimpleParentRelationship( URI.create( "some:test:location" ), + new SimpleProjectVersionRef( "org.foo", "bar", "1" ), + new SimpleProjectVersionRef( "org.foo", "parent", "1001" ) ); + + String json = mapper.writeValueAsString( rel ); + System.out.println( json ); + + ProjectRelationship result = mapper.readValue( json, ProjectRelationship.class ); + + assertThat( (ParentRelationship) result, equalTo( rel ) ); + } + + @Test + public void roundTrip_SimpleConcreteDependency() + throws Exception + { + DependencyRelationship rel = + new SimpleDependencyRelationship( URI.create( "some:test:location" ), RelationshipConstants.POM_ROOT_URI, + new SimpleProjectVersionRef( "org.foo", "bar", "1" ), + new SimpleProjectVersionRef( "org.foo", "dep", "1.1" ).asJarArtifact(), + DependencyScope.compile, 0, false, false, false ); + + String json = mapper.writeValueAsString( rel ); + System.out.println( json ); + + ProjectRelationship result = mapper.readValue( json, ProjectRelationship.class ); + + assertThat( (DependencyRelationship) result, equalTo( rel ) ); + } +} diff --git a/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/ParentRelationshipTest.java b/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/ParentRelationshipTest.java new file mode 100644 index 00000000..2d51d616 --- /dev/null +++ b/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/ParentRelationshipTest.java @@ -0,0 +1,69 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.commonjava.atlas.maven.graph.rel.ParentRelationship; +import org.commonjava.atlas.maven.graph.rel.SimpleParentRelationship; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.ref.SimpleProjectVersionRef; +import org.commonjava.atlas.maven.ident.util.VersionUtils; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; + +public class ParentRelationshipTest +{ + + @Rule + public TestName naming = new TestName(); + + private URI testURI() + throws URISyntaxException + { + return new URI( "test:repo:" + naming.getMethodName() ); + } + + @Test + public void cloneToDifferentProject() + throws InvalidVersionSpecificationException, URISyntaxException + { + final ProjectVersionRef projectRef = + new SimpleProjectVersionRef( "org.foo", "foobar", VersionUtils.createSingleVersion( "1.0" ) ); + + final ProjectVersionRef project2Ref = + new SimpleProjectVersionRef( "org.foo", "footoo", VersionUtils.createSingleVersion( "1.0" ) ); + + final ProjectVersionRef parentRef = + new SimpleProjectVersionRef( "org.foo", "foobar-parent", VersionUtils.createSingleVersion( "1" ) ); + + final URI source = testURI(); + final ParentRelationship pr = new SimpleParentRelationship( source, projectRef, parentRef ); + final ParentRelationship pr2 = (ParentRelationship) pr.cloneFor( project2Ref ); + + assertThat( pr.getDeclaring(), equalTo( projectRef ) ); + assertThat( pr2.getDeclaring(), equalTo( project2Ref ) ); + assertThat( pr.getTarget(), equalTo( parentRef ) ); + assertThat( pr2.getTarget(), equalTo( parentRef ) ); + } + +} diff --git a/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/RelationshipComparatorTest.java b/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/RelationshipComparatorTest.java new file mode 100644 index 00000000..66be6764 --- /dev/null +++ b/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/RelationshipComparatorTest.java @@ -0,0 +1,66 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import static org.commonjava.atlas.maven.graph.rel.RelationshipConstants.POM_ROOT_URI; +import static org.commonjava.atlas.maven.graph.util.RelationshipUtils.dependency; +import static org.commonjava.atlas.maven.ident.util.IdentityUtils.projectVersion; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import org.commonjava.atlas.maven.graph.rel.DependencyRelationship; +import org.commonjava.atlas.maven.graph.rel.RelationshipComparator; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.junit.Test; + +public class RelationshipComparatorTest +{ + + /** + * Tests the transitivity of the compare mathod, i.e. if A < B and B < C, then also A < C. + * The test creates 4 projects (W, X, Y and Z) and 3 relationships: + *
+     * A = W depends on X
+     * B = X depends on Y
+     * C = Y depends on Z
+     * 
+ * + * Then it confirms that A < B and B < C. The last step is to test if A < C. + */ + @Test + public void testCompareTransitivity() + { + final ProjectVersionRef nodeW = projectVersion( "w", "w", "1.0" ); + final ProjectVersionRef nodeX = projectVersion( "x", "x", "1.0" ); + final ProjectVersionRef nodeY = projectVersion( "y", "y", "1.0" ); + final ProjectVersionRef nodeZ = projectVersion( "z", "z", "1.0" ); + + DependencyRelationship relA = dependency( POM_ROOT_URI, nodeW, nodeX, 0, false, false ); + DependencyRelationship relB = dependency( POM_ROOT_URI, nodeX, nodeY, 0, false, false ); + DependencyRelationship relC = dependency( POM_ROOT_URI, nodeY, nodeZ, 0, false, false ); + + assertThat( "relA < relB must be true to perform the test", + RelationshipComparator.INSTANCE.compare( relA, relB ), equalTo( -1 ) ); + assertThat( "relB < relC must be true to perform the test", + RelationshipComparator.INSTANCE.compare( relB, relC ), equalTo( -1 ) ); + + int compare = RelationshipComparator.INSTANCE.compare( relA, relC ); + compare = ((Float) Math.signum( compare )).intValue(); + assertThat( "relA < relC must be true because relA < relB and relB < relC, but it is not", + compare, equalTo( -1 ) ); + } + +} diff --git a/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/RelationshipPathComparatorTest.java b/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/RelationshipPathComparatorTest.java new file mode 100644 index 00000000..3948747a --- /dev/null +++ b/relationships-api/src/test/java/org/commonjava/atlas/maven/graph/rel/RelationshipPathComparatorTest.java @@ -0,0 +1,85 @@ +/** + * Copyright (C) 2012-2022 Red Hat, Inc. (nos-devel@redhat.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.commonjava.atlas.maven.graph.rel; + +import static org.commonjava.atlas.maven.graph.util.RelationshipUtils.dependency; +import static org.commonjava.atlas.maven.ident.util.IdentityUtils.projectVersion; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.commonjava.atlas.maven.graph.rel.ProjectRelationship; +import org.commonjava.atlas.maven.graph.rel.RelationshipPathComparator; +import org.commonjava.atlas.maven.graph.rel.SimpleParentRelationship; +import org.commonjava.atlas.maven.ident.ref.ProjectVersionRef; +import org.commonjava.atlas.maven.ident.version.InvalidVersionSpecificationException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; + +public class RelationshipPathComparatorTest +{ + + @Rule + public TestName naming = new TestName(); + + private URI testURI() + throws URISyntaxException + { + return new URI( "test:repo:" + naming.getMethodName() ); + } + + @Test + public void sortParentDependencyPathAheadOfDirectDependency() + throws InvalidVersionSpecificationException, URISyntaxException + { + final List>> paths = new ArrayList>>(); + + List> rels = new ArrayList>(); + + final ProjectVersionRef root = projectVersion( "group.id", "my-artifact", "1.0" ); + + final ProjectVersionRef dep = projectVersion( "org.group", "dep-1", "1.0" ); + + final URI source = testURI(); + rels.add( dependency( source, root, dep, 0, false, false ) ); + rels.add( dependency( source, dep, projectVersion( "org.foo", "bar", "1.0" ), 0, false, false ) ); + + paths.add( rels ); + + rels = new ArrayList>(); + + final ProjectVersionRef parent = projectVersion( "group.id", "parent", "1" ); + + rels.add( new SimpleParentRelationship( source, root, parent ) ); + rels.add( dependency( source, parent, "org.foo", "bar", "1.1.1", 0, false, false ) ); + + paths.add( rels ); + + Collections.sort( paths, RelationshipPathComparator.INSTANCE ); + + final List> result = paths.get( 0 ); + final ProjectRelationship firstResult = result.get( 0 ); + + assertThat( ( firstResult instanceof SimpleParentRelationship ), equalTo( true ) ); + } + +} diff --git a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/EProjectRelationshipsTest.java b/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/EProjectRelationshipsTest.java deleted file mode 100644 index 80f71371..00000000 --- a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/EProjectRelationshipsTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.model.EProjectDirectRelationships; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ExtensionRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -public class EProjectRelationshipsTest -{ - - @Rule - public TestName naming = new TestName(); - - private URI testURI() - throws URISyntaxException - { - return new URI( "test:repo:" + naming.getMethodName() ); - } - - @Test - public void builderWith2Dependencies2PluginsAParentAndAnExtension() - throws InvalidVersionSpecificationException, URISyntaxException - { - final ProjectVersionRef p = new ProjectVersionRef( "org.apache.maven", "maven-core", "3.0.3" ); - final URI source = testURI(); - - final EProjectDirectRelationships.Builder prb = new EProjectDirectRelationships.Builder( source, p ); - - final ProjectVersionRef parent = new ProjectVersionRef( "org.apache.maven", "maven", "3.0.3" ); - final ParentRelationship parentRel = new ParentRelationship( source, p, parent ); - - int idx = 0; - int pidx = 0; - final DependencyRelationship papi = - new DependencyRelationship( source, p, new ArtifactRef( "org.apache.maven", "maven-plugin-api", "3.0.3", - null, null, false ), DependencyScope.compile, - idx++, false ); - final DependencyRelationship art = - new DependencyRelationship( source, p, new ArtifactRef( "org.apache.maven", "maven-artifact", "3.0.3", - null, null, false ), DependencyScope.compile, - idx++, false ); - final PluginRelationship jarp = - new PluginRelationship( source, p, new ProjectVersionRef( "org.apache.maven.plugins", "maven-jar-plugin", - "2.2" ), pidx++, false ); - final PluginRelationship comp = - new PluginRelationship( source, p, new ProjectVersionRef( "org.apache.maven.plugins", - "maven-compiler-plugin", "2.3.2" ), pidx++, false ); - final ExtensionRelationship wag = - new ExtensionRelationship( source, p, new ProjectVersionRef( "org.apache.maven.wagon", - "wagon-provider-webdav", "1.0" ), 0 ); - - prb.withParent( parentRel ); - prb.withDependencies( papi, art ); - prb.withPlugins( jarp, comp ); - prb.withExtensions( wag ); - - final EProjectDirectRelationships rels = prb.build(); - - final Set> all = rels.getAllRelationships(); - - assertThat( all.size(), equalTo( 6 ) ); - - assertThat( all.contains( parentRel ), equalTo( true ) ); - assertThat( all.contains( papi ), equalTo( true ) ); - assertThat( all.contains( art ), equalTo( true ) ); - assertThat( all.contains( jarp ), equalTo( true ) ); - assertThat( all.contains( comp ), equalTo( true ) ); - assertThat( all.contains( wag ), equalTo( true ) ); - } - -} diff --git a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/filter/DependencyFilterTest.java b/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/filter/DependencyFilterTest.java deleted file mode 100644 index 2991d90e..00000000 --- a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/filter/DependencyFilterTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.filter; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -public class DependencyFilterTest -{ - - @Rule - public TestName naming = new TestName(); - - private URI testURI() - throws URISyntaxException - { - return new URI( "test:repo:" + naming.getMethodName() ); - } - - @Test - public void rejectTestScopeForRuntimeFilter() - throws Exception - { - final DependencyFilter filter = new DependencyFilter( DependencyScope.runtime ); - final DependencyRelationship rel = - new DependencyRelationship( testURI(), new ProjectVersionRef( "g", "a", "1" ), - new ArtifactRef( "g", "b", "2", "jar", null, false ), DependencyScope.test, 0, - false ); - - assertThat( filter.accept( rel ), equalTo( false ) ); - } - -} diff --git a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/rel/ParentRelationshipTest.java b/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/rel/ParentRelationshipTest.java deleted file mode 100644 index 1a11f52f..00000000 --- a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/rel/ParentRelationshipTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.commonjava.maven.atlas.ident.version.VersionUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -public class ParentRelationshipTest -{ - - @Rule - public TestName naming = new TestName(); - - private URI testURI() - throws URISyntaxException - { - return new URI( "test:repo:" + naming.getMethodName() ); - } - - @Test - public void cloneToDifferentProject() - throws InvalidVersionSpecificationException, URISyntaxException - { - final ProjectVersionRef projectRef = - new ProjectVersionRef( "org.foo", "foobar", VersionUtils.createSingleVersion( "1.0" ) ); - - final ProjectVersionRef project2Ref = - new ProjectVersionRef( "org.foo", "footoo", VersionUtils.createSingleVersion( "1.0" ) ); - - final ProjectVersionRef parentRef = - new ProjectVersionRef( "org.foo", "foobar-parent", VersionUtils.createSingleVersion( "1" ) ); - - final URI source = testURI(); - final ParentRelationship pr = new ParentRelationship( source, projectRef, parentRef ); - final ParentRelationship pr2 = (ParentRelationship) pr.cloneFor( project2Ref ); - - assertThat( pr.getDeclaring(), equalTo( projectRef ) ); - assertThat( pr2.getDeclaring(), equalTo( project2Ref ) ); - assertThat( pr.getTarget(), equalTo( parentRef ) ); - assertThat( pr2.getTarget(), equalTo( parentRef ) ); - } - -} diff --git a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/rel/RelationshipPathComparatorTest.java b/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/rel/RelationshipPathComparatorTest.java deleted file mode 100644 index cdc05f9d..00000000 --- a/relationships-api/src/test/java/org/commonjava/maven/atlas/graph/rel/RelationshipPathComparatorTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.graph.rel; - -import static org.commonjava.maven.atlas.graph.util.RelationshipUtils.dependency; -import static org.commonjava.maven.atlas.ident.util.IdentityUtils.projectVersion; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.ident.version.InvalidVersionSpecificationException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -public class RelationshipPathComparatorTest -{ - - @Rule - public TestName naming = new TestName(); - - private URI testURI() - throws URISyntaxException - { - return new URI( "test:repo:" + naming.getMethodName() ); - } - - @Test - public void sortParentDependencyPathAheadOfDirectDependency() - throws InvalidVersionSpecificationException, URISyntaxException - { - final List>> paths = new ArrayList>>(); - - List> rels = new ArrayList>(); - - final ProjectVersionRef root = projectVersion( "group.id", "my-artifact", "1.0" ); - - final ProjectVersionRef dep = projectVersion( "org.group", "dep-1", "1.0" ); - - final URI source = testURI(); - rels.add( dependency( source, root, dep, 0 ) ); - rels.add( dependency( source, dep, projectVersion( "org.foo", "bar", "1.0" ), 0 ) ); - - paths.add( rels ); - - rels = new ArrayList>(); - - final ProjectVersionRef parent = projectVersion( "group.id", "parent", "1" ); - - rels.add( new ParentRelationship( source, root, parent ) ); - rels.add( dependency( source, parent, "org.foo", "bar", "1.1.1", 0 ) ); - - paths.add( rels ); - - Collections.sort( paths, RelationshipPathComparator.INSTANCE ); - - final List> result = paths.get( 0 ); - final ProjectRelationship firstResult = result.get( 0 ); - - assertThat( ( firstResult instanceof ParentRelationship ), equalTo( true ) ); - } - -} diff --git a/tck/pom.xml b/tck/pom.xml deleted file mode 100644 index 8bff16b4..00000000 --- a/tck/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - 4.0.0 - - - org.commonjava.maven.atlas - atlas-parent - 0.12.0-EXP-SNAPSHOT - - - atlas-drivers-tck - - Atlas :: Maven Project-Graph :: TCK - - - - org.commonjava.maven.atlas - atlas-relationships-api - - - junit - junit - compile - - - diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/AbstractSPI_TCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/AbstractSPI_TCK.java deleted file mode 100644 index eca812d0..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/AbstractSPI_TCK.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Date; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.RelationshipGraphFactory; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnectionFactory; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TestName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractSPI_TCK -{ - - @Rule - public TestName naming = new TestName(); - - protected URI sourceURI() - throws URISyntaxException - { - return new URI( "test:repo:" + naming.getMethodName() ); - } - - protected RelationshipGraph simpleGraph( final ProjectVersionRef... roots ) - throws Exception - { - final ViewParams params = new ViewParams( newWorkspaceId(), roots ); - params.addActiveSource( sourceURI() ); - - return graphFactory().open( params, true ); - } - - protected String newWorkspaceId() - { - return "Test-" + System.currentTimeMillis(); - } - - protected final Logger logger = LoggerFactory.getLogger( getClass() ); - - protected abstract RelationshipGraphConnectionFactory connectionFactory() - throws Exception; - - private RelationshipGraphFactory graphFactory; - - protected final RelationshipGraphFactory graphFactory() - throws Exception - { - if ( graphFactory == null ) - { - graphFactory = new RelationshipGraphFactory( connectionFactory() ); - } - - return graphFactory; - } - - private long start; - - @Before - public void printStart() - { - start = System.currentTimeMillis(); - System.out.printf( "***START [%s#%s] (%s)\n\n", naming.getClass(), naming.getMethodName(), new Date().toString() ); - } - - @After - public void printEnd() - throws Exception - { - System.out.printf( "\n\n***END [%s#%s] - %sms (%s)\n", naming.getClass(), naming.getMethodName(), ( System.currentTimeMillis() - start ), - new Date().toString() ); - - if ( graphFactory != null ) - { - graphFactory.close(); - } - - connectionFactory().close(); - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/CycleDetectionTCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/CycleDetectionTCK.java deleted file mode 100644 index ba49cd2f..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/CycleDetectionTCK.java +++ /dev/null @@ -1,257 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph; - -import static org.apache.commons.lang.StringUtils.join; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.util.HashSet; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.DependencyFilter; -import org.commonjava.maven.atlas.graph.model.EProjectCycle; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.junit.Test; - -public abstract class CycleDetectionTCK - extends AbstractSPI_TCK -{ - - @Test - // @Ignore - public void introducesCycleCheckWithExistingGraph() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef dep = new ProjectVersionRef( "org.other", "dep", "1.0" ); - final ProjectVersionRef dep2 = new ProjectVersionRef( "org.other", "dep2", "1.0" ); - - final RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - graph.storeRelationships( new DependencyRelationship( source, project, new ArtifactRef( dep, null, null, false ), null, 0, false ), - new DependencyRelationship( source, dep, new ArtifactRef( dep2, null, null, false ), null, 0, false ) ); - - final boolean introduces = graph.introducesCycle( new DependencyRelationship( source, dep, new ArtifactRef( project, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - assertThat( introduces, equalTo( true ) ); - } - - @Test - // @Ignore - public void buildGraphWithCycleBackToRootAndRetrieveCycle() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef dep = new ProjectVersionRef( "org.other", "dep", "1.0" ); - final ProjectVersionRef dep2 = new ProjectVersionRef( "org.other", "dep2", "1.0" ); - - final RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - graph.storeRelationships( new DependencyRelationship( source, project, dep.asJarArtifact(), null, 0, false ), - new DependencyRelationship( source, dep, dep2.asJarArtifact(), null, 0, false ), - new DependencyRelationship( source, dep2, project.asJarArtifact(), null, 0, false ) ); - /* @formatter:on */ - - // final EProjectGraph graph = getManager().getGraph( session, project ); - - final Set cycles = graph.getCycles(); - System.out.println( "Cycles:\n\n" + join( cycles, "\n" ) ); - assertThat( cycles.size(), equalTo( 1 ) ); - - for ( final EProjectCycle cycle : cycles ) - { - final Set projects = cycle.getAllParticipatingProjects(); - assertThat( projects.contains( project ), equalTo( true ) ); - assertThat( projects.contains( dep ), equalTo( true ) ); - assertThat( projects.contains( dep2 ), equalTo( true ) ); - } - } - - @Test - // @Ignore - public void buildGraphWithCycleBetweenDepLevelsAndRetrieveCycle() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef dep = new ProjectVersionRef( "org.other", "dep", "1.0" ); - final ProjectVersionRef dep2 = new ProjectVersionRef( "org.other", "dep2", "1.0" ); - - final RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - final Set> rejected = graph.storeRelationships( - new DependencyRelationship( source, project, new ArtifactRef( dep, null, null, false ), null, 0, false ), - new DependencyRelationship( source, dep, new ArtifactRef( dep2, null, null, false ), null, 0, false ), - new DependencyRelationship( source, dep2, new ArtifactRef( dep, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - assertThat( rejected, notNullValue() ); - - // System.out.println( "Rejects: " + rejected ); - // - // assertThat( rejected.size(), equalTo( 2 ) ); - // final ProjectRelationship reject = rejected.iterator() - // .next(); - // assertThat( reject.getDeclaring(), equalTo( dep2 ) ); - // assertThat( reject.getTarget() - // .asProjectVersionRef(), equalTo( dep ) ); - - final Set cycles = graph.getCycles(); - System.out.println( "Cycles:\n\n" + join( cycles, "\n" ) ); - assertThat( cycles.size(), equalTo( 1 ) ); - - for ( final EProjectCycle cycle : cycles ) - { - final Set projects = cycle.getAllParticipatingProjects(); - assertThat( projects.contains( project ), equalTo( false ) ); - assertThat( projects.contains( dep ), equalTo( true ) ); - assertThat( projects.contains( dep2 ), equalTo( true ) ); - } - } - - @Test - // @Ignore - public void GB_cycleFromGraph1PresentInGraph2WhenNodeIsCrossReferenced() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef a = new ProjectVersionRef( "project", "A", "1.0" ); - final ProjectVersionRef b = new ProjectVersionRef( "project", "B", "1.0" ); - final ProjectVersionRef c = new ProjectVersionRef( "project", "C", "1.0" ); - - final ProjectVersionRef d = new ProjectVersionRef( "project", "D", "1.0" ); - final ProjectVersionRef e = new ProjectVersionRef( "project", "E", "1.0" ); - - final RelationshipGraph graph = simpleGraph( a ); - - /* @formatter:off */ - // a --> b --> c --> a - // d --> e --> c --> a --> b --> c - graph.storeRelationships( new DependencyRelationship( source, a, new ArtifactRef( b, null, null, false ), null, 0, false ), - new DependencyRelationship( source, b, new ArtifactRef( c, null, null, false ), null, 0, false ), - new DependencyRelationship( source, c, new ArtifactRef( a, null, null, false ), null, 0, false ), - new DependencyRelationship( source, d, new ArtifactRef( e, null, null, false ), null, 0, false ), - new DependencyRelationship( source, e, new ArtifactRef( c, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - final RelationshipGraph graph2 = - graphFactory().open( new ViewParams.Builder( graph.getParams() ).withRoots( d ) - .build(), false ); - - final Set cycles1 = graph.getCycles(); - System.out.println( "Graph 1 Cycles:\n\n" + join( cycles1, "\n" ) ); - - final Set cycles2 = graph2.getCycles(); - System.out.println( "Graph 2 Cycles:\n\n" + join( cycles2, "\n" ) ); - - assertThat( cycles1.size(), equalTo( 1 ) ); - assertThat( cycles2.size(), equalTo( 1 ) ); - - final Set> cycleSets = new HashSet>(); - cycleSets.add( cycles1 ); - cycleSets.add( cycles2 ); - - int i = 0; - for ( final Set cycles : cycleSets ) - { - int j = 0; - for ( final EProjectCycle cycle : cycles ) - { - final Set refs = cycle.getAllParticipatingProjects(); - assertThat( i + ", " + j + " missing A", refs.contains( a ), equalTo( true ) ); - assertThat( i + ", " + j + " missing B", refs.contains( b ), equalTo( true ) ); - assertThat( i + ", " + j + " missing C", refs.contains( c ), equalTo( true ) ); - j++; - } - i++; - } - } - - @Test - // @Ignore - public void cycleFromGraph1MissingInFilteredGraph2WhenOneRelationshipInCycleFilteredOut() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef a = new ProjectVersionRef( "project", "A", "1.0" ); - final ProjectVersionRef b = new ProjectVersionRef( "project", "B", "1.0" ); - final ProjectVersionRef c = new ProjectVersionRef( "project", "C", "1.0" ); - - final ProjectVersionRef d = new ProjectVersionRef( "project", "D", "1.0" ); - final ProjectVersionRef e = new ProjectVersionRef( "project", "E", "1.0" ); - - final RelationshipGraph graph = simpleGraph( a ); - - /* @formatter:off */ - // a --> b --> c --> a - // d --> e --> c --> a --> b --> c - graph.storeRelationships( new DependencyRelationship( source, a, new ArtifactRef( b, null, null, false ), null, 0, false ), - new DependencyRelationship( source, c, new ArtifactRef( a, null, null, false ), null, 0, false ), - new PluginRelationship( source, b, c, 0, false ), - new DependencyRelationship( source, d, new ArtifactRef( e, null, null, false ), null, 0, false ), - new DependencyRelationship( source, e, new ArtifactRef( c, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - final RelationshipGraph graph2 = - graphFactory().open( new ViewParams.Builder( graph.getParams() ).withFilter( new DependencyFilter() ) - .withRoots( d ) - .build(), false ); - - final Set cycles1 = graph.getCycles(); - System.out.println( "Graph 1 Cycles:\n\n" + join( cycles1, "\n" ) ); - - final Set cycles2 = graph2.getCycles(); - System.out.println( "Graph 2 Cycles:\n\n" + join( cycles2, "\n" ) ); - - assertThat( cycles1.size(), equalTo( 1 ) ); - assertThat( cycles2.size(), equalTo( 0 ) ); - - final Set> cycleSets = new HashSet>(); - cycleSets.add( cycles1 ); - // cycleSets.add( cycles2 ); - - int i = 0; - for ( final Set cycles : cycleSets ) - { - int j = 0; - for ( final EProjectCycle cycle : cycles ) - { - final Set refs = cycle.getAllParticipatingProjects(); - assertThat( i + ", " + j + " missing A", refs.contains( a ), equalTo( true ) ); - assertThat( i + ", " + j + " missing B", refs.contains( b ), equalTo( true ) ); - assertThat( i + ", " + j + " missing C", refs.contains( c ), equalTo( true ) ); - j++; - } - i++; - } - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/RelationshipGraphConnection_TCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/RelationshipGraphConnection_TCK.java deleted file mode 100644 index 6de11cbb..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/RelationshipGraphConnection_TCK.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.util.Set; - -import org.commonjava.maven.atlas.graph.spi.RelationshipGraphConnection; -import org.junit.Test; - -public abstract class RelationshipGraphConnection_TCK - extends AbstractSPI_TCK -{ - - @Test - public void createWorkspaceAndRetrieveById() - throws Exception - { - final String wsid = newWorkspaceId(); - final RelationshipGraphConnection connection = connectionFactory().openConnection( wsid, true ); - - System.out.println( "wsid: " + connection.getWorkspaceId() ); - - assertThat( connection, notNullValue() ); - - logger.info( "Created connection: {}", connection ); - - final RelationshipGraphConnection result = connectionFactory().openConnection( wsid, false ); - - logger.info( "Retrieved connection: {}", result ); - - assertThat( result, notNullValue() ); - assertThat( result.getWorkspaceId(), equalTo( connection.getWorkspaceId() ) ); - assertThat( result.equals( connection ), equalTo( true ) ); - } - - @Test - public void createWorkspaceAndFindInAllWorkspacesListing() - throws Exception - { - final String wsid = newWorkspaceId(); - final RelationshipGraphConnection connection = connectionFactory().openConnection( wsid, true ); - - System.out.println( "wsid: " + connection.getWorkspaceId() ); - - assertThat( connection, notNullValue() ); - - logger.info( "Created connection: {}", connection ); - - final Set all = connectionFactory().listWorkspaces(); - - logger.info( "Retrieved all workspaces: {}", all ); - - assertThat( all, notNullValue() ); - assertThat( all.size(), equalTo( 1 ) ); - assertThat( all.contains( connection.getWorkspaceId() ), equalTo( true ) ); - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/RelationshipGraphTCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/RelationshipGraphTCK.java deleted file mode 100644 index 4f637c90..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/RelationshipGraphTCK.java +++ /dev/null @@ -1,173 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.filter.DependencyFilter; -import org.commonjava.maven.atlas.graph.model.GraphPath; -import org.commonjava.maven.atlas.graph.mutate.ManagedDependencyMutator; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.ProjectRelationship; -import org.commonjava.maven.atlas.graph.traverse.AncestryTraversal; -import org.commonjava.maven.atlas.graph.traverse.TraversalType; -import org.commonjava.maven.atlas.graph.util.RelationshipUtils; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -public abstract class RelationshipGraphTCK - extends AbstractSPI_TCK -{ - - @Test - public void createPath_ReturnNullWhenTargetVersionIsAnExpression() - throws Exception - { - final ProjectVersionRef from = new ProjectVersionRef( "org.from", "project", "1.0" ); - final ProjectVersionRef to = new ProjectVersionRef( "org.to", "artifact", "${version.target}" ); - - final URI src = new URI( "test:source-uri" ); - final ProjectRelationship rel = - new DependencyRelationship( src, from, to.asArtifactRef( "jar", null ), DependencyScope.compile, 0, false ); - - final RelationshipGraph graph = simpleGraph( from ); - final GraphPath path = graph.createPath( rel ); - - assertThat( path, nullValue() ); - } - - @Test - public void storeBOMThenVerifyBomGAVPresentInView() - throws Exception - { - final URI src = sourceURI(); - final ProjectVersionRef gav = new ProjectVersionRef( "g", "a", "v" ); - - final ProjectVersionRef d1 = new ProjectVersionRef( "g", "d1", "1" ); - final ProjectVersionRef d2 = new ProjectVersionRef( "g", "d2", "2" ); - - final RelationshipGraph graph = - openGraph( new ViewParams( newWorkspaceId(), new DependencyFilter(), new ManagedDependencyMutator(), gav ), - true ); - - /* @formatter:off */ - graph.storeRelationships( - new ParentRelationship(src, gav), - new DependencyRelationship(src, gav, d1.asArtifactRef("jar", - null), DependencyScope.compile, 0, true), - new DependencyRelationship(src, gav, d2.asArtifactRef("jar", - null), DependencyScope.compile, 1, true)); - /* @formatter:on */ - - graph.containsGraph( gav ); - } - - @Test - public void connectThreeGraphsWithParentInterrelationships() - throws Exception - { - final ProjectVersionRef r = new ProjectVersionRef( "org.test", "root", "1" ); - final ProjectVersionRef p = new ProjectVersionRef( "org.test", "parent", "1.0" ); - final ProjectVersionRef c = new ProjectVersionRef( "org.test", "child", "1.0" ); - - final URI source = sourceURI(); - - final String wsid = newWorkspaceId(); - - openGraph( new ViewParams( wsid, r ), true ).storeRelationships( new ParentRelationship( source, r ) ); - - openGraph( new ViewParams( wsid, p ), true ).storeRelationships( new ParentRelationship( source, p, r ) ); - - final RelationshipGraph child = openGraph( new ViewParams( wsid, c ), true ); - - child.storeRelationships( new ParentRelationship( source, c, p ) ); - - System.out.println( "Incomplete subgraphs: " + child.getIncompleteSubgraphs() ); - System.out.flush(); - assertThat( child.isComplete(), equalTo( true ) ); - - final AncestryTraversal ancestryTraversal = new AncestryTraversal(); - child.traverse( ancestryTraversal, TraversalType.depth_first ); - - final List ancestry = ancestryTraversal.getAncestry(); - LoggerFactory.getLogger( getClass() ) - .info( "Ancestry: {}", ancestry ); - - assertThat( ancestry, notNullValue() ); - assertThat( ancestry.size(), equalTo( 3 ) ); - - final Iterator iterator = ancestry.iterator(); - assertThat( iterator.next(), equalTo( c ) ); - assertThat( iterator.next(), equalTo( p ) ); - assertThat( iterator.next(), equalTo( r ) ); - } - - @Test - public void connectThreeGraphsWithParentInterrelationships_WrongOrder() - throws Exception - { - final ProjectVersionRef r = new ProjectVersionRef( "org.test", "root", "1" ); - final ProjectVersionRef p = new ProjectVersionRef( "org.test", "parent", "1.0" ); - final ProjectVersionRef c = new ProjectVersionRef( "org.test", "child", "1.0" ); - - final URI source = sourceURI(); - - final String wsid = newWorkspaceId(); - - final RelationshipGraph child = openGraph( new ViewParams( wsid, c ), true ); - - child.storeRelationships( new ParentRelationship( source, c, p ) ); - - openGraph( new ViewParams( wsid, p ), true ).storeRelationships( new ParentRelationship( source, p, r ) ); - - openGraph( new ViewParams( wsid, r ), true ).storeRelationships( new ParentRelationship( source, r ) ); - - assertThat( child.isComplete(), equalTo( true ) ); - - final AncestryTraversal ancestryTraversal = new AncestryTraversal(); - child.traverse( ancestryTraversal, TraversalType.depth_first ); - - final List ancestry = ancestryTraversal.getAncestry(); - LoggerFactory.getLogger( getClass() ) - .info( "Ancestry: {}", ancestry ); - - assertThat( ancestry, notNullValue() ); - assertThat( ancestry.size(), equalTo( 3 ) ); - - final Iterator iterator = ancestry.iterator(); - assertThat( iterator.next(), equalTo( c ) ); - assertThat( iterator.next(), equalTo( p ) ); - assertThat( iterator.next(), equalTo( r ) ); - } - - private RelationshipGraph openGraph( final ViewParams params, final boolean create ) - throws Exception - { - final RelationshipGraph graph = - graphFactory().open( new ViewParams.Builder( params ).withActiveSources( Collections.singleton( RelationshipUtils.ANY_SOURCE_URI ) ) - .build(), create ); - return graph; - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/SubGraphSelectionTCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/SubGraphSelectionTCK.java deleted file mode 100644 index 14790112..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/SubGraphSelectionTCK.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.junit.Test; - -public abstract class SubGraphSelectionTCK - extends AbstractSPI_TCK -{ - - @Test - // @Ignore - public void selectVersionForVariableSubgraph() - throws Exception - { - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef varDep = new ProjectVersionRef( "org.other", "dep", "1.0-SNAPSHOT" ); - final ProjectVersionRef varD2 = new ProjectVersionRef( "org.other", "dep2", "1.0-SNAPSHOT" ); - final ProjectVersionRef selected = new ProjectVersionRef( varDep, "1.0-20130314.161200-1" ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - graph.storeRelationships( new DependencyRelationship( source, project, new ArtifactRef( varDep, null, null, false ), null, 0, false ), - new DependencyRelationship( source, varDep, new ArtifactRef( varD2, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - Set variables = graph.getVariableSubgraphs(); - System.out.println( "Before selection here are the variable nodes: " + variables ); - assertThat( variables.contains( varDep ), equalTo( true ) ); - - final RelationshipGraph graph2 = - graphFactory().open( new ViewParams.Builder( graph.getParams() ).withSelection( varDep.asProjectRef(), - selected ) - .build(), false ); - - // final ProjectVersionRef selDep = view.selectVersion( varDep.asProjectRef(), selected ); - // assertThat( selDep.asProjectRef(), equalTo( varDep.asProjectRef() ) ); - - variables = graph2.getVariableSubgraphs(); - System.out.println( "After selection here are the variable nodes: " + variables ); - assertThat( variables.isEmpty(), equalTo( true ) ); - - final Set incomplete = graph2.getIncompleteSubgraphs(); - System.out.println( "Checking missing subgraphs for: " + selected ); - assertThat( incomplete.contains( selected ), equalTo( true ) ); - } - - @Test - // @Ignore - public void selectVersionForVariableSubgraph_SelectionsContextualToView() - throws Exception - { - final ProjectVersionRef project = new ProjectVersionRef( "org.my", "project", "1.0" ); - final ProjectVersionRef varDep = new ProjectVersionRef( "org.other", "dep", "1.0-SNAPSHOT" ); - final ProjectVersionRef varD2 = new ProjectVersionRef( "org.other", "dep2", "1.0-SNAPSHOT" ); - final ProjectVersionRef selected = new ProjectVersionRef( varDep, "1.0-20130314.161200-1" ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( project ); - - /* @formatter:off */ - graph.storeRelationships( new DependencyRelationship( source, project, new ArtifactRef( varDep, null, null, false ), null, 0, false ), - new DependencyRelationship( source, varDep, new ArtifactRef( varD2, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - Set variables = graph.getVariableSubgraphs(); - assertThat( variables.contains( varDep ), equalTo( true ) ); - - // Select a concrete version for the session associated with the FIRST graph. - // Second graph session should remain unchanged. - final RelationshipGraph graph2 = - graphFactory().open( new ViewParams.Builder( graph.getParams() ).withSelection( varDep.asProjectRef(), - selected ) - .build(), false ); - - assertThat( graph.getParams() - .getSelection( varDep ), nullValue() ); - assertThat( graph2.getParams() - .getSelection( varDep ), equalTo( selected ) ); - - assertThat( selected.asProjectRef(), equalTo( varDep.asProjectRef() ) ); - - assertThat( selected.asProjectVersionRef() - .equals( varDep.asProjectVersionRef() ), equalTo( false ) ); - - variables = graph.getVariableSubgraphs(); - assertThat( variables.contains( varDep ), equalTo( true ) ); - - variables = graph2.getVariableSubgraphs(); - assertThat( variables.contains( varDep ), equalTo( false ) ); - - Set incomplete = graph.getIncompleteSubgraphs(); - assertThat( incomplete.contains( selected ), equalTo( false ) ); - - incomplete = graph2.getIncompleteSubgraphs(); - assertThat( incomplete.contains( selected ), equalTo( true ) ); - - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/AncestryTraversalTCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/AncestryTraversalTCK.java deleted file mode 100644 index 7cd0d92c..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/AncestryTraversalTCK.java +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph.traverse; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.util.List; -import java.util.Set; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ExtensionRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.traverse.AncestryTraversal; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.tck.graph.AbstractSPI_TCK; -import org.junit.Test; - -public abstract class AncestryTraversalTCK - extends AbstractSPI_TCK -{ - - @Test - public void traverseTwoAncestors() - throws Exception - { - final ProjectVersionRef myRef = new ProjectVersionRef( "my.group", "my-artifact", "1.0" ); - final ProjectVersionRef parentRef = new ProjectVersionRef( "my.group", "my-dad", "1" ); - final ProjectVersionRef grandRef = new ProjectVersionRef( "other.group", "grandpa", "20120821" ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( myRef ); - - graph.storeRelationships( new ParentRelationship( source, myRef, parentRef ), - new ParentRelationship( source, parentRef, grandRef ), - new ParentRelationship( source, grandRef ) ); - - final Set projects = graph.getAllProjects(); - assertThat( projects.size(), equalTo( 3 ) ); - assertThat( projects.contains( myRef ), equalTo( true ) ); - assertThat( projects.contains( parentRef ), equalTo( true ) ); - assertThat( projects.contains( grandRef ), equalTo( true ) ); - - final AncestryTraversal ancestry = new AncestryTraversal(); - graph.traverse( ancestry ); - - final List ancestorRefs = ancestry.getAncestry(); - - logger.info( "Ancestry: %s", ancestorRefs ); - - assertThat( ancestorRefs.size(), equalTo( 3 ) ); - - int idx = 0; - ProjectVersionRef ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "my.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "my-artifact" ) ); - - ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "my.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "my-dad" ) ); - - ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "other.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "grandpa" ) ); - - } - - @Test - public void traverseTwoAncestorsWithEmptyGrandParentRels() - throws Exception - { - final ProjectVersionRef myRef = new ProjectVersionRef( "my.group", "my-artifact", "1.0" ); - final ProjectVersionRef parentRef = new ProjectVersionRef( "my.group", "my-dad", "1" ); - final ProjectVersionRef grandRef = new ProjectVersionRef( "other.group", "grandpa", "20120821" ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( myRef ); - - graph.storeRelationships( new ParentRelationship( source, myRef, parentRef ), - new ParentRelationship( source, parentRef, grandRef ) ); - - final AncestryTraversal ancestry = new AncestryTraversal(); - graph.traverse( ancestry ); - - final List ancestorRefs = ancestry.getAncestry(); - - assertThat( ancestorRefs.size(), equalTo( 3 ) ); - - int idx = 0; - ProjectVersionRef ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "my.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "my-artifact" ) ); - - ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "my.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "my-dad" ) ); - - ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "other.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "grandpa" ) ); - - } - - @Test - public void traverseTwoAncestors_IgnoreNonParentRelationships() - throws Exception - { - final ProjectVersionRef myRef = new ProjectVersionRef( "my.group", "my-artifact", "1.0" ); - final ProjectVersionRef parentRef = new ProjectVersionRef( "my.group", "my-dad", "1" ); - final ProjectVersionRef grandRef = new ProjectVersionRef( "other.group", "grandpa", "20120821" ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( myRef ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, myRef, parentRef ), - new DependencyRelationship( source, myRef, new ArtifactRef( new ProjectVersionRef( "some.group", "foo", "1.0" ), null, null, false ), null, 0, false ), - new DependencyRelationship( source, myRef, new ArtifactRef( new ProjectVersionRef( "some.group", "bar", "1.2.1" ), null, null, false ), null, 1, false ), - new PluginRelationship( source, myRef, new ProjectVersionRef( "org.apache.maven.plugins", "maven-compiler-plugin", "2.5.1" ), 0, false ), - new PluginRelationship( source, myRef, new ProjectVersionRef( "org.apache.maven.plugins","maven-jar-plugin", "2.2" ), 1, false ), - new ExtensionRelationship( source, myRef, new ProjectVersionRef( "org.apache.maven.plugins", "maven-compiler-plugin", "2.5.1" ), 0 ), - new ParentRelationship( source, parentRef, grandRef ), - new DependencyRelationship( source, parentRef, new ProjectVersionRef( "other.group", "utils", "3-1" ).asJarArtifact(), null, 0, false ) - ); - /* @formatter:on */ - - final AncestryTraversal ancestry = new AncestryTraversal(); - graph.traverse( ancestry ); - - final List ancestorRefs = ancestry.getAncestry(); - - assertThat( ancestorRefs.size(), equalTo( 3 ) ); - - int idx = 0; - ProjectVersionRef ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "my.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "my-artifact" ) ); - - ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "my.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "my-dad" ) ); - - ref = ancestorRefs.get( idx++ ); - - assertThat( ref.getGroupId(), equalTo( "other.group" ) ); - assertThat( ref.getArtifactId(), equalTo( "grandpa" ) ); - - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/BuildOrderTraversalTCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/BuildOrderTraversalTCK.java deleted file mode 100644 index c10d19e0..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/BuildOrderTraversalTCK.java +++ /dev/null @@ -1,316 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph.traverse; - -import static org.apache.commons.lang.StringUtils.join; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.net.URI; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.filter.DependencyFilter; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.rel.PluginRelationship; -import org.commonjava.maven.atlas.graph.traverse.BuildOrderTraversal; -import org.commonjava.maven.atlas.graph.traverse.model.BuildOrder; -import org.commonjava.maven.atlas.ident.DependencyScope; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.tck.graph.AbstractSPI_TCK; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -public abstract class BuildOrderTraversalTCK - extends AbstractSPI_TCK -{ - - @Test - public void simpleDependencyBuildOrder() - throws Exception - { - final ProjectVersionRef c = new ProjectVersionRef( "group.id", "c", "3" ); - final ProjectVersionRef b = new ProjectVersionRef( "group.id", "b", "2" ); - final ProjectVersionRef a = new ProjectVersionRef( "group.id", "a", "1" ); - - final Map relativeOrder = new HashMap(); - relativeOrder.put( c, b ); - relativeOrder.put( b, a ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( c ); - - /* @formatter:off */ - graph.storeRelationships( new DependencyRelationship( source, c, new ArtifactRef( b, null, null, false ), null, 0, false ), - new DependencyRelationship( source, b, new ArtifactRef( a, null, null, false ), null, 0, false ) ); - /* @formatter:on */ - - assertThat( graph.getAllRelationships() - .size(), equalTo( 2 ) ); - - logger.info( "Starting build-order traversal" ); - final BuildOrderTraversal bo = new BuildOrderTraversal( new DependencyFilter( DependencyScope.test ) ); - graph.traverse( bo ); - - final BuildOrder buildOrderObj = bo.getBuildOrder(); - final List buildOrder = buildOrderObj.getOrder(); - - assertRelativeOrder( relativeOrder, buildOrder ); - } - - @Test - //@Ignore - public void simpleDependencyBuildOrder_includeDepParent() - throws Exception - - { - final ProjectVersionRef c = new ProjectVersionRef( "group.id", "c", "3" ); - final ProjectVersionRef b = new ProjectVersionRef( "group.id", "b", "2" ); - final ProjectVersionRef a = new ProjectVersionRef( "group.id", "a", "1" ); - final ProjectVersionRef p = new ProjectVersionRef( "group.id", "b-parent", "1001" ); - - final Map relativeOrder = new HashMap(); - relativeOrder.put( c, b ); - relativeOrder.put( b, a ); - relativeOrder.put( b, p ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( c ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, c ), - new ParentRelationship( source, b, p ), - new DependencyRelationship( source, c, b.asJarArtifact(), null, 0, false ), - new DependencyRelationship( source, b, a.asJarArtifact(), null, 0, false ) - ); - /* @formatter:on */ - - assertThat( graph.getAllRelationships() - .size(), equalTo( 3 ) ); - - final BuildOrderTraversal bo = new BuildOrderTraversal( new DependencyFilter( DependencyScope.test ) ); - graph.traverse( bo ); - - final BuildOrder buildOrderObj = bo.getBuildOrder(); - final List buildOrder = buildOrderObj.getOrder(); - - LoggerFactory.getLogger( getClass() ) - .info( "Build order: {}", buildOrder ); - - assertThat( buildOrder.size(), equalTo( 4 ) ); - - assertRelativeOrder( relativeOrder, buildOrder ); - } - - @Test - //@Ignore - public void simpleDependencyBuildOrder_IgnorePluginPath() - throws Exception - { - final ProjectVersionRef c = new ProjectVersionRef( "group.id", "c", "3" ); - final ProjectVersionRef b = new ProjectVersionRef( "group.id", "b", "2" ); - final ProjectVersionRef a = new ProjectVersionRef( "group.id", "a", "1" ); - final ProjectVersionRef pa = new ProjectVersionRef( "plugin.id", "p-a", "1" ); - final ProjectVersionRef pb = new ProjectVersionRef( "plugin.id", "p-b", "2" ); - - final Map relativeOrder = new HashMap(); - relativeOrder.put( c, b ); - relativeOrder.put( b, a ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( c ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, c ), - new DependencyRelationship( source, c, b.asJarArtifact(), null, 0, false ), - new PluginRelationship( source, c, pb, 0, false ), - new DependencyRelationship( source, pb, pa.asJarArtifact(), null, 0, false ), - new DependencyRelationship( source, b, a.asJarArtifact(), null, 0, false ) - ); - /* @formatter:on */ - - assertThat( graph.getAllRelationships() - .size(), equalTo( 4 ) ); - - final BuildOrderTraversal bo = new BuildOrderTraversal( new DependencyFilter( DependencyScope.test ) ); - graph.traverse( bo ); - - final BuildOrder buildOrderObj = bo.getBuildOrder(); - final List buildOrder = buildOrderObj.getOrder(); - - assertRelativeOrder( relativeOrder, buildOrder ); - } - - @Test - //@Ignore - public void simpleDependencyBuildOrder_runtimeDepsOnly() - throws Exception - { - final ProjectVersionRef e = new ProjectVersionRef( "group.id", "e", "5" ); - final ProjectVersionRef d = new ProjectVersionRef( "group.id", "d", "4" ); - final ProjectVersionRef c = new ProjectVersionRef( "group.id", "c", "3" ); - final ProjectVersionRef b = new ProjectVersionRef( "group.id", "b", "2" ); - final ProjectVersionRef a = new ProjectVersionRef( "group.id", "a", "1" ); - final ProjectVersionRef pa = new ProjectVersionRef( "plugin.id", "p-a", "1" ); - final ProjectVersionRef pb = new ProjectVersionRef( "plugin.id", "p-b", "2" ); - - final Map relativeOrder = new HashMap(); - relativeOrder.put( c, b ); - relativeOrder.put( b, a ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( c ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, c ), - new DependencyRelationship( source, c, b.asJarArtifact(), null, 0, false ), - new DependencyRelationship( source, c, d.asJarArtifact(), DependencyScope.test, 1, false ), - new PluginRelationship( source, c, pb, 0, false ), - new DependencyRelationship( source, b, a.asJarArtifact(), DependencyScope.runtime, 0, false ), - new DependencyRelationship( source, d, e.asJarArtifact(), DependencyScope.runtime, 0, false ), - new DependencyRelationship( source, pb, pa.asJarArtifact(), null, 0, false ) - ); - /* @formatter:on */ - - assertThat( graph.getAllRelationships() - .size(), equalTo( 6 ) ); - - final BuildOrderTraversal bo = new BuildOrderTraversal( new DependencyFilter( DependencyScope.runtime ) ); - graph.traverse( bo ); - - final BuildOrder buildOrderObj = bo.getBuildOrder(); - final List buildOrder = buildOrderObj.getOrder(); - - assertThat( buildOrder.size(), equalTo( 3 ) ); - - assertRelativeOrder( relativeOrder, buildOrder ); - } - - @Test - //@Ignore - public void simpleDependencyBuildOrder_ignoreExcluded() - throws Exception - { - final ProjectVersionRef d = new ProjectVersionRef( "group.id", "d", "4" ); - final ProjectVersionRef c = new ProjectVersionRef( "group.id", "c", "3" ); - final ProjectVersionRef b = new ProjectVersionRef( "group.id", "b", "2" ); - final ProjectVersionRef a = new ProjectVersionRef( "group.id", "a", "1" ); - - final Map relativeOrder = new HashMap(); - relativeOrder.put( c, b ); - relativeOrder.put( b, a ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( c ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, c ), - new DependencyRelationship( source, c, b.asJarArtifact(), null, 0, false, d ), - new DependencyRelationship( source, b, a.asJarArtifact(), DependencyScope.runtime, 0, false ), - new DependencyRelationship( source, b, d.asJarArtifact(), DependencyScope.runtime, 1, false ) - ); - /* @formatter:on */ - - assertThat( graph.getAllRelationships() - .size(), equalTo( 3 ) ); - - final BuildOrderTraversal bo = new BuildOrderTraversal( new DependencyFilter( DependencyScope.runtime ) ); - graph.traverse( bo ); - - final BuildOrder buildOrderObj = bo.getBuildOrder(); - final List buildOrder = buildOrderObj.getOrder(); - - logger.info( "Build order: %s", buildOrder ); - assertThat( buildOrder.size(), equalTo( 3 ) ); - - assertRelativeOrder( relativeOrder, buildOrder ); - } - - @Test - //@Ignore - public void simpleEverythingBuildOrder() - throws Exception - { - final ProjectVersionRef c = new ProjectVersionRef( "group.id", "c", "3" ); - final ProjectVersionRef b = new ProjectVersionRef( "group.id", "b", "2" ); - final ProjectVersionRef a = new ProjectVersionRef( "group.id", "a", "1" ); - final ProjectVersionRef pa = new ProjectVersionRef( "plugin.dep.id", "p-a", "1" ); - final ProjectVersionRef pb = new ProjectVersionRef( "plugin.id", "p-b", "2" ); - - final Map relativeOrder = new HashMap(); - relativeOrder.put( c, b ); - relativeOrder.put( b, a ); - relativeOrder.put( c, pb ); - relativeOrder.put( pb, pa ); - - final URI source = sourceURI(); - final RelationshipGraph graph = simpleGraph( c ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, c ), - new DependencyRelationship( source, c, b.asJarArtifact(), null, 0, false ), - new PluginRelationship( source, c, pb, 0, false ), - new DependencyRelationship( source, b, a.asJarArtifact(), DependencyScope.runtime, 0, false ), - new DependencyRelationship( source, pb, pa.asJarArtifact(), null, 0, false ) - ); - /* @formatter:on */ - - System.out.println( "Got relationships:\n\n " + join( graph.getAllRelationships(), "\n " ) ); - assertThat( graph.getAllRelationships() - .size(), equalTo( 4 ) ); - - final BuildOrderTraversal bo = new BuildOrderTraversal(); - graph.traverse( bo ); - - final BuildOrder buildOrderObj = bo.getBuildOrder(); - final List buildOrder = buildOrderObj.getOrder(); - - System.out.printf( "Build order: %s\n", buildOrder ); - - assertRelativeOrder( relativeOrder, buildOrder ); - } - - private void assertRelativeOrder( final Map relativeOrder, final List buildOrder ) - { - for ( final Map.Entry entry : relativeOrder.entrySet() ) - { - final ProjectRef k = entry.getKey() - .asProjectRef(); - final ProjectRef v = entry.getValue() - .asProjectRef(); - - final int kidx = buildOrder.indexOf( k ); - final int vidx = buildOrder.indexOf( v ); - - if ( kidx < 0 ) - { - fail( "Cannot find: " + k + " in build order: " + buildOrder ); - } - - if ( vidx < 0 ) - { - fail( "Cannot find: " + v + " in build order: " + buildOrder ); - } - - if ( vidx >= kidx ) - { - fail( "prerequisite project: " + v + " of: " + k + " appears AFTER it in the build order: " + buildOrder ); - } - } - } - -} diff --git a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/TransitiveDependencyTraversalTCK.java b/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/TransitiveDependencyTraversalTCK.java deleted file mode 100644 index 9f54cf87..00000000 --- a/tck/src/main/java/org/commonjava/maven/atlas/tck/graph/traverse/TransitiveDependencyTraversalTCK.java +++ /dev/null @@ -1,186 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 Red Hat, Inc.. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package org.commonjava.maven.atlas.tck.graph.traverse; - -import static org.commonjava.maven.atlas.ident.DependencyScope.compile; -import static org.commonjava.maven.atlas.ident.util.IdentityUtils.projectVersion; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.net.URI; -import java.util.List; - -import org.commonjava.maven.atlas.graph.RelationshipGraph; -import org.commonjava.maven.atlas.graph.ViewParams; -import org.commonjava.maven.atlas.graph.rel.DependencyRelationship; -import org.commonjava.maven.atlas.graph.rel.ParentRelationship; -import org.commonjava.maven.atlas.graph.traverse.TransitiveDependencyTraversal; -import org.commonjava.maven.atlas.ident.ref.ArtifactRef; -import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; -import org.commonjava.maven.atlas.tck.graph.AbstractSPI_TCK; -import org.junit.Test; - -public abstract class TransitiveDependencyTraversalTCK - extends AbstractSPI_TCK -{ - - @Test - public void collectDependencyOfDependency() - throws Exception - { - final URI source = sourceURI(); - final ProjectVersionRef root = projectVersion( "group.id", "my-project", "1.0" ); - final ProjectVersionRef d1 = projectVersion( "other.group", "dep-L1", "1.0.1" ); - final ProjectVersionRef d2 = projectVersion( "foo", "dep-L2", "1.1.1" ); - - final RelationshipGraph graph = simpleGraph( root ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, root ), - new DependencyRelationship( source, root, d1.asJarArtifact(), compile, 0, false ), - new DependencyRelationship( source, d1, d2.asJarArtifact(), compile, 0, false ) - ); - /* @formatter:on */ - - final TransitiveDependencyTraversal depTraversal = new TransitiveDependencyTraversal(); - graph.traverse( depTraversal ); - - final List artifacts = depTraversal.getArtifacts(); - - assertThat( artifacts.size(), equalTo( 2 ) ); - - int idx = 0; - - ArtifactRef ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L1" ) ); - - ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L2" ) ); - } - - @Test - public void collectDependencyOfDependencyWithExternalDepManagement() - throws Exception - { - final URI source = sourceURI(); - final ProjectVersionRef root = projectVersion( "group.id", "my-project", "1.0" ); - final ProjectVersionRef d1 = projectVersion( "other.group", "dep-L1", "1.0.1" ); - final ProjectVersionRef d2 = projectVersion( "foo", "dep-L2", "1.1.1" ); - final ProjectVersionRef d3 = projectVersion( "foo", "dep-L2", "1.1.2" ); - - RelationshipGraph graph = simpleGraph( root ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, root ), - new DependencyRelationship( source, root, d1.asJarArtifact(), compile, 0, false ), - new DependencyRelationship( source, d1, d2.asJarArtifact(), compile, 0, false ) - ); - /* @formatter:on */ - - graph = graphFactory().open( new ViewParams.Builder( graph.getParams() ).withSelection( d2.asProjectRef(), d3 ) - .build(), false ); - - // graph.getView() - // .selectVersion( d2.asProjectRef(), d3 ); - - final TransitiveDependencyTraversal depTraversal = new TransitiveDependencyTraversal(); - graph.traverse( depTraversal ); - - final List artifacts = depTraversal.getArtifacts(); - - assertThat( artifacts.size(), equalTo( 2 ) ); - - int idx = 0; - - ArtifactRef ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L1" ) ); - - ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L2" ) ); - assertThat( ref.getVersionString(), equalTo( d3.getVersionString() ) ); - } - - @Test - public void preferDirectDependency() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef root = projectVersion( "group.id", "my-project", "1.0" ); - final ProjectVersionRef d1 = projectVersion( "other.group", "dep-L1", "1.0.1" ); - final ProjectVersionRef d2a = projectVersion( "foo", "dep-L2", "1.1.1" ); - final ProjectVersionRef d2b = projectVersion( "foo", "dep-L2", "1.0" ); - - final RelationshipGraph graph = simpleGraph( root ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, root ), - new DependencyRelationship( source, root, d1.asJarArtifact(), compile, 0, false ), - new DependencyRelationship( source, root, d2a.asJarArtifact(), compile, 1, false ), - new DependencyRelationship( source, d1, d2b.asJarArtifact(), compile, 0, false ) - ); - /* @formatter:on */ - - final TransitiveDependencyTraversal depTraversal = new TransitiveDependencyTraversal(); - graph.traverse( depTraversal ); - - final List artifacts = depTraversal.getArtifacts(); - - assertThat( artifacts.size(), equalTo( 2 ) ); - - int idx = 0; - - ArtifactRef ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L1" ) ); - - ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L2" ) ); - assertThat( ref.getVersionSpec() - .renderStandard(), equalTo( "1.1.1" ) ); - } - - @Test - public void preferLocalDirectDepOverDirectDepInParent() - throws Exception - { - final URI source = sourceURI(); - - final ProjectVersionRef root = projectVersion( "group.id", "my-project", "1.0" ); - final ProjectVersionRef parent = projectVersion( "group.id", "parent", "1" ); - final ProjectVersionRef d1a = projectVersion( "other.group", "dep-L1", "1.1.1" ); - final ProjectVersionRef d1b = projectVersion( "other.group", "dep-L1", "1.0" ); - - final RelationshipGraph graph = simpleGraph( root ); - - /* @formatter:off */ - graph.storeRelationships( new ParentRelationship( source, root, parent ), - new DependencyRelationship( source, root, d1a.asJarArtifact(), compile, 0, false ), - new DependencyRelationship( source, parent, d1b.asJarArtifact(), compile, 0, false ) - ); - /* @formatter:on */ - - final TransitiveDependencyTraversal depTraversal = new TransitiveDependencyTraversal(); - graph.traverse( depTraversal ); - - final List artifacts = depTraversal.getArtifacts(); - - assertThat( artifacts.size(), equalTo( 1 ) ); - - int idx = 0; - - final ArtifactRef ref = artifacts.get( idx++ ); - assertThat( ref.getArtifactId(), equalTo( "dep-L1" ) ); - - assertThat( ref.getVersionSpec() - .renderStandard(), equalTo( "1.1.1" ) ); - } - -} diff --git a/travis-settings.xml b/travis-settings.xml new file mode 100644 index 00000000..b7d397b6 --- /dev/null +++ b/travis-settings.xml @@ -0,0 +1,58 @@ + + + + + sonatype-nexus-snapshots + ${env.SONATYPE_USER} + ${env.SONATYPE_PASS} + + + + + snapshot-repo + + + sonatype-nexus-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + false + + + true + + + + + + sonatype-nexus-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + false + + + true + + + + + + + snapshot-repo + + \ No newline at end of file