Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  The MIT License
   *
   *  Copyright 2010 Sony Ericsson Mobile Communications. 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.hudsontrigger.actions.manual;
 
 
 import java.util.List;
 
 import static com.sonyericsson.hudson.plugins.gerrit.trigger.utils.StringUtil.getPluginImageUrl;

RootAction for manually triggering a "Gerrit-build".

Author(s):
Robert Sandell <robert.sandell@sonyericsson.com>
 
 public class ManualTriggerAction implements RootAction {

    
The expected number of parts separated by _ in a generated id. Each part is actually another id.

 
     public static final int EXPECTED_NR_OF_PARTS_IN_A_GENERATED_ID = 3;
 
     private static final String SESSION_RESULT = "result";
     private static final String SESSION_SEARCH_ERROR = "error_search";
     private static final String SESSION_BUILD_ERROR = "error_build";
     private static final String SESSION_TRIGGER_MONITOR = "trigger_monitor";
 
     private static final Logger logger = LoggerFactory.getLogger(ManualTriggerAction.class);
    
The char that separates the different id components in a search-result-row.
 
     public static final String ID_SEPARATOR = ":";
    
The maximum length of a change subject to display.
 
     private static final int MAX_SUBJECT_STR_LENGTH = 65;
 
     @Override
     public String getIconFileName() {
         if (isEnabled() && Hudson.getInstance().hasPermission(.)) {
             return getPluginImageUrl("icon_retrigger24.png");
         } else {
             return null;
         }
     }
 
     @Override
     public String getDisplayName() {
         if (isEnabled() && Hudson.getInstance().hasPermission(.)) {
            return Messages.ManualGerritTrigger();
        } else {
            return null;
        }
    }
    @Override
    public String getUrlName() {
        return "/gerrit_manual_trigger";
    }

    
    public boolean isEnabled() {
        if (PluginImpl.getInstance() != null && PluginImpl.getInstance().getConfig() != null) {
            return PluginImpl.getInstance().getConfig().isEnableManualTrigger();
        } else {
            return false;
        }
    }

    
Serves the permission required to perform this action. Used by index.jelly

Returns:
the permission.
    @SuppressWarnings("unused")
    public Permission getRequiredPermission() {
        return .;
    }

    
Gets the full path to the provided javascript file. For use by jelly files to give to the client browser.

Parameters:
jsName the javascript filename.
Returns:
the full path from the web-context root.
    @SuppressWarnings("unused")
    //called from jelly
    public String getJsUrl(String jsName) {
        return StringUtil.getPluginJsUrl(jsName);
    }

    
Finds the highest and lowest code review vote for the provided patch set.

Parameters:
res the patch set.
Returns:
the highest and lowest code review vote for the patch set.
    public HighLow getCodeReview(JSONObject res) {
        return ..getApprovals(res);
    }

    
Finds the lowest and highest verified vote for the provided patch set.

Parameters:
res the patch-set.
Returns:
the highest and lowest verified vote.
    public HighLow getVerified(JSONObject res) {
        return ..getApprovals(res);
    }

    
Cuts the string to a max length of MAX_SUBJECT_STR_LENGTH and escapes unsafe HTML characters.

Parameters:
subject the string to fix if needed.
Returns:
the fixed string.
See also:
hudson.Util.escape(java.lang.String)
    @SuppressWarnings("unused")
    //Called from jelly
    public String toReadableHtml(String subject) {
        if (subject != null && subject.length() > ) {
            subject = subject.substring(0, );
        }
        if (subject != null) {
            return hudson.Util.escape(subject);
        } else {
            return "";
        }
    }

    
Does a search.

Parameters:
queryString the query to send to Gerrit.
request the request.
response the response.
Throws:
java.io.IOException if the unfortunate happens.
    @SuppressWarnings("unused")
    //Called from jelly
    public void doGerritSearch(@QueryParameter("queryString"final String queryStringStaplerRequest request,
                               StaplerResponse responsethrows IOException {
        if (!isEnabled()) {
            response.sendRedirect2(".");
            return;
        }
        IGerritHudsonTriggerConfig config = PluginImpl.getInstance().getConfig();
        GerritQueryHandler handler = new GerritQueryHandler(config);
        clearSessionData(request);
        request.getSession(true).setAttribute("queryString"queryString);
        try {
            List<JSONObjectjson = handler.queryJava(queryStringtruetruefalse);
            request.getSession(true).setAttribute(json);
            //TODO Implement some smart default selection.
            //That can notice that a specific revision is searched or that there is only one result etc.
        } catch (GerritQueryException gqe) {
            .debug("Bad query. "gqe);
            request.getSession(true).setAttribute(gqe);
        } catch (Exception ex) {
            .warn("Could not query Gerrit for [" + queryString + "]"ex);
            request.getSession(true).setAttribute(ex);
        }
        response.sendRedirect2(".");
    }

    
Builds the selected patch-set(s).

Parameters:
selectedIds the selected rows in the form's search-result separated by "[]".
request the request.
response the response.
Throws:
java.io.IOException if the unfortunate happens.
    @SuppressWarnings("unused")
    //Called from jelly
    public void doBuild(@QueryParameter("selectedIds"String selectedIdsStaplerRequest request,
                        StaplerResponse responsethrows IOException {
        if (!isEnabled()) {
            response.sendRedirect2(".");
            return;
        }
        request.getSession(true).removeAttribute();
        String[] selectedRows = null;
        if (selectedIds != null && selectedIds.length() > 0) {
            selectedRows = selectedIds.split("\\[\\]");
        }
        if (selectedRows == null || selectedRows.length <= 0) {
            .debug("No builds selected.");
            request.getSession(true).setAttribute(, Messages.ErrorSelectSomethingToBuild());
            response.sendRedirect2(".");
        } else {
            .debug("Something to build.");
            List<JSONObjectresult = (List<JSONObject>)request.getSession(true).getAttribute();
            TriggerMonitor monitor = new TriggerMonitor();
            .trace("Putting monitor into session.");
            request.getSession(true).setAttribute(monitor);
            .trace("Calling to index the search result.");
            HashMap<StringJSONObjectindexed = indexResult(result);
            .debug("Creating and triggering events.");
            for (String rowId : selectedRows) {
                ManualPatchsetCreated event = findAndCreatePatchSetEvent(rowIdindexed);
                .debug("Created event: {}"event);
                if (event != null) {
                    monitor.add(event);
                    .trace("Triggering event: {}"event);
                    triggerEvent(event);
                }
            }
            .debug("Sending redirect.");
            response.sendRedirect2(".");
        }
    }

    
Clears the HTTP session from search and manual-trigger related data.

Parameters:
request the request with the HTTP session.
    private void clearSessionData(StaplerRequest request) {
        request.getSession(true).removeAttribute();
        request.getSession(true).removeAttribute();
        request.getSession(true).removeAttribute();
        request.getSession(true).removeAttribute();
    }

    
Generates a "unique" id for the change and/or patch. So it can be identified as a single row in the search result.

Parameters:
change the change.
patch the patch-set in the change.
Returns:
the generated id.
    public String generateTheId(JSONObject changeJSONObject patch) {
        StringBuilder theId = new StringBuilder(change.getString("id"));
        if (patch != null) {
            theId.append();
            theId.append(patch.getString("revision"));
        }
        theId.append();
        theId.append(change.getString("number"));
        if (patch != null) {
            theId.append();
            theId.append(patch.getString("number"));
        }
        return theId.toString();
    }

    
Indexes the search result based on each change and patchset's rowId.

Parameters:
result the search result.
Returns:
an indexed map where the rowId is the key.
See also:
generateTheId(net.sf.json.JSONObject,net.sf.json.JSONObject)
    private HashMap<StringJSONObjectindexResult(List<JSONObjectresult) {
        HashMap<StringJSONObjectmap = new HashMap<StringJSONObject>();
        for (JSONObject res : result) {
            if (!res.has("type")) {
                String changeId = generateTheId(resnull);
                map.put(changeIdres);
                JSONArray arr = res.getJSONArray("patchSets");
                for (Object obj : arr) {
                    if (obj instanceof JSONObject) {
                        JSONObject patch = (JSONObject)obj;
                        String theId = generateTheId(respatch);
                        map.put(theIdpatch);
                    }
                }
            }
        }
        return map;
    }

    
Generates the URL to the provided change in Gerrit. If the change already has a URL provided, that URL will be used.

Parameters:
event the event who's change to link to.
Returns:
the URL to the event's change.
    public String getGerritUrl(PatchsetCreated event) {
        if (event.getChange().getUrl() != null && event.getChange().getUrl().length() > 0) {
            return event.getChange().getUrl();
        } else {
            return PluginImpl.getInstance().getConfig().getGerritFrontEndUrlFor(
                    event.getChange().getNumber(),
                    event.getPatchSet().getNumber());
        }
    }

    
Creates a list of the parameters as they would be in a scheduled build. Without escaped quotes.

Parameters:
jsonChange the JSON data for the change.
jsonPatchSet the JSON data for the patch-set.
Returns:
a list of the parameters.
    @SuppressWarnings("unused"//called from jelly.
    public List<ParameterValuegetParametersForPatchSet(JSONObject jsonChangeJSONObject jsonPatchSet) {
        List<ParameterValueparameters = new LinkedList<ParameterValue>();
        Change change = new Change(jsonChange);
        PatchSet patchSet = new PatchSet(jsonPatchSet);
        PatchsetCreated event = new PatchsetCreated();
        event.setChange(change);
        event.setPatchset(patchSet);
        GerritTriggerParameters.setOrCreateParameters(eventparametersfalse);
        return parameters;
    }

    
Tells if the given parameter should have a URL or not. i.e. if the parameter represents com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTriggerParameters.GERRIT_CHANGE_URL.

Parameters:
parameterValue the parameter.
Returns:
true if so.
    @SuppressWarnings("unused"//called from jelly.
    public boolean hasUrl(ParameterValue parameterValue) {
        return ..name().equals(parameterValue.getName());
    }

    
Generates the URL to the provided change in Gerrit. If the change already has a URL provided, that URL will be used.

Parameters:
change the change to link to.
Returns:
the URL to the change.
    public String getGerritUrl(JSONObject change) {
        String url = change.optString("url"null);
        if (url != null && url.length() > 0) {
            return url;
        } else if (change.optString("number""").length() > 0) {
            return PluginImpl.getInstance().getConfig().getGerritFrontEndUrlFor(
                    change.getString("number"), "1");
        } else {
            return "";
        }
    }

    
Finds the patch-set in the indexed search result and creates a com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.events.ManualPatchsetCreated from its data.

Parameters:
rowId the generated rowId in the search result.
indexed the indexed search result.
Returns:
the event, or null if there is no patch-set in the search result.
                                                             HashMap<StringJSONObjectindexed) {
        .trace("Searching for {}"rowId);
        String[] ids = rowId.split();
        if (ids.length >= ) {
            .debug("Correct nr of ids: {}"ids.length);
            JSONObject patch = indexed.get(rowId);
            if (patch != null) {
                .debug("Found the patch: {}"patch);
                String changeId = ids[0] +  + ids[2];
                .debug("ChangeId calculated to: {}"changeId);
                JSONObject change = indexed.get(changeId);
                if (change != null) {
                    .debug("Found the change: {}"change);
                    return new ManualPatchsetCreated(changepatch, Hudson.getAuthentication().getName());
                } else {
                    .trace("No change found with id {}"changeId);
                    return null;
                }
            } else {
                .trace("No patch found for id {}"rowId);
                return null;
            }
        } else {
            .trace("Bad nr of ids.");
            return null;
        }
    }

    
Triggers the event by putting it into the event queue.

    private void triggerEvent(ManualPatchsetCreated event) {
        .trace("Going to trigger event: {}"event);
        PluginImpl.getInstance().triggerEvent(event);
    }

    
A tuple of a high and a low number.
    public static class HighLow {
        private final int high;
        private final int low;

        
Standard constructor.

Parameters:
high the highest number.
low the lowest number.
        public HighLow(int highint low) {
            this. = high;
            this. = low;
        }

        
Get the High number.

Returns:
the high number.
        public int getHigh() {
            return ;
        }

        
Get the Low number.

Returns:
the low number.
        public int getLow() {
            return ;
        }
        @Override
        public String toString() {
            return "HighLow(" +  + "," +  + ")";
        }
    }

    
Represents a "vote"-type or Approval of a change in the JSON structure.
    public static enum Approval {
        
A Code Review Approval type CRVW.
        CODE_REVIEW("CRVW"),
        
A Verified Approval type VRIF.
        VERIFIED("VRIF");
        private String type;

        
Standard constructor.

Parameters:
type the approval type.
        Approval(String type) {
            this. = type;
        }

        
Finds the highest and lowest approval value of the approval's type for the specified change.

Parameters:
res the change.
Returns:
the highest and lowest value. Or 0,0 if there are no values.
        public HighLow getApprovals(JSONObject res) {
            .trace("Get Approval: {} {}"res);
            int highValue = .;
            int lowValue = .;
            if (res.has("currentPatchSet")) {
                .trace("Has currentPatchSet");
                JSONObject patchSet = res.getJSONObject("currentPatchSet");
                if (patchSet.has("approvals")) {
                    JSONArray approvals = patchSet.getJSONArray("approvals");
                    .trace("Approvals: "approvals);
                    for (Object o : approvals) {
                        JSONObject ap = (JSONObject)o;
                        if (.equalsIgnoreCase(ap.optString("type"))) {
                            .trace("A {}");
                            try {
                                int approval = Integer.parseInt(ap.getString("value"));
                                highValue = Math.max(highValueapproval);
                                lowValue = Math.min(lowValueapproval);
                            } catch (NumberFormatException nfe) {
                                .warn("Gerrit is bad at giving me Approval-numbers!"nfe);
                            }
                        }
                    }
                }
            }
            if (highValue == . && lowValue == .) {
                .debug("Returning all 0");
                return new HighLow(0, 0);
            } else {
                HighLow r = new HighLow(highValuelowValue);
                .debug("Returning something {}"r);
                return r;
            }
        }
    }
New to GrepCode? Check out our FAQ X