Search in sources :

Example 1 with MetadataXpp3Writer

use of org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer in project karaf by apache.

the class MavenUtil method generateMavenMetadata.

/**
 * Generate the maven-metadata-local.xml for the given Maven <code>Artifact</code>.
 *
 * @param artifact the Maven <code>Artifact</code>.
 * @param target   the target maven-metadata-local.xml file to generate.
 * @throws IOException if the maven-metadata-local.xml can't be generated.
 */
public static void generateMavenMetadata(Artifact artifact, File target) throws IOException {
    target.getParentFile().mkdirs();
    Metadata metadata = new Metadata();
    metadata.setGroupId(artifact.getGroupId());
    metadata.setArtifactId(artifact.getArtifactId());
    metadata.setVersion(artifact.getVersion());
    metadata.setModelVersion("1.1.0");
    Versioning versioning = new Versioning();
    versioning.setLastUpdatedTimestamp(new Date(System.currentTimeMillis()));
    Snapshot snapshot = new Snapshot();
    snapshot.setLocalCopy(true);
    versioning.setSnapshot(snapshot);
    SnapshotVersion snapshotVersion = new SnapshotVersion();
    snapshotVersion.setClassifier(artifact.getClassifier());
    snapshotVersion.setVersion(artifact.getVersion());
    snapshotVersion.setExtension(artifact.getType());
    snapshotVersion.setUpdated(versioning.getLastUpdated());
    versioning.addSnapshotVersion(snapshotVersion);
    metadata.setVersioning(versioning);
    MetadataXpp3Writer metadataWriter = new MetadataXpp3Writer();
    Writer writer = new FileWriter(target);
    metadataWriter.write(writer, metadata);
}
Also used : Versioning(org.apache.maven.artifact.repository.metadata.Versioning) Snapshot(org.apache.maven.artifact.repository.metadata.Snapshot) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer) SnapshotVersion(org.apache.maven.artifact.repository.metadata.SnapshotVersion) FileWriter(java.io.FileWriter) Metadata(org.apache.maven.artifact.repository.metadata.Metadata) Date(java.util.Date) FileWriter(java.io.FileWriter) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer) Writer(java.io.Writer)

Example 2 with MetadataXpp3Writer

use of org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer in project fabric8 by jboss-fuse.

the class AetherResolutionSupport method mvnInstall.

/**
 * <p>Simulation of <code>mvn clean install</code> inside local repository</p>
 * <p>Like <code>mvn clean install -DskipTests -Dmaven.repo.local=_repo</code></p>
 * @param repository
 * @param groupId
 * @param artifactId
 * @param version
 * @param content
 */
