Example usage for org.apache.maven.artifact.repository.layout DefaultRepositoryLayout DefaultRepositoryLayout

List of usage examples for org.apache.maven.artifact.repository.layout DefaultRepositoryLayout DefaultRepositoryLayout

Introduction

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

Prototype

DefaultRepositoryLayout

Source Link

Usage

From source file:com.adviser.maven.MojoSupport.java

License:Apache License

protected Artifact resourceToArtifact(String resourceLocation, boolean skipNonMavenProtocols)
        throws MojoExecutionException {
    resourceLocation = resourceLocation.replace("\r\n", "").replace("\n", "").replace(" ", "").replace("\t",
            "");/*from   www  .j  a v a2 s .  c  o  m*/
    final int index = resourceLocation.indexOf("mvn:");
    if (index < 0) {
        if (skipNonMavenProtocols) {
            return null;
        }
        throw new MojoExecutionException("Resource URL is not a maven URL: " + resourceLocation);
    } else {
        resourceLocation = resourceLocation.substring(index + "mvn:".length());
    }
    // Truncate the URL when a '#', a '?' or a '$' is encountered
    final int index1 = resourceLocation.indexOf('?');
    final int index2 = resourceLocation.indexOf('#');
    int endIndex = -1;
    if (index1 > 0) {
        if (index2 > 0) {
            endIndex = Math.min(index1, index2);
        } else {
            endIndex = index1;
        }
    } else if (index2 > 0) {
        endIndex = index2;
    }
    if (endIndex >= 0) {
        resourceLocation = resourceLocation.substring(0, endIndex);
    }
    final int index3 = resourceLocation.indexOf('$');
    if (index3 > 0) {
        resourceLocation = resourceLocation.substring(0, index3);
    }

    //check if the resourceLocation descriptor contains also remote repository information.
    ArtifactRepository repo = null;
    if (resourceLocation.startsWith("http://")) {
        final int repoDelimIntex = resourceLocation.indexOf('!');
        String repoUrl = resourceLocation.substring(0, repoDelimIntex);

        repo = new DefaultArtifactRepository(repoUrl, repoUrl, new DefaultRepositoryLayout());
        org.apache.maven.repository.Proxy mavenProxy = configureProxyToInlineRepo();
        if (mavenProxy != null) {
            repo.setProxy(mavenProxy);
        }
        resourceLocation = resourceLocation.substring(repoDelimIntex + 1);

    }
    String[] parts = resourceLocation.split("/");
    String groupId = parts[0];
    String artifactId = parts[1];
    String version = null;
    String classifier = null;
    String type = "jar";
    if (parts.length > 2) {
        version = parts[2];
        if (parts.length > 3) {
            type = parts[3];
            if (parts.length > 4) {
                classifier = parts[4];
            }
        }
    } else {
        Dependency dep = findDependency(project.getDependencies(), artifactId, groupId);
        if (dep == null && project.getDependencyManagement() != null) {
            dep = findDependency(project.getDependencyManagement().getDependencies(), artifactId, groupId);
        }
        if (dep != null) {
            version = dep.getVersion();
            classifier = dep.getClassifier();
            type = dep.getType();
        }
    }
    if (version == null || version.length() == 0) {
        throw new MojoExecutionException("Cannot find version for: " + resourceLocation);
    }
    Artifact artifact = factory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);
    artifact.setRepository(repo);
    return artifact;
}

From source file:com.effectivemaven.centrepoint.maven.repository.CentralRepositoryService.java

License:Apache License

@Inject
private CentralRepositoryService(RepositoryParams params) {
    try {/*from   w w w . ja  va 2  s. co m*/
        // jetty:run friendly setting
        Map<? extends Object, ? extends Object> context = Collections
                .singletonMap(PlexusConstants.IGNORE_CONTAINER_CONFIGURATION, Boolean.TRUE);

        // use Plexus to load the Maven components needed to retrieve repository information
        InputStreamReader configurationReader = new InputStreamReader(
                getClass().getResourceAsStream("/custom-plexus.xml"));
        PlexusContainer container = new DefaultPlexusContainer(configurationReader, context);

        this.artifactFactory = (ArtifactFactory) container.lookup(ArtifactFactory.ROLE);

        this.metadataSource = (ArtifactMetadataSource) container.lookup(MavenMetadataSource.ROLE,
                MavenMetadataSource.ROLE_HINT);

        ArtifactRepositoryFactory repositoryFactory = (ArtifactRepositoryFactory) container
                .lookup(ArtifactRepositoryFactory.ROLE);

        String localRepositoryUrl = new File(params.localRepositoryPath).toURL().toExternalForm();
        this.localRepository = repositoryFactory.createDeploymentArtifactRepository("local", localRepositoryUrl,
                new DefaultRepositoryLayout(), false);

        repository = repositoryFactory.createArtifactRepository("central", params.repositoryUrl,
                new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy());

        projectBuilder = (MavenProjectBuilder) container.lookup(MavenProjectBuilder.ROLE);
    } catch (Exception e) {
        throw new RuntimeException("Error starting Maven components for repository service", e);
    }
}

