Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 JFrog Ltd.
   *
   * 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.jfrog.hudson.maven3.extractor;
 
 import hudson.EnvVars;
 import  org.jfrog.build.api.BuildInfoConfigProperties;
 import  org.jfrog.build.client.ArtifactoryClientConfiguration;
 import  org.jfrog.build.extractor.maven.BuildInfoRecorder;
 
 import java.io.File;
 import java.net.URL;
 import java.util.Map;

Class for setting up the Environment for a MavenModuleSet project. Responsible for adding the new maven opts with the location of the plugin.

Author(s):
Tomer Cohen
 
 public class MavenExtractorEnvironment extends Environment {
     public static final String MAVEN_PLUGIN_OPTS = "-Dm3plugin.lib";
     public static final String CLASSWORLDS_CONF_KEY = "classworlds.conf";
 
     private final MavenModuleSet project;
     private final String originalMavenOpts;
     private final ArtifactoryRedeployPublisher publisher;
     private final MavenModuleSetBuild build;
     private final BuildListener buildListener;
     private final EnvVars envVars;
     private FilePath classworldsConf;
     private String propertiesFilePath;
 
     // the build env vars method may be called again from another setUp of a wrapper so we need this flag to
     // attempt only once certain operations (like copying file or changing maven opts).
     private boolean initialized;
 
             ArtifactoryMaven3NativeConfigurator resolverBuildListener buildListener)
             throws IOExceptionInterruptedException {
         this. = buildListener;
         this. = build.getProject();
         this. = build;
         this. = publisher;
         this. = resolver;
         this. = .getMavenOpts();
         this. = build.getEnvironment(buildListener);
     }
 
     @Override
     public void buildEnvVars(Map<StringStringenv) {
 
         if (.getWorkspace() == null) {
             // HAP-274 - workspace might not be initialized yet (this method will be called later in the build lifecycle)
             return;
         }
 
         //If an SCM is configured
         if (! && !(.getProject().getScm() instanceof NullSCM)) {
             //Handle all the extractor info only when a checkout was already done
             boolean checkoutWasPerformed = true;
            try {
                Field scmField = AbstractBuild.class.getDeclaredField("scm");
                scmField.setAccessible(true);
                Object scmObject = scmField.get();
                //Null changelog parser is set when a checkout wasn't performed yet
                checkoutWasPerformed = !(scmObject instanceof NullChangeLogParser);
            } catch (Exception e) {
                .getLogger().println("[Warning] An error occurred while testing if the SCM checkout " +
                        "has already been performed: " + e.getMessage());
            }
            if (!checkoutWasPerformed) {
                return;
            }
        }
        // if not valid Maven version don't modify the environment
        if (!isMavenVersionValid()) {
            return;
        }
        env.put(."true");
        if ( == null && !env.containsKey()) {
            URL resource = getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-native.conf");
             = copyClassWorldsFile(resource);
        }
        if ( != null) {
            addCustomClassworlds(env.getRemote());
        }
        if (!) {
            try {
                PublisherContext publisherContext = null;
                if ( != null) {
                    publisherContext = createPublisherContext();
                }
                ResolverContext resolverContext = null;
                if ( != null) {
                    Credentials resolverCredentials = CredentialResolver.getPreferredResolver(
                            .getArtifactoryServer());
                    resolverContext = new ResolverContext(.getArtifactoryServer(), .getDetails(),
                            resolverCredentials);
                }
                ArtifactoryClientConfiguration configuration = ExtractorUtils.addBuilderInfoArguments(
                        envpublisherContextresolverContext);
                 = configuration.getPropertiesFile();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
             = true;
        }
        env.put(BuildInfoConfigProperties.PROP_PROPS_FILE, );
    }
    private boolean isMavenVersionValid() {
        try {
            return MavenVersionHelper.isAtLeastResolutionCapableVersion();
        } catch (Exception e) {
            throw new RuntimeException("Unable to determine Maven version"e);
        }
    }
    @Override
    public boolean tearDown(AbstractBuild buildBuildListener listenerthrows IOExceptionInterruptedException {
        if ( != null) {
            .delete();
        }
        return true;
    }
        ReleaseAction release = ActionableHelper.getLatestAction(buildReleaseAction.class);
        ServerDetails server = publisher.getDetails();
        if (release != null) {
            // staging build might change the target deployment repository
            String stagingRepoKey = release.getStagingRepositoryKey();
            if (!StringUtils.isBlank(stagingRepoKey) && !stagingRepoKey.equals(server.repositoryKey)) {
                server = new ServerDetails(server.artifactoryNamestagingRepoKey,
                        server.snapshotsRepositoryKeyserver.downloadRepositoryKey);
            }
        }
        PublisherContext context = new PublisherContext.Builder().artifactoryServer(publisher.getArtifactoryServer())
                .serverDetails(server).deployerOverrider(publisher).runChecks(publisher.isRunChecks())
                .includePublishArtifacts(publisher.isIncludePublishArtifacts())
                .violationRecipients(publisher.getViolationRecipients()).scopes(publisher.getScopes())
                .licenseAutoDiscovery(publisher.isLicenseAutoDiscovery())
                .discardOldBuilds(publisher.isDiscardOldBuilds()).deployArtifacts(publisher.isDeployArtifacts())
                .includesExcludes(publisher.getArtifactDeploymentPatterns())
                .skipBuildInfoDeploy(!publisher.isDeployBuildInfo())
                .includeEnvVars(publisher.isIncludeEnvVars()).discardBuildArtifacts(publisher.isDiscardBuildArtifacts())
                .matrixParams(publisher.getMatrixParams()).evenIfUnstable(publisher.isEvenIfUnstable())
                .enableIssueTrackerIntegration(publisher.isEnableIssueTrackerIntegration())
                .aggregateBuildIssues(publisher.isAggregateBuildIssues())
                .aggregationBuildStatus(publisher.getAggregationBuildStatus()).build();
        return context;
    }


    
Append custom Maven opts to the existing to the already existing ones. The opt that will be appended is the location Of the plugin for the Maven process to use.
    public String appendNewMavenOpts(MavenModuleSet projectAbstractBuild buildBuildListener listener)
            throws IOException {
        String opts = project.getMavenOpts();
        if (StringUtils.contains(opts)) {
            listener.getLogger().println(
                    "Property '" +  +
                            "' is already part of MAVEN_OPTS. This is usually a leftover of " +
                            "previous build which was forcibly stopped. Replacing the value with an updated one. " +
                            "Please remove it from the job configuration.");
            // this regex will remove the property and the value (the value either ends with a space or surrounded by quotes
            opts = opts.replaceAll( + "=([^\\s\"]+)|" +  + "=\"([^\"]*)\"""")
                    .trim();
        }
        StringBuilder mavenOpts = new StringBuilder();
        if (StringUtils.isNotBlank(opts)) {
            mavenOpts.append(opts);
        }
        File maven3ExtractorJar = Which.jarFile(BuildInfoRecorder.class);
        try {
            FilePath actualDependencyDirectory =
                    PluginDependencyHelper.getActualDependencyDirectory(buildmaven3ExtractorJar);
            mavenOpts.append(" ").append().append("=")
                    .append(quote(actualDependencyDirectory.getRemote()));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return mavenOpts.toString();
    }

    
Adds quotes around strings containing spaces.
    private static String quote(String arg) {
        if (StringUtils.isNotBlank(arg) && arg.indexOf(' ') >= 0) {
            return "\"" + arg + "\"";
        } else {
            return arg;
        }
    }

    
Copies a classworlds file to a temporary location either on the local filesystem or on a slave depending on the node type.

Returns:
The path of the classworlds.conf file
    private FilePath copyClassWorldsFile(AbstractBuild<?, ?> buildURL resource) {
        try {
            FilePath remoteClassworlds =
                    build.getWorkspace().createTextTempFile("classworlds""conf"""false);
            remoteClassworlds.copyFrom(resource);
            return remoteClassworlds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
Add a custom classworlds.conf file that will be read by the Maven build. Adds an environment variable classwordls.conf with the location of the classworlds file for Maven.

Returns:
The path of the classworlds.conf file
    public static void addCustomClassworlds(Map<StringStringenvString classworldsConfPath) {
        env.put(classworldsConfPath);
    }
New to GrepCode? Check out our FAQ X