protected void mvnInstall(File repository, String groupId, String artifactId, String version, Date timestamp, String content) throws IOException {
    File location = new File(repository, String.format("%s/%s/%s", groupId.replaceAll("\\.", "/"), artifactId, version));
    String name = String.format("%s-%s", artifactId, version);
    File jar = new File(location, name + ".jar");
    FileUtils.write(jar, content);
    jar.setLastModified(timestamp.getTime());
    File pom = new File(location, name + ".pom");
    FileUtils.touch(pom);
    pom.setLastModified(timestamp.getTime());
    String remoteRepositoriesConfig = "";
    remoteRepositoriesConfig += name + ".jar>=\n";
    remoteRepositoriesConfig += name + ".pom>=\n";
    File remoteRepositories = new File(location, "_remote.repositories");
    FileUtils.write(remoteRepositories, remoteRepositoriesConfig);
    remoteRepositories.setLastModified(timestamp.getTime());
    Metadata gamd = getOrCreateLocalMetadata(repository, groupId, artifactId);
    if (!gamd.getVersioning().getVersions().contains(version)) {
        gamd.getVersioning().addVersion(version);
    }
    if (!version.endsWith("-SNAPSHOT")) {
        gamd.getVersioning().setRelease(version);
    } else {
        Metadata gavmd = getOrCreateLocalMetadata(repository, groupId, artifactId, version);
        gavmd.getVersioning().setSnapshot(new Snapshot());
        gavmd.getVersioning().getSnapshot().setLocalCopy(true);
        gavmd.getVersioning().setLastUpdatedTimestamp(timestamp);
        gavmd.getVersioning().getSnapshotVersions().clear();
        SnapshotVersion sv1 = new SnapshotVersion();
        sv1.setUpdated(gavmd.getVersioning().getLastUpdated());
        sv1.setVersion(version);
        sv1.setExtension("jar");
        gavmd.getVersioning().getSnapshotVersions().add(sv1);
        SnapshotVersion sv2 = new SnapshotVersion();
        sv2.setUpdated(gavmd.getVersioning().getLastUpdated());
        sv2.setVersion(version);
        sv2.setExtension("pom");
        gavmd.getVersioning().getSnapshotVersions().add(sv2);
        gavmd.getVersioning().setLastUpdatedTimestamp(timestamp);
        File gavmdFile = new File(location, "maven-metadata-local.xml");
        new MetadataXpp3Writer().write(new FileWriter(gavmdFile), gavmd);
        gavmdFile.setLastModified(timestamp.getTime());
    }
    gamd.getVersioning().setLastUpdatedTimestamp(timestamp);
    File gamdFile = new File(location.getParentFile(), "maven-metadata-local.xml");
    new MetadataXpp3Writer().write(new FileWriter(gamdFile), gamd);
    gamdFile.setLastModified(timestamp.getTime());
}
Also used : Snapshot(org.apache.maven.artifact.repository.metadata.Snapshot) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer) SnapshotVersion(org.apache.maven.artifact.repository.metadata.SnapshotVersion) FileWriter(java.io.FileWriter) Metadata(org.apache.maven.artifact.repository.metadata.Metadata) File(java.io.File)

Example 3 with MetadataXpp3Writer

use of org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer in project indy by Commonjava.

the class KojiMavenMetadataProviderTest method excludeBinaryImportsFromVersionMetadata.

@Test
public void excludeBinaryImportsFromVersionMetadata() throws Exception {
    initKojiClient("metadata-with-import-generate", false);
    Metadata metadata = provider.getMetadata(new StoreKey(MAVEN_PKG_KEY, group, "public"), "commons-io/commons-io/maven-metadata.xml");
    assertThat(metadata, notNullValue());
    StringWriter sw = new StringWriter();
    new MetadataXpp3Writer().write(sw, metadata);
    System.out.println(sw.toString());
    Versioning versioning = metadata.getVersioning();
    assertThat(versioning, notNullValue());
    assertThat(versioning.getLatest(), equalTo("2.4.0.redhat-1"));
    assertThat(versioning.getRelease(), equalTo("2.4.0.redhat-1"));
    List<String> versions = versioning.getVersions();
    assertThat(versions, notNullValue());
    assertThat(versions.size(), equalTo(1));
    int idx = 0;
    assertThat(versions.get(idx), equalTo("2.4.0.redhat-1"));
}
Also used : Versioning(org.apache.maven.artifact.repository.metadata.Versioning) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer) StringWriter(java.io.StringWriter) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) Metadata(org.apache.maven.artifact.repository.metadata.Metadata) TransferMetadata(org.commonjava.maven.galley.io.checksum.TransferMetadata) StoreKey(org.commonjava.indy.model.core.StoreKey) Test(org.junit.Test)

Example 4 with MetadataXpp3Writer

use of org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer in project indy by Commonjava.

the class MavenMetadataMerger method merge.