From source file:com.googlecode.t7mp.steps.deployment.AddRemoteRepositoryStep.java

License:Apache License

private ArtifactRepository createTomcatRepository() {
    ArtifactRepository repository = new DefaultArtifactRepository("t7mp.maven.repo.releases", REPO_URL,
            new DefaultRepositoryLayout(), createSnapshotPolicy(), createRelasesPolicy());
    return repository;
}

From source file:com.maestrodev.plugins.collabnet.FrsCopyWorker.java

License:Apache License

private String copyArtifact(FrsSession frsSession, String releaseId)
        throws MalformedURLException, RemoteException {
    Artifact artifact = new DefaultArtifact(artifactGroupId, artifactId,
            VersionRange.createFromVersion(artifactVersion), null, artifactType, artifactClassifier,
            new DefaultArtifactHandler(artifactType));
    String path = new DefaultRepositoryLayout().pathOf(artifact);
    String url = repositoryUrl + "/" + path;

    String filename = this.filename;
    if (StringUtils.isBlank(filename)) {
        filename = path.substring(path.lastIndexOf('/') + 1);
    }//from  w  ww  .  j a va  2 s.  c  om

    String msg = "Uploading '" + url + "' to release '" + releaseId + "' as '" + filename + "'";
    logger.debug(msg);
    writeOutput(msg + "\n");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(repositoryUsername, repositoryPassword.toCharArray());
        }
    });

    return frsSession.uploadFileFromUrl(releaseId, new URL(url), filename, overwrite);
}

From source file:com.redhat.rcm.offliner.PomArtifactListReader.java

License:Apache License

/**
 * Applies mirrors from the settings.xml on the {@code repositories}. Read mirrors replace the original repositories
 * in provided repository list./* w  ww  . ja  v a 2 s .co m*/
 *
 * @param settings settings.xml contents
 * @param repositories list of repositories read from pom
 */
private void processMirrors(final Settings settings, final List<Repository> repositories) {
    List<Mirror> mirrors = settings.getMirrors();
    MirrorSelector mirrorSelector = new DefaultMirrorSelector();
    DefaultRepositoryLayout layout = new DefaultRepositoryLayout();
    for (Repository repository : new ArrayList<>(repositories)) {
        ArtifactRepository artRepository = new MavenArtifactRepository();
        artRepository.setId(repository.getId());
        // TODO read the layout from the original repository
        artRepository.setLayout(layout);
        Mirror mirror = mirrorSelector.getMirror(artRepository, mirrors);
        if (mirror != null) {
            Repository mirrorRepository = new Repository();
            mirrorRepository.setId(mirror.getId());
            mirrorRepository.setLayout(mirror.getLayout());
            mirrorRepository.setReleases(repository.getReleases());
            mirrorRepository.setSnapshots(repository.getSnapshots());
            mirrorRepository.setUrl(mirror.getUrl());
            Collections.replaceAll(repositories, repository, mirrorRepository);
        }
    }
}

From source file:de.fct.companian.analyze.mvn.helper.MvnProjectBuilder.java

License:Apache License

