Example usage for org.apache.maven.artifact.repository ArtifactRepository getBasedir

List of usage examples for org.apache.maven.artifact.repository ArtifactRepository getBasedir

Introduction

In this page you can find the example usage for org.apache.maven.artifact.repository ArtifactRepository getBasedir.

Prototype

String getBasedir();

Source Link

Usage

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.writers.wtp.AbstractWtpResourceWriter.java

License:Apache License

/**
 * Adds dependency for Eclipse WTP project.
 *
 * @param writer//from   w  ww. j  a v a 2s .  c o  m
 * @param artifact
 * @param localRepository
 * @param basedir
 * @throws MojoExecutionException
 */
protected void addDependency(XMLWriter writer, IdeDependency dep, ArtifactRepository localRepository,
        File basedir, String deployPath) throws MojoExecutionException {
    String handle;
    String dependentObject = null;
    String archiveName;

    // ejb's and wars must always be toplevel
    if (Constants.PROJECT_PACKAGING_WAR.equals(dep.getType())
            || Constants.PROJECT_PACKAGING_EJB.equals(dep.getType())) {
        deployPath = "/";
    }

    if (dep.isReferencedProject()) {
        // <dependent-module deploy-path="/WEB-INF/lib"
        // handle="module:/resource/artifactid/artifactid">
        // <dependency-type>uses</dependency-type>
        // </dependent-module>

        handle = "module:/resource/" + dep.getEclipseProjectName() + "/" + dep.getEclipseProjectName(); //$NON-NLS-1$ //$NON-NLS-2$

        String archiveExtension = dep.getType();
        if (Constants.PROJECT_PACKAGING_EJB.equals(dep.getType())) {
            dependentObject = "EjbModule_";
            // an EJB module is packed as a .jar file
            archiveExtension = Constants.PROJECT_PACKAGING_JAR;
        } else if (Constants.PROJECT_PACKAGING_WAR.equals(dep.getType())) {
            dependentObject = "WebModule_";
        }
        archiveName = dep.getEclipseProjectName() + "." + archiveExtension;
    } else {
        // <dependent-module deploy-path="/WEB-INF/lib"
        // handle="module:/classpath/var/M2_REPO/cl/cl/2.1/cl-2.1.jar">
        // <dependency-type>uses</dependency-type>
        // </dependent-module>

        File artifactPath = dep.getFile();

        if (artifactPath == null) {
            log.error(Messages.getString("EclipsePlugin.artifactpathisnull", dep.getId())); //$NON-NLS-1$
            return;
        }

        String fullPath = artifactPath.getPath();
        File repoFile = new File(fullPath);

        if (dep.isSystemScoped()) {
            handle = "module:/classpath/lib/" //$NON-NLS-1$
                    + IdeUtils.toRelativeAndFixSeparator(config.getEclipseProjectDirectory(), repoFile, false);
        } else {
            File localRepositoryFile = new File(localRepository.getBasedir());
            String relativePath = IdeUtils.toRelativeAndFixSeparator(localRepositoryFile, repoFile, false);

            if (!new File(relativePath).isAbsolute()) {
                handle = "module:/classpath/var/M2_REPO/" //$NON-NLS-1$
                        + relativePath;
            } else {
                handle = "module:/classpath/lib/" //$NON-NLS-1$
                        + IdeUtils.toRelativeAndFixSeparator(config.getEclipseProjectDirectory(), repoFile,
                                false);
            }
        }
        if (Constants.PROJECT_PACKAGING_EAR.equals(this.config.getPackaging()) && !"/".equals(deployPath)) {
            // This is a very ugly hack around a WTP bug! a delpoydir in the configuration file is duplicated.
            // a deploy dir like "lib" will be used as "lib/lib" the only workig workaround is to include a ..
            // in the archive name.
            archiveName = "../" + artifactPath.getName();
        } else {
            archiveName = artifactPath.getName();
        }
    }

    writer.startElement(ELT_DEPENDENT_MODULE);

    writer.addAttribute("archiveName", archiveName);

    writer.addAttribute(ATTR_DEPLOY_PATH, deployPath); //$NON-NLS-1$
    writer.addAttribute(ATTR_HANDLE, handle);

    if (dependentObject != null && config.getWtpVersion() >= 2.0f) {
        writer.startElement(ELT_DEPENDENCY_OBJECT);
        writer.writeText(dependentObject + System.identityHashCode(dep));
        writer.endElement();
    }

    writer.startElement(ELT_DEPENDENCY_TYPE);
    writer.writeText("uses"); //$NON-NLS-1$
    writer.endElement();

    writer.endElement();
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.IdeUtils.java

License:Apache License

/**
 * @param artifact the artifact/*w  w w  .j a  v a2  s  .c  o  m*/
 * @return the not-available marker file for the specified artifact
 */
public static File getNotAvailableMarkerFile(ArtifactRepository localRepository, Artifact artifact) {
    return new File(localRepository.getBasedir(),
            localRepository.pathOf(artifact) + NOT_AVAILABLE_MARKER_FILE_SUFFIX);
}

From source file:com.googlecode.jndiresources.maven.ManageArtifact.java

License:Apache License

/**
 * Load the artifact in local repository, and return the file path.
 * /*from w w w.j  ava 2  s  .co m*/
 * @param groupId The Maven group id.
 * @param artifactId The Maven artifact id.
 * @param version The Maven version.
 * @param repositories A list of String with remoteRepositories or null.
 * @return The path in local repository.
 * @throws MavenException If error when dowload or identify the maven jar
 *             file.
 * @throws ArtifactNotFoundException If artifact is not found.
 * @throws ResourceDoesNotExistException If error.
 */
public static String getArtifact(final String groupId, final String artifactId, final String version,
        final List repositories)
        throws MavenException, ArtifactNotFoundException, ResourceDoesNotExistException {
    // TODO : rcuperer la bonne version en cas de suprieur...
    try {
        if (maven_ == null) {
            maven_ = new MavenEmbedder();
            maven_.setClassLoader(Thread.currentThread().getContextClassLoader());
            maven_.setAlignWithUserInstallation(true);
            maven_.start();
        }

        final String scope = Artifact.RELEASE_VERSION;
        final String type = "jar";
        final ArtifactRepository localRepository = maven_.getLocalRepository();

        final Artifact artifact = maven_.createArtifact(groupId, artifactId, version, scope, type);
        final List remoteRepositories = new ArrayList();

        if ((repositories == null) || repositories.isEmpty())
            remoteRepositories.add(maven_.createRepository(CENTRAL_REPO, "central"));
        else {
            int id = 0;
            for (final Iterator i = repositories.iterator(); i.hasNext();) {
                remoteRepositories.add(maven_.createRepository((String) i.next(), "central_" + id++));
            }
        }
        maven_.resolve(artifact, remoteRepositories, localRepository);
        return localRepository.getBasedir() + File.separatorChar + localRepository.pathOf(artifact);
    } catch (ArtifactNotFoundException e) {
        throw (ArtifactNotFoundException) e.fillInStackTrace();
    } catch (Exception e) {
        throw new MavenException("Repository error", e);
    }
}

From source file:fr.imag.adele.cadse.platform.DependenciesTask.java

License:Apache License

/**
 * Main task execution.  Called by parent execute().
 *///from w  ww  .j av a2 s .  c  om
protected void doExecute() {

    if (useScope != null && scopes != null) {
        throw new BuildException("You cannot specify both useScope and scopes in the dependencies task.");
    }

    if (getPom() != null && !this.dependencies.isEmpty()) {
        throw new BuildException("You cannot specify both dependencies and a pom in the dependencies task");
    }

    // Try to load dependency refs from an exsiting Ant cache file
    if (isCacheDependencyRefs()) {
        if (getDependencyRefsBuildFile() == null) {
            setDependencyRefsBuildFile(DEFAULT_ANT_BUILD_FILE);
        }
        if (checkCachedDependencies()) {
            log("Dependency refs loaded from file: " + getDependencyRefsBuildFile(), Project.MSG_VERBOSE);
            return;
        }
    }

    ArtifactRepository localRepo = createLocalArtifactRepository();
    log("Using local repository: " + localRepo.getBasedir(), Project.MSG_VERBOSE);

    // Look up required resources from the plexus container
    ArtifactResolver resolver = (ArtifactResolver) lookup(ArtifactResolver.ROLE);
    ArtifactFactory artifactFactory = (ArtifactFactory) lookup(ArtifactFactory.ROLE);
    MavenMetadataSource metadataSource = (MavenMetadataSource) lookup(ArtifactMetadataSource.ROLE);

    Pom pom = initializePom(localRepo);
    if (pom != null) {
        dependencies = pom.getDependencies();
    } else {
        // we have to have some sort of Pom object in order to satisfy the requirements for building the
        // originating Artifact below...
        pom = createDummyPom(localRepo);
    }

    if (dependencies.isEmpty()) {
        log("There were no dependencies specified", Project.MSG_WARN);
    }

    log("Resolving dependencies...", Project.MSG_VERBOSE);

    Set artifacts;

    List remoteArtifactRepositories = createRemoteArtifactRepositories(pom.getRepositories());

    try {
        artifacts = MavenMetadataSource.createArtifacts(artifactFactory, dependencies, null, null, null);

        Artifact pomArtifact = artifactFactory.createBuildArtifact(pom.getGroupId(), pom.getArtifactId(),
                pom.getVersion(), pom.getPackaging());

        List listeners = Collections.singletonList(new AntResolutionListener(getProject()));

        ArtifactFilter filter = null;
        if (useScope != null) {
            filter = new ScopeArtifactFilter(useScope);
        }
        if (scopes != null) {
            filter = new SpecificScopesArtifactFilter(scopes);
        }
        if (type != null) {
            ArtifactFilter typeArtifactFilter = new TypesArtifactFilter(type);
            if (filter != null) {
                AndArtifactFilter andFilter = new AndArtifactFilter();
                andFilter.add(filter);
                andFilter.add(typeArtifactFilter);
                filter = andFilter;
            } else {
                filter = typeArtifactFilter;
            }
        }
        for (Object o : artifacts) {
            resolver.resolve((Artifact) o, remoteArtifactRepositories, localRepo);
        }

    } catch (ArtifactResolutionException e) {
        throw new BuildException("Unable to resolve artifact: " + e.getMessage(), e);
    } catch (ArtifactNotFoundException e) {
        throw new BuildException("Dependency not found: " + e.getMessage(), e);
    } catch (InvalidDependencyVersionException e) {
        throw new BuildException("Invalid dependency version: " + e.getMessage(), e);
    }

    FileSet dependencyFileSet = createFileSet();

    FileSet sourcesFileSet = createFileSet();

    FileSet javadocsFileSet = createFileSet();

    Path dependencyPath = new Path(getProject());

    Set versions = new HashSet();

    for (Object o : artifacts) {
        Artifact artifact = (Artifact) o;

        addArtifactToResult(localRepo, artifact, dependencyFileSet, dependencyPath);

        versions.add(artifact.getVersion());

        if (sourcesFilesetId != null) {
            resolveSource(artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "sources",
                    sourcesFileSet);
        }

        if (javadocFilesetId != null) {
            resolveSource(artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "javadoc",
                    javadocsFileSet);
        }

    }

    defineFilesetReference(filesetId, dependencyFileSet);

    defineFilesetReference(sourcesFilesetId, sourcesFileSet);

    defineFilesetReference(javadocFilesetId, javadocsFileSet);

    if (pathId != null) {
        getProject().addReference(pathId, dependencyPath);
    }

    if (versionsId != null) {
        String versionsValue = StringUtils.join(versions.iterator(), File.pathSeparator);
        getProject().setNewProperty(versionsId, versionsValue);
    }
}

From source file:hudson.gridmaven.reporters.MavenFingerprinter.java

License:Open Source License

private void recordParents(MavenBuildProxy build, MavenProject pom) throws IOException, InterruptedException {
    MavenProject parent = pom.getParent();
    while (parent != null) {
        File parentFile = parent.getFile();

        if (parentFile == null) {
            // Parent artifact contains no actual file, so we resolve against
            // the local repository
            ArtifactRepository localRepository = getLocalRepository(build.getMavenBuildInformation(), parent,
                    pom);//from   w  ww. j ava 2s  . c o  m
            if (localRepository != null) {
                Artifact parentArtifact = getArtifact(parent);
                // Don't use ArtifactRepository.find(), for compatibility with Maven 2.x
                if (parentArtifact != null) {
                    parentFile = new File(localRepository.getBasedir(), localRepository.pathOf(parentArtifact));
                }
            }
        }

        if (parentFile != null) {
            // we need to include the artifact Id for poms as well, otherwise a
            // project with the same groupId would override its parent's
            // fingerprint
            record(parent.getGroupId() + ":" + parent.getArtifactId(), parentFile, used);
        }
        parent = parent.getParent();
    }
}

From source file:hudson.maven.artifact.AbstractArtifactComponentTestCase.java

License:Apache License

protected void assertRemoteArtifactPresent(Artifact artifact) throws Exception {
    ArtifactRepository remoteRepo = remoteRepository();

    String path = remoteRepo.pathOf(artifact);

    File file = new File(remoteRepo.getBasedir(), path);

    file = new File(file.getParentFile(), "artifact-1.0-SNAPSHOT.jar");

    if (!file.exists()) {
        fail("Remote artifact " + file + " should be present.");
    }//from w w  w. ja  v  a2 s  .  com
}

From source file:hudson.maven.artifact.deployer.DefaultArtifactDeployer.java

License:Apache License

public void deploy(File source, Artifact artifact, ArtifactRepository deploymentRepository,
        ArtifactRepository localRepository) throws ArtifactDeploymentException {

    // If we're installing the POM, we need to transform it first. The source file supplied for 
    // installation here may be the POM, but that POM may not be set as the file of the supplied
    // artifact. Since the transformation only has access to the artifact and not the supplied
    // source file, we have to use the Artifact.setFile(..) and Artifact.getFile(..) methods
    // to shunt the POM file into the transformation process.
    // Here, we also set a flag indicating that the POM has been shunted through the Artifact,
    // and to expect the transformed version to be available in the Artifact afterwards...
    boolean useArtifactFile = false;
    File oldArtifactFile = artifact.getFile();
    if ("pom".equals(artifact.getType())) {
        artifact.setFile(source);/*from w w  w.j  av  a2  s . co m*/
        useArtifactFile = true;
    }

    try {
        transformationManager.transformForDeployment(artifact, deploymentRepository, localRepository);

        // If we used the Artifact shunt to transform a POM source file, we need to install
        // the transformed version, not the supplied version. Therefore, we need to replace
        // the supplied source POM with the one from Artifact.getFile(..).
        if (useArtifactFile) {
            source = artifact.getFile();
            artifact.setFile(oldArtifactFile);
        }

        // FIXME: Why oh why are we re-installing the artifact in the local repository? Isn't this
        // the responsibility of the ArtifactInstaller??

        // Copy the original file to the new one if it was transformed
        File artifactFile = new File(localRepository.getBasedir(), localRepository.pathOf(artifact));
        if (!artifactFile.equals(source)) {
            FileUtils.copyFile(source, artifactFile);
        }
        //FIXME find a way to get hudson BuildListener ??
        TransferListener downloadMonitor = new TransferListener() {

            public void transferInitiated(TransferEvent transferEvent) {
                String message = transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "Uploading"
                        : "Downloading";

                String url = transferEvent.getWagon().getRepository().getUrl();

                // TODO: can't use getLogger() because this isn't currently instantiated as a component
                System.out.println(message + ": " + url + "/" + transferEvent.getResource().getName());
            }

            public void transferStarted(TransferEvent transferEvent) {
                // no op
            }

            public void transferProgress(TransferEvent transferEvent, byte[] buffer, int length) {
                // no op
            }

            public void transferCompleted(TransferEvent transferEvent) {
                long contentLength = transferEvent.getResource().getContentLength();
                if (contentLength != WagonConstants.UNKNOWN_LENGTH) {
                    String type = (transferEvent.getRequestType() == TransferEvent.REQUEST_PUT ? "uploaded"
                            : "downloaded");
                    String l = contentLength >= 1024 ? (contentLength / 1024) + "K" : contentLength + "b";
                    System.out.println(l + " " + type);
                }

            }

            public void transferError(TransferEvent transferEvent) {
                transferEvent.getException().printStackTrace();
            }

            public void debug(String message) {
                // TODO Auto-generated method stub

            }

        };
        wagonManager.putArtifact(source, artifact, deploymentRepository, downloadMonitor);

        // must be after the artifact is installed
        for (Iterator i = artifact.getMetadataList().iterator(); i.hasNext();) {
            ArtifactMetadata metadata = (ArtifactMetadata) i.next();
            repositoryMetadataManager.deploy(metadata, localRepository, deploymentRepository);
        }
        // TODO: would like to flush this, but the plugin metadata is added in advance, not as an install/deploy transformation
        // This would avoid the need to merge and clear out the state during deployment
        //            artifact.getMetadataList().clear();
    } catch (TransferFailedException e) {
        throw new ArtifactDeploymentException("Error deploying artifact: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ArtifactDeploymentException("Error deploying artifact: " + e.getMessage(), e);
    } catch (RepositoryMetadataDeploymentException e) {
        throw new ArtifactDeploymentException("Error installing artifact's metadata: " + e.getMessage(), e);
    }
}

From source file:hudson.maven.MavenEmbedder.java

License:Apache License

protected MavenExecutionRequest buildMavenExecutionRequest(MavenRequest mavenRequest)
        throws MavenEmbedderException, ComponentLookupException {
    MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();

    if (mavenRequest.getGlobalSettingsFile() != null) {
        mavenExecutionRequest.setGlobalSettingsFile(new File(mavenRequest.getGlobalSettingsFile()));
    }// w  ww.  j a  v  a  2s  .  c o  m

    if (mavenExecutionRequest.getUserSettingsFile() != null) {
        mavenExecutionRequest.setUserSettingsFile(new File(mavenRequest.getUserSettingsFile()));
    }

    try {
        lookup(MavenExecutionRequestPopulator.class).populateFromSettings(mavenExecutionRequest, getSettings());

        lookup(MavenExecutionRequestPopulator.class).populateDefaults(mavenExecutionRequest);
    } catch (MavenExecutionRequestPopulationException e) {
        throw new MavenEmbedderException(e.getMessage(), e);
    }

    ArtifactRepository localRepository = getLocalRepository();
    mavenExecutionRequest.setLocalRepository(localRepository);
    mavenExecutionRequest.setLocalRepositoryPath(localRepository.getBasedir());
    mavenExecutionRequest.setOffline(mavenRequest.isOffline());

    mavenExecutionRequest.setUpdateSnapshots(mavenRequest.isUpdateSnapshots());

    // TODO check null and create a console one ?
    mavenExecutionRequest.setTransferListener(mavenRequest.getTransferListener());

    mavenExecutionRequest.setCacheNotFound(mavenRequest.isCacheNotFound());
    mavenExecutionRequest.setCacheTransferError(true);

    mavenExecutionRequest.setUserProperties(mavenRequest.getUserProperties());
    mavenExecutionRequest.getSystemProperties().putAll(System.getProperties());
    if (mavenRequest.getSystemProperties() != null) {
        mavenExecutionRequest.getSystemProperties().putAll(mavenRequest.getSystemProperties());
    }
    mavenExecutionRequest.getSystemProperties().putAll(getEnvVars());

    if (this.mavenHome != null) {
        mavenExecutionRequest.getSystemProperties().put("maven.home", this.mavenHome.getAbsolutePath());
    }

    if (mavenRequest.getProfiles() != null && !mavenRequest.getProfiles().isEmpty()) {
        for (String id : mavenRequest.getProfiles()) {
            Profile p = new Profile();
            p.setId(id);
            p.setSource("cli");
            mavenExecutionRequest.addProfile(p);
            mavenExecutionRequest.addActiveProfile(id);
        }
    }

    mavenExecutionRequest.setLoggingLevel(mavenRequest.getLoggingLevel());

    lookup(Logger.class).setThreshold(mavenRequest.getLoggingLevel());

    mavenExecutionRequest.setExecutionListener(mavenRequest.getExecutionListener())
            .setInteractiveMode(mavenRequest.isInteractive())
            .setGlobalChecksumPolicy(mavenRequest.getGlobalChecksumPolicy()).setGoals(mavenRequest.getGoals());

    if (mavenRequest.getPom() != null) {
        mavenExecutionRequest.setPom(new File(mavenRequest.getPom()));
    }

    if (mavenRequest.getWorkspaceReader() != null) {
        mavenExecutionRequest.setWorkspaceReader(mavenRequest.getWorkspaceReader());
    }

    // FIXME inactive profiles 

    //this.mavenExecutionRequest.set

    return mavenExecutionRequest;

}

From source file:hudson.maven.reporters.MavenFingerprinter.java

License:Open Source License

private void recordParents(MavenBuildProxy build, MavenProject pom, BuildListener listener)
        throws IOException, InterruptedException {
    Map<String, String> modelParents = build.getMavenBuildInformation().modelParents;
    ArtifactRepository localRepository = getLocalRepository(build.getMavenBuildInformation(), pom);
    if (localRepository == null) {
        listener.error(//from   www  .ja va2  s .c om
                "Could not find local repository for " + build.getMavenBuildInformation().getMavenVersion());
        return;
    }
    String parent = modelParents.get(pom.getId());
    while (parent != null) {
        String[] parts = parent.split(":");
        assert parts.length == 4 : parent;
        // Maven 2.x lacks DefaultArtifact constructor with String version and ArtifactRepository.find:
        Artifact parentArtifact = new DefaultArtifact(parts[0], parts[1],
                VersionRange.createFromVersion(parts[3]), null, parts[2], null,
                new DefaultArtifactHandler(parts[2]));
        File parentFile = new File(localRepository.getBasedir(), localRepository.pathOf(parentArtifact));
        // we need to include the artifact Id for poms as well, otherwise a project with the same groupId would override its parent's fingerprint
        record(parts[0] + ":" + parts[1], parentFile, used);
        parent = modelParents.get(parent);
    }
}

From source file:io.fabric8.maven.docker.assembly.MappingTrackArchiver.java

License:Apache License

private File getLocalMavenRepoFile(MavenSession session, File source) {
    ArtifactRepository localRepo = session.getLocalRepository();
    if (localRepo == null) {
        log.warn("No local repo found so not adding any extra watches in the local repository");
        return null;
    }//  www . jav  a  2  s  .  com

    Artifact artifact = getArtifactFromJar(source);
    if (artifact != null) {
        try {
            return new File(localRepo.getBasedir(), localRepo.pathOf(artifact));
        } catch (InvalidArtifactRTException e) {
            log.warn("Cannot get the local repository path for %s in base dir %s : %s", artifact,
                    localRepo.getBasedir(), e.getMessage());
        }
    }
    return null;
}