@Override
public byte[] merge(final Collection<Transfer> sources, final Group group, final String path) {
    Logger logger = LoggerFactory.getLogger(getClass());
    logger.debug("Generating merged metadata in: {}:{}", group.getKey(), path);
    final Metadata master = new Metadata();
    master.setVersioning(new Versioning());
    final MetadataXpp3Reader reader = new MetadataXpp3Reader();
    final FileReader fr = null;
    InputStream stream = null;
    boolean merged = false;
    Transfer snapshotProvider = null;
    for (final Transfer src : sources) {
        if (!src.exists()) {
            continue;
        }
        try {
            stream = src.openInputStream();
            String content = IOUtils.toString(stream);
            logger.debug("Adding in metadata content from: {}\n\n{}\n\n", src, content);
            // there is a lot of junk in here to make up for Metadata's anemic merge() method.
            final Metadata md = reader.read(new StringReader(content), false);
            if (md.getGroupId() != null) {
                master.setGroupId(md.getGroupId());
            }
            if (md.getArtifactId() != null) {
                master.setArtifactId(md.getArtifactId());
            }
            if (md.getVersion() != null) {
                master.setVersion(md.getVersion());
            }
            master.merge(md);
            Versioning versioning = master.getVersioning();
            Versioning mdVersioning = md.getVersioning();
            // FIXME: Should we try to merge snapshot lists instead of using the first one we encounter??
            if (versioning.getSnapshot() == null && mdVersioning != null) {
                logger.info("INCLUDING snapshot information from: {} in: {}:{}", src, group.getKey(), path);
                snapshotProvider = src;
                versioning.setSnapshot(mdVersioning.getSnapshot());
                final List<SnapshotVersion> snapshotVersions = versioning.getSnapshotVersions();
                boolean added = false;
                for (final SnapshotVersion snap : mdVersioning.getSnapshotVersions()) {
                    if (!snapshotVersions.contains(snap)) {
                        snapshotVersions.add(snap);
                        added = true;
                    }
                }
                if (added) {
                    Collections.sort(snapshotVersions, new SnapshotVersionComparator());
                }
            } else {
                logger.warn("SKIPPING snapshot information from: {} in: {}:{} (obscured by: {})", src, group.getKey(), path, snapshotProvider);
            }
            merged = true;
        } catch (final IOException e) {
            final StoreKey key = getKey(src);
            logger.error(String.format("Cannot read metadata: %s from artifact-store: %s. Reason: %s", src.getPath(), key, e.getMessage()), e);
        } catch (final XmlPullParserException e) {
            final StoreKey key = getKey(src);
            logger.error(String.format("Cannot parse metadata: %s from artifact-store: %s. Reason: %s", src.getPath(), key, e.getMessage()), e);
        } finally {
            closeQuietly(fr);
            closeQuietly(stream);
        }
    }
    Versioning versioning = master.getVersioning();
    if (versioning != null && versioning.getVersions() != null) {
        if (metadataProviders != null) {
            for (MavenMetadataProvider provider : metadataProviders) {
                try {
                    Metadata toMerge = provider.getMetadata(group.getKey(), path);
                    if (toMerge != null) {
                        merged = master.merge(toMerge) || merged;
                    }
                } catch (IndyWorkflowException e) {
                    logger.error(String.format("Cannot read metadata: %s from metadata provider: %s. Reason: %s", path, provider.getClass().getSimpleName(), e.getMessage()), e);
                }
            }
        }
        List<SingleVersion> versionObjects = versioning.getVersions().stream().map(VersionUtils::createSingleVersion).collect(Collectors.toList());
        Collections.sort(versionObjects);
        versioning.setVersions(versionObjects.stream().map(SingleVersion::renderStandard).collect(Collectors.toList()));
        if (versionObjects.size() > 0) {
            String latest = versionObjects.get(versionObjects.size() - 1).renderStandard();
            versioning.setLatest(latest);
            versioning.setRelease(latest);
        }
    }
    if (merged) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            new MetadataXpp3Writer().write(baos, master);
            return baos.toByteArray();
        } catch (final IOException e) {
            logger.error(String.format("Cannot write consolidated metadata: %s to: %s. Reason: %s", path, group.getKey(), e.getMessage()), e);
        }
    }
    return null;
}
Also used : MetadataXpp3Reader(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader) InputStream(java.io.InputStream) Metadata(org.apache.maven.artifact.repository.metadata.Metadata) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Logger(org.slf4j.Logger) StoreKey(org.commonjava.indy.model.core.StoreKey) Versioning(org.apache.maven.artifact.repository.metadata.Versioning) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer) SnapshotVersion(org.apache.maven.artifact.repository.metadata.SnapshotVersion) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Transfer(org.commonjava.maven.galley.model.Transfer) StringReader(java.io.StringReader) FileReader(java.io.FileReader) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) SingleVersion(org.commonjava.maven.atlas.ident.version.SingleVersion)

