Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  The MIT License
   *
   *  Copyright 2010 Sony Ericsson Mobile Communications. All rights reserved.
   *  Copyright 2012 Sony Mobile Communications AB. All rights reserved.
   *
   *  Permission is hereby granted, free of charge, to any person obtaining a copy
   *  of this software and associated documentation files (the "Software"), to deal
   *  in the Software without restriction, including without limitation the rights
  *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  *  copies of the Software, and to permit persons to whom the Software is
  *  furnished to do so, subject to the following conditions:
  *
  *  The above copyright notice and this permission notice shall be included in
  *  all copies or substantial portions of the Software.
  *
  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  *  THE SOFTWARE.
  */
 package com.sonyericsson.hudson.plugins.gerrit.trigger.gerritnotifier;
 
 
 import hudson.EnvVars;
 
 import java.util.List;

The Big RunListener in charge of coordinating build results and reporting back to Gerrit.

Author(s):
Robert Sandell <robert.sandell@sonyericsson.com>
 
 public class ToGerritRunListener extends RunListener<AbstractBuild> {
 
     private static final Logger logger = LoggerFactory.getLogger(ToGerritRunListener.class);
     private static ToGerritRunListener instance;
     private transient BuildMemory memory;

    
Default Constructor.
 
     public ToGerritRunListener() {
         super(AbstractBuild.class);
          = new BuildMemory();
     }

    
Returns the registered instance of this class from the list of all listeners.

Returns:
the instance.
 
     public static ToGerritRunListener getInstance() {
         if ( == null) {
             for (RunListener listener : all()) {
                 if (listener instanceof ToGerritRunListener) {
                      = (ToGerritRunListener)listener;
                     break;
                 }
             }
         }
         return ;
     }
 
     @Override
     public synchronized void onCompleted(AbstractBuild rTaskListener listener) {
         GerritCause cause = getCause(r);
         .info("Completed. Build: {} Cause: {}"rcause);
         if (cause != null) {
             cleanUpGerritCauses(causer);
             GerritTriggeredEvent event = cause.getEvent();
             if (GerritTrigger.getTrigger(r.getProject()) != null) {
                 // There won't be a trigger if this job was run through a unit test
                 GerritTrigger.getTrigger(r.getProject()).notifyBuildEnded(event);
             }
             event.fireBuildCompleted(r);
             if (!cause.isSilentMode()) {
                 .completed(eventr);
                if (r.getResult().isWorseThan(.)) {
                    try {
                        // Attempt to record the failure message, if applicable
                        String failureMessage = this.obtainFailureMessage(eventrlistener);
                        .info("Obtained failure message: {}"failureMessage);
                        .setEntryFailureMessage(eventrfailureMessage);
                    } catch (IOException e) {
                        listener.error("[gerrit-trigger] Unable to read failure message from the workspace.");
                        .warn("IOException while obtaining failure message for build: "
                                + r.getDisplayName(), e);
                    } catch (InterruptedException e) {
                        listener.error("[gerrit-trigger] Unable to read failure message from the workspace.");
                        .warn("InterruptedException while obtaining failure message for build: "
                                + r.getDisplayName(), e);
                    }
                }
                updateTriggerContexts(r);
                if (.isAllBuildsCompleted(event)) {
                    try {
                        .info("All Builds are completed for cause: {}"cause);
                        event.fireAllBuildsCompleted();
                        NotificationFactory.getInstance().queueBuildCompleted(.getMemoryImprint(event), listener);
                    } finally {
                        .forget(event);
                    }
                } else {
                    .info("Waiting for more builds to complete for cause [{}]. Status: \n{}",
                            cause.getStatusReport(event));
                }
            }
        }
    }
    @Override
    public synchronized void onStarted(AbstractBuild rTaskListener listener) {
        GerritCause cause = getCause(r);
        .debug("Started. Build: {} Cause: {}"rcause);
        if (cause != null) {
            cleanUpGerritCauses(causer);
            setThisBuild(r);
            if (cause.getEvent() != null) {
                cause.getEvent().fireBuildStarted(r);
            }
            if (!cause.isSilentMode()) {
                .started(cause.getEvent(), r);
                updateTriggerContexts(r);
                BuildsStartedStats stats = .getBuildsStartedStats(cause.getEvent());
                NotificationFactory.getInstance().queueBuildStarted(rlistenercause.getEvent(), stats);
            }
            .info("Gerrit build [{}] Started for cause: [{}]."rcause);
            .info("MemoryStatus:\n{}".getStatusReport(cause.getEvent()));
        }
    }

    
    protected void updateTriggerContexts(AbstractBuild r) {
        List<Causecauses = r.getCauses();
        for (Cause cause : causes) {
            if (cause instanceof GerritCause) {
                .updateTriggerContext((GerritCause)causer);
            }
        }
    }

    
    protected void setThisBuild(AbstractBuild r) {
        List<Causecauses = r.getCauses();
        for (Cause cause : causes) {
            if (cause instanceof GerritCause) {
                ((GerritCause)cause).getContext().setThisBuild(r);
            }
        }
    }

    
Workaround for builds that are triggered by the same Gerrit cause but multiple times in the same quiet period.

Parameters:
firstFound the cause first returned by hudson.model.Run.getCause(java.lang.Class).
build the build to clean up.
    protected void cleanUpGerritCauses(GerritCause firstFoundAbstractBuild build) {
        List<Causecauses = build.getAction(CauseAction.class).getCauses();
        int pos = causes.indexOf(firstFound) + 1;
        while (pos < causes.size()) {
            Cause c = causes.get(pos);
            if (c.equals(firstFound)) {
                causes.remove(pos);
            } else {
                pos++;
            }
        }
    }

    
Called just before a build is scheduled by the trigger.

Parameters:
project the project that will be built.
event the event that caused the build to be scheduled.
    public synchronized void onTriggered(AbstractProject projectGerritTriggeredEvent event) {
        //TODO stop builds for earlier patch-sets on same change.
        .triggered(eventproject);
        event.fireProjectTriggered(project);
        //Logging
        String name = null;
        if (project != null) {
            name = project.getName();
        }
        .info("Project [{}] triggered by Gerrit: [{}]"nameevent);
    }

    
Called just before a build is scheduled by the user to retrigger.

Parameters:
project the project.
event the event.
otherBuilds the list of other builds in the previous context.
    public synchronized void onRetriggered(AbstractProject project,
                                           GerritTriggeredEvent event,
                                           List<AbstractBuildotherBuilds) {
        .retriggered(eventprojectotherBuilds);
        event.fireProjectTriggered(project);
        //Logging
        String name = null;
        if (project != null) {
            name = project.getName();
        }
        .info("Project [{}] re-triggered by Gerrit-User: [{}]"nameevent);
    }

    
Checks the memory if the project is currently building the event.

    public boolean isBuilding(AbstractProject projectGerritTriggeredEvent event) {
        if (project == null || event == null) {
            return false;
        } else {
            return .isBuilding(eventproject);
        }
    }

    
    public boolean isBuilding(GerritTriggeredEvent event) {
        if (event == null) {
            return false;
        } else {
            return .isBuilding(event);
        }
    }

    
Finds the GerritCause for a build if there is one.

Parameters:
build the build to look in.
Returns:
the GerritCause or null if there is none.
    private GerritCause getCause(AbstractBuild build) {
        return (GerritCause)build.getCause(GerritCause.class);
    }

    
Searches the workspace for files matching the filepath glob.

Parameters:
ws The workspace
filepath The filepath glob pattern
Returns:
List of matching hudson.FilePaths. Guaranteed to be non-null.
Throws:
java.io.IOException if an error occurs while reading the workspace
java.lang.InterruptedException if an error occurs while reading the workspace
    protected FilePath[] getMatchingWorkspaceFiles(FilePath wsString filepath)
            throws IOExceptionInterruptedException {
        return ws.list(filepath);
    }

    
Returns the expanded file contents using the provided environment variables. null will be returned if the path does not exist.

Parameters:
path The file path being read.
envVars The environment variables to use during expansion.
Returns:
The string file contents, or null if it does not exist.
Throws:
java.io.IOException if an error occurs while reading the file
java.lang.InterruptedException if an error occurs while checking the status of the file
    protected String getExpandedContent(FilePath pathEnvVars envVarsthrows IOExceptionInterruptedException {
        if (path.exists()) {
            return envVars.expand(path.readToString());
        }
        return null;
    }

    
Attempt to obtain the failure message for a build.

Parameters:
event The event that triggered this build
build The build being executed
listener The build listener
Returns:
Message content from the configured unsuccessful message file
Throws:
java.io.IOException In case of an error communicating with the hudson.FilePath or Environment
java.lang.InterruptedException If interrupted while working with the hudson.FilePath or Environment
    private String obtainFailureMessage(GerritTriggeredEvent eventAbstractBuild buildTaskListener listener)
            throws IOExceptionInterruptedException {
        AbstractProject project = build.getProject();
        String content = null;
        GerritTrigger trigger = GerritTrigger.getTrigger(project);
        // trigger will be null in unit tests
        if (trigger != null) {
            String filepath = trigger.getBuildUnsuccessfulFilepath();
            .debug("Looking for failure message in file glob: {}"filepath);
            if (filepath != null && !filepath.isEmpty()) {
                EnvVars envVars;
                if (listener == null) {
                    envVars = build.getEnvironment();
                } else {
                    envVars = build.getEnvironment(listener);
                }
                // The filename may contain environment variables
                filepath = envVars.expand(filepath);
                // Check for ANT-style file path
                FilePath[] matches = this.getMatchingWorkspaceFiles(build.getWorkspace(), filepath);
                .debug("Found matching workspace files: {}"matches);
                if (matches.length > 0) {
                    // Use the first match
                    FilePath path = matches[0];
                    content = this.getExpandedContent(pathenvVars);
                    .info("Obtained failure message from file: {}"content);
                }
            }
        }
        return content;
    }
New to GrepCode? Check out our FAQ X