public static MavenProject buildMavenProject(File pomFile) {
    if (logger.isDebugEnabled()) {
        logger.debug("buildMavenProject() start, pomFile=" + pomFile);
    }// w w  w.  j  ava  2 s . c om
    MavenProject mvnProject = null;

    ClassWorld classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());

    ContainerConfiguration cc = new DefaultContainerConfiguration().setClassWorld(classWorld)
            .setName("embedder");

    DefaultPlexusContainer container;
    org.codehaus.plexus.logging.Logger mvnLogger;
    try {
        mvnLogger = new ConsoleLogger(org.codehaus.plexus.logging.Logger.LEVEL_DEBUG, "Console");
        container = new DefaultPlexusContainer(cc);
        container.setLoggerManager(new MavenLoggerManager(mvnLogger));
        container.getLoggerManager().setThresholds(org.codehaus.plexus.logging.Logger.LEVEL_DEBUG);

        ProjectBuilder builder;
        try {
            builder = container.lookup(ProjectBuilder.class);
            logger.info("buildMavenProject() project builder = " + builder);

            try {

                ArtifactRepositoryFactory repoFactory = new DefaultArtifactRepositoryFactory();

                ArtifactRepository localRepo = repoFactory.createArtifactRepository("mylocal",
                        "file://h:/maven/repository", new DefaultRepositoryLayout(),
                        new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy());

                List<ArtifactRepository> remoteRepos = new ArrayList<ArtifactRepository>();
                ArtifactRepository mvnCentral = repoFactory.createArtifactRepository("mvnCentral",
                        "http://repo1.maven.org/maven2/", new DefaultRepositoryLayout(),
                        new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy());
                remoteRepos.add(mvnCentral);

                ProjectBuildingRequest buildRequest = new DefaultProjectBuildingRequest();
                buildRequest.setLocalRepository(localRepo);
                buildRequest.setRemoteRepositories(remoteRepos);
                buildRequest.setResolveDependencies(true);
                buildRequest.setOffline(false);

                ProjectBuildingResult buildResult = builder.build(pomFile, buildRequest);
                if (buildResult != null) {
                    logger.info("buildMavenProject() got a build result");

                    mvnProject = buildResult.getProject();
                }
            } catch (ProjectBuildingException e) {
                logger.error("buildMavenProject() error building project", e);
            }

        } catch (ComponentLookupException e) {
            logger.error("buildMavenProject() error looking up ArtifactResolver", e);
        }
    } catch (PlexusContainerException e) {
        logger.error("buildMavenProject() error from Plexus container", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("buildMavenProject() finished, mvnProject=" + mvnProject);
    }
    return mvnProject;
}

From source file:io.fabric8.maven.DeployToProfileMojo.java

License:Apache License