Example 5 with MetadataXpp3Writer

use of org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer in project karaf by apache.

the class KarMojo method createArchive.

/**
 * Generates the configuration archive.
 *
 * @param bundles
 */
@SuppressWarnings("deprecation")
private File createArchive(List<Artifact> bundles, File featuresFile, String groupId, String artifactId, String version) throws MojoExecutionException {
    ArtifactRepositoryLayout layout = new DefaultRepositoryLayout();
    File archiveFile = getArchiveFile(outputDirectory, finalName, classifier);
    MavenArchiver archiver = new MavenArchiver();
    MavenArchiveConfiguration configuration = new MavenArchiveConfiguration();
    configuration.addManifestEntries(archive.getManifestEntries());
    archiver.setArchiver(jarArchiver);
    archiver.setOutputFile(archiveFile);
    try {
        // TODO should .kar be a bundle?
        // archive.addManifestEntry(Constants.BUNDLE_NAME, project.getName());
        // archive.addManifestEntry(Constants.BUNDLE_VENDOR, project.getOrganization().getName());
        // ArtifactVersion version = project.getArtifact().getSelectedVersion();
        // String versionString = "" + version.getMajorVersion() + "." + version.getMinorVersion() + "." + version.getIncrementalVersion();
        // if (version.getQualifier() != null) {
        // versionString += "." + version.getQualifier();
        // }
        // archive.addManifestEntry(Constants.BUNDLE_VERSION, versionString);
        // archive.addManifestEntry(Constants.BUNDLE_MANIFESTVERSION, "2");
        // archive.addManifestEntry(Constants.BUNDLE_DESCRIPTION, project.getDescription());
        // // NB, no constant for this one
        // archive.addManifestEntry("Bundle-License", ((License) project.getLicenses().get(0)).getUrl());
        // archive.addManifestEntry(Constants.BUNDLE_DOCURL, project.getUrl());
        // //TODO this might need some help
        // archive.addManifestEntry(Constants.BUNDLE_SYMBOLICNAME, project.getArtifactId());
        // include the feature.xml
        Artifact featureArtifact = factory.createArtifactWithClassifier(groupId, artifactId, version, "xml", KarArtifactInstaller.FEATURE_CLASSIFIER);
        jarArchiver.addFile(featuresFile, repositoryPath + layout.pathOf(featureArtifact));
        if (featureArtifact.isSnapshot()) {
            // the artifact is a snapshot, create the maven-metadata-local.xml
            getLog().debug("Feature artifact is a SNAPSHOT, handling the maven-metadata-local.xml");
            File metadataTarget = new File(featuresFile.getParentFile(), "maven-metadata-local.xml");
            getLog().debug("Looking for " + metadataTarget.getAbsolutePath());
            if (!metadataTarget.exists()) {
                // the maven-metadata-local.xml doesn't exist, create it
                getLog().debug(metadataTarget.getAbsolutePath() + " doesn't exist, create it");
                Metadata metadata = new Metadata();
                metadata.setGroupId(featureArtifact.getGroupId());
                metadata.setArtifactId(featureArtifact.getArtifactId());
                metadata.setVersion(featureArtifact.getVersion());
                metadata.setModelVersion("1.1.0");
                Versioning versioning = new Versioning();
                versioning.setLastUpdatedTimestamp(new Date(System.currentTimeMillis()));
                Snapshot snapshot = new Snapshot();
                snapshot.setLocalCopy(true);
                versioning.setSnapshot(snapshot);
                SnapshotVersion snapshotVersion = new SnapshotVersion();
                snapshotVersion.setClassifier(featureArtifact.getClassifier());
                snapshotVersion.setVersion(featureArtifact.getVersion());
                snapshotVersion.setExtension(featureArtifact.getType());
                snapshotVersion.setUpdated(versioning.getLastUpdated());
                versioning.addSnapshotVersion(snapshotVersion);
                metadata.setVersioning(versioning);
                MetadataXpp3Writer metadataWriter = new MetadataXpp3Writer();
                try {
                    Writer writer = new FileWriter(metadataTarget);
                    metadataWriter.write(writer, metadata);
                } catch (Exception e) {
                    getLog().warn("Could not create maven-metadata-local.xml", e);
                    getLog().warn("It means that this SNAPSHOT could be overwritten by an older one present on remote repositories");
                }
            }
            getLog().debug("Adding file " + metadataTarget.getAbsolutePath() + " in the jar path " + repositoryPath + layout.pathOf(featureArtifact).substring(0, layout.pathOf(featureArtifact).lastIndexOf('/')) + "/maven-metadata-local.xml");
            jarArchiver.addFile(metadataTarget, repositoryPath + layout.pathOf(featureArtifact).substring(0, layout.pathOf(featureArtifact).lastIndexOf('/')) + "/maven-metadata-local.xml");
        }
        for (Artifact artifact : bundles) {
            artifactResolver.resolve(artifact, remoteRepos, localRepo);
            // TODO this may not be reasonable, but... resolved snapshot artifacts have timestamped versions
            // which do not work in startup.properties.
            artifact.setVersion(artifact.getBaseVersion());
            if (artifact.isSnapshot()) {
                // the artifact is a snapshot, create the maven-metadata-local.xml
                final File metadataTmp = File.createTempFile("maven-metadata-local.xml", ".tmp");
                try {
                    MavenUtil.generateMavenMetadata(artifact, metadataTmp);
                } catch (Exception e) {
                    getLog().warn("Could not create maven-metadata-local.xml", e);
                    getLog().warn("It means that this SNAPSHOT could be overwritten by an older one present on remote repositories");
                }
                jarArchiver.addFile(metadataTmp, repositoryPath + layout.pathOf(artifact).substring(0, layout.pathOf(artifact).lastIndexOf('/')) + "/maven-metadata-local.xml");
                try {
                    metadataTmp.delete();
                } catch (final Exception ex) {
                    getLog().warn("Cannot delete temporary created file.", ex);
                }
            }
            String targetFileName = repositoryPath + layout.pathOf(artifact);
            jarArchiver.addFile(artifact.getFile(), targetFileName);
        }
        if (resourcesDir.isDirectory()) {
            archiver.getArchiver().addDirectory(resourcesDir);
        }
        archiver.createArchive(project, archive);
        return archiveFile;
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to create archive", e);
    }
}
Also used : ArtifactRepositoryLayout(org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DefaultRepositoryLayout(org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout) Metadata(org.apache.maven.artifact.repository.metadata.Metadata) MavenArchiver(org.apache.maven.archiver.MavenArchiver) Artifact(org.apache.maven.artifact.Artifact) Date(java.util.Date) ArtifactNotFoundException(org.apache.maven.artifact.resolver.ArtifactNotFoundException) ArtifactResolutionException(org.apache.maven.artifact.resolver.ArtifactResolutionException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Versioning(org.apache.maven.artifact.repository.metadata.Versioning) Snapshot(org.apache.maven.artifact.repository.metadata.Snapshot) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer) SnapshotVersion(org.apache.maven.artifact.repository.metadata.SnapshotVersion) MavenArchiveConfiguration(org.apache.maven.archiver.MavenArchiveConfiguration) MetadataXpp3Writer(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer)

Aggregations

MetadataXpp3Writer (org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer)15 Metadata (org.apache.maven.artifact.repository.metadata.Metadata)13 Versioning (org.apache.maven.artifact.repository.metadata.Versioning)11 StoreKey (org.commonjava.indy.model.core.StoreKey)7 StringWriter (java.io.StringWriter)6 EventMetadata (org.commonjava.maven.galley.event.EventMetadata)6 SnapshotVersion (org.apache.maven.artifact.repository.metadata.SnapshotVersion)5 TransferMetadata (org.commonjava.maven.galley.io.checksum.TransferMetadata)5 Test (org.junit.Test)5 File (java.io.File)4 IOException (java.io.IOException)4 Snapshot (org.apache.maven.artifact.repository.metadata.Snapshot)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 FileWriter (java.io.FileWriter)3 Date (java.util.Date)2 MetadataXpp3Reader (org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader)2 IndyWorkflowException (org.commonjava.indy.IndyWorkflowException)2 Transfer (org.commonjava.maven.galley.model.Transfer)2 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1