@SuppressWarnings("unchecked")
protected void uploadDeploymentUnit(J4pClient client, boolean newUserAdded) throws Exception {
    String uri = getMavenUploadUri(client);

    // lets resolve the artifact to make sure we get a local file
    Artifact artifact = project.getArtifact();
    ArtifactResolutionRequest request = new ArtifactResolutionRequest();
    request.setArtifact(artifact);/* w  ww  . ja  v a 2s  .c  o m*/
    addNeededRemoteRepository();
    request.setRemoteRepositories(remoteRepositories);
    request.setLocalRepository(localRepository);

    resolver.resolve(request);

    String packaging = project.getPackaging();
    File pomFile = project.getFile();

    @SuppressWarnings("unchecked")
    List<Artifact> attachedArtifacts = project.getAttachedArtifacts();

    DefaultRepositoryLayout layout = new DefaultRepositoryLayout();
    ArtifactRepository repo = new DefaultArtifactRepository(serverId, uri, layout);
    if (newUserAdded) {
        // make sure to set authentication if we just added new user
        repo.setAuthentication(new Authentication(fabricServer.getUsername(), fabricServer.getPassword()));
    }

    // Deploy the POM
    boolean isPomArtifact = "pom".equals(packaging);
    if (!isPomArtifact) {
        ProjectArtifactMetadata metadata = new ProjectArtifactMetadata(artifact, pomFile);
        artifact.addMetadata(metadata);
    }

    try {
        if (isPomArtifact) {
            deploy(pomFile, artifact, repo, localRepository, retryFailedDeploymentCount);
        } else {
            File file = artifact.getFile();

            // lets deploy the pom for the artifact first
            if (isFile(pomFile)) {
                deploy(pomFile, artifact, repo, localRepository, retryFailedDeploymentCount);
            }
            if (isFile(file)) {
                deploy(file, artifact, repo, localRepository, retryFailedDeploymentCount);
            } else if (!attachedArtifacts.isEmpty()) {
                getLog().info("No primary artifact to deploy, deploying attached artifacts instead.");

                Artifact pomArtifact = artifactFactory.createProjectArtifact(artifact.getGroupId(),
                        artifact.getArtifactId(), artifact.getBaseVersion());
                pomArtifact.setFile(pomFile);

                deploy(pomFile, pomArtifact, repo, localRepository, retryFailedDeploymentCount);

                // propagate the timestamped version to the main artifact for the attached artifacts to pick it up
                artifact.setResolvedVersion(pomArtifact.getVersion());
            } else {
                String message = "The packaging for this project did not assign a file to the build artifact";
                throw new MojoExecutionException(message);
            }
        }

        for (Artifact attached : attachedArtifacts) {
            deploy(attached.getFile(), attached, repo, localRepository, retryFailedDeploymentCount);
        }
    } catch (ArtifactDeploymentException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:io.fabric8.maven.DeployToProfileMojo.java

License:Apache License

@SuppressWarnings("unchecked")
private void addNeededRemoteRepository() {
    // TODO: Remove this code when we use releases from Maven Central
    // included jboss-fs repo which is required until we use an Apache version of Karaf
    boolean found = false;
    if (remoteRepositories != null) {
        for (Object obj : remoteRepositories) {
            if (obj instanceof ArtifactRepository) {
                ArtifactRepository repo = (ArtifactRepository) obj;
                if (repo.getUrl().contains("repository.jboss.org/nexus/content/groups/fs-public")) {
                    found = true;/*w  w w .j ava 2s .c o m*/
                    getLog().debug("Found existing (" + repo.getId() + ") remote repository: " + repo.getUrl());
                    break;
                }
            }
        }
    }
    if (!found) {
        ArtifactRepository fsPublic = new MavenArtifactRepository();
        fsPublic.setId("jboss-public-fs");
        fsPublic.setUrl("http://repository.jboss.org/nexus/content/groups/fs-public/");
        fsPublic.setLayout(new DefaultRepositoryLayout());
        fsPublic.setReleaseUpdatePolicy(new ArtifactRepositoryPolicy(true, "never", "warn"));
        fsPublic.setSnapshotUpdatePolicy(new ArtifactRepositoryPolicy(false, "never", "ignore"));
        if (remoteRepositories == null) {
            remoteRepositories = new ArrayList();
        }
        remoteRepositories.add(fsPublic);
        getLog().info(
                "Adding needed remote repository: http://repository.jboss.org/nexus/content/groups/fs-public/");
    }
}

From source file:io.github.appbundler.CreateApplicationBundleMojo.java

License:Apache License

/**
 * Copy all dependencies into the $JAVAROOT directory
 *
 * @param javaDirectory where to put jar files
 * @return A list of file names added/*www  .  j  ava  2s .  c  o  m*/
 * @throws MojoExecutionException
 */
private List<String> copyDependencies(File javaDirectory) throws MojoExecutionException {

    ArtifactRepositoryLayout layout = new DefaultRepositoryLayout();

    List<String> list = new ArrayList<String>();

    //        File repoDirectory = new File(javaDirectory, "repo");
    //        repoDirectory.mkdirs();

    // First, copy the project's own artifact
    File artifactFile = project.getArtifact().getFile();
    list.add(layout.pathOf(project.getArtifact()));

    try {
        FileUtils.copyFile(artifactFile, new File(javaDirectory, layout.pathOf(project.getArtifact())));
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Could not copy artifact file " + artifactFile + " to " + javaDirectory);
    }

    Set<Artifact> artifacts = project.getArtifacts();

    Iterator<Artifact> i = artifacts.iterator();

    while (i.hasNext()) {
        Artifact artifact = i.next();

        File file = artifact.getFile();
        File dest = new File(javaDirectory, layout.pathOf(artifact));

        getLog().debug("Adding " + file);

        try {
            FileUtils.copyFile(file, dest);
        } catch (IOException e) {
            throw new MojoExecutionException("Error copying file " + file + " into " + javaDirectory, e);
        }

        list.add(layout.pathOf(artifact));
    }

    return list;
}

From source file:net.oneandone.maven.plugins.prerelease.util.IntegrationBase.java

License:Apache License

public static Maven maven(World world) {
    DefaultPlexusContainer container;//  w w  w  .  ja v  a2  s .c o  m
    ArtifactRepositoryFactory factory;
    ArtifactRepository central;
    ArtifactRepository snapshots;
    FileNode localDir;
    ArtifactRepository local;
    MavenSession session;
    RepositorySystem repoSystem;
    DefaultRepositorySystemSession repoSession;

    container = container(null, null, Logger.LEVEL_DISABLED);
    try {
        factory = container.lookup(ArtifactRepositoryFactory.class);
    } catch (ComponentLookupException e) {
        throw new IllegalStateException(e);
    }
    central = factory.createArtifactRepository("central", "http://repo1.maven.org/maven2",
            new DefaultRepositoryLayout(),
            new ArtifactRepositoryPolicy(false, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));
    snapshots = factory.createArtifactRepository("apache-snapshots", "http://repository.apache.org/snapshots/",
            new DefaultRepositoryLayout(),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN),
            new ArtifactRepositoryPolicy(false, ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));
    localDir = defaultLocalRepositoryDir(world);
    local = factory.createArtifactRepository("local", localDir.getURI().toASCIIString(),
            new DefaultRepositoryLayout(),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));

    try {
        repoSystem = container.lookup(RepositorySystem.class);
        repoSession = MavenRepositorySystemUtils.newSession();
        repoSession.setLocalRepositoryManager(
                repoSystem.newLocalRepositoryManager(repoSession, new LocalRepository(localDir.getAbsolute())));
        session = new MavenSession(container, repoSession, new DefaultMavenExecutionRequest(),
                new DefaultMavenExecutionResult());
        return new Maven(world, new DefaultLog(null), session, local, null, null,
                container.lookup(ProjectBuilder.class), Arrays.asList(central, snapshots));
    } catch (ComponentLookupException e) {
        throw new IllegalStateException(e);
    }
}