├── .gitignore ├── .idea ├── .gitignore └── codeStyles │ ├── .gitignore │ ├── Project.xml │ └── codeStyleConfig.xml ├── .settings └── org.eclipse.jdt.core.prefs ├── LICENSE ├── README.md ├── pom.xml └── src ├── aps └── resources │ └── log4j.properties ├── main ├── java │ └── com │ │ └── meetme │ │ └── plugins │ │ └── jira │ │ └── gerrit │ │ ├── SessionKeys.java │ │ ├── adminui │ │ └── AdminServlet.java │ │ ├── data │ │ ├── GerritCommand.java │ │ ├── GerritConfiguration.java │ │ ├── GerritConfigurationImpl.java │ │ ├── IssueReviewsCacheLoader.java │ │ ├── IssueReviewsImpl.java │ │ ├── IssueReviewsManager.java │ │ └── dto │ │ │ ├── GerritApproval.java │ │ │ ├── GerritChange.java │ │ │ └── GerritPatchSet.java │ │ ├── tabpanel │ │ ├── GerritEventKeys.java │ │ ├── GerritReviewIssueAction.java │ │ ├── GerritReviewsTabPanel.java │ │ ├── SubtaskReviewsIssueAction.java │ │ └── SubtaskReviewsTabPanel.java │ │ ├── webpanel │ │ ├── GerritReviewsIssueAgilePanel.java │ │ ├── GerritReviewsIssueLeftPanel.java │ │ ├── GerritReviewsIssueSidePanel.java │ │ ├── IssueStatusOptionsProvider.java │ │ ├── IssueTypeOptionsProvider.java │ │ ├── ReviewStatusOptionsProvider.java │ │ └── ShowReviewsWebPanelCondition.java │ │ └── workflow │ │ ├── ApprovalScoreConditionFactoryImpl.java │ │ ├── ApproveReviewFactoryImpl.java │ │ ├── NoOpenReviewsConditionFactoryImpl.java │ │ ├── condition │ │ ├── ApprovalScore.java │ │ └── NoOpenReviews.java │ │ └── function │ │ └── ApprovalFunction.java └── resources │ ├── atlassian-plugin.xml │ ├── i18n │ ├── admin.properties │ ├── tabpanel.properties │ ├── webpanel.properties │ └── workflow.properties │ ├── images │ ├── gerrit-check.png │ ├── gerrit-icon16.png │ ├── gerrit-x.png │ ├── meetme.png │ └── meetme_75.png │ ├── styles │ └── gerrit-reviews-tabpanel.css │ └── templates │ ├── admin.vm │ ├── gerrit-reviews-agile-panel.vm │ ├── gerrit-reviews-left-panel.vm │ ├── gerrit-reviews-side-panel.vm │ ├── gerrit-reviews-tabpanel-item.vm │ ├── subtask-reviews-tabpanel-item.vm │ ├── utility.vm │ └── workflow │ ├── approve-function-edit.vm │ ├── approve-function-view.vm │ ├── no-open-reviews-condition-edit.vm │ ├── no-open-reviews-condition-view.vm │ ├── score-condition-edit.vm │ └── score-condition-view.vm └── test └── java └── com └── meetme └── plugins └── jira └── gerrit ├── data ├── IssueReviewsManagerTest.java └── dto │ └── GerritApprovalTest.java ├── tabpanel ├── GerritReviewIssueActionTest.java ├── SubtaskReviewsIssueActionTest.java └── SubtaskReviewsTabPanelTest.java ├── webpanel └── ShowReviewsWebPanelConditionTest.java └── workflow ├── AbstractWorkflowTest.java └── function └── ApprovalFunctionTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | work/ 2 | target/ 3 | bin/ 4 | 5 | #IDE specific files 6 | projectFilesBackup/ 7 | .project 8 | .classpath 9 | *.iml 10 | 11 | .DS_Store 12 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !codeStyleSettings.xml 3 | !.gitignore 4 | !codeStyles 5 | -------------------------------------------------------------------------------- /.idea/codeStyles/.gitignore: -------------------------------------------------------------------------------- 1 | !*.xml 2 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 135 | 136 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | #Fri Jun 08 18:11:32 EDT 2012 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 3 | eclipse.preferences.version=1 4 | org.eclipse.jdt.core.compiler.source=1.6 5 | org.eclipse.jdt.core.compiler.compliance=1.6 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | JIRA-Gerrit integration plugin 2 | ============================== 3 | © Copyright 2012 MeetMe, Inc. 4 | 5 | Maintainer: Joe Hansche 6 | 7 | 8 | Licensing 9 | --------- 10 | Please see the file named LICENSE. 11 | 12 | 13 | Install 14 | ------- 15 | * Available in the [JIRA Marketplace](https://marketplace.atlassian.com/plugins/com.meetme.plugins.jira.gerrit-plugin) 16 | for automatic installation from the JIRA "Find New Plugins" administration 17 | panel. 18 | * Alternatively, you can also download the JAR from the above URL, and install 19 | it manually from the "Manage Plugins" administration panel. 20 | 21 | 22 | Getting Started 23 | --------------- 24 | * Generate an SSH keypair for the JIRA user 25 | * Save the private key in a place where you can upload it to JIRA (1) 26 | * The public key will simply be copied/pasted (2) 27 | * Create a new user in Gerrit that you will use for the integration: 28 | 29 | $ ssh gerrit.company.com -p 29418 gerrit create-account jira --email jira@company.com --full-name JIRA --ssh-key 30 | 31 | * In JIRA, navigate to Administration > Plugins > Gerrit Admin 32 | * Enter hostname, port, and user under the SSH section 33 | * Upload the SSH private key generated at (1) above 34 | * Optionally change the Gerrit search query patterns: 35 | * `tr:%s` - Look for the issue key in a "Bug:" or "Issue:" footer 36 | * `topic:%s` - Look for the issue key in the change Topic (uploaded using 37 | `HEAD:refs/for/master/(issueKey)`) 38 | * `message:%s` - Look for the issue key in the commit message 39 | 40 | 41 | Features 42 | -------- 43 | * "Gerrit Reviews" issue tab panel to show all reviews related to the issue 44 | * "Gerrit Subtask Reviews" issue tab panel to show reviews related to all 45 | the issue's subtasks 46 | * Workflow condition to require that an issue must (or must not) have any 47 | open reviews 48 | * Workflow condition to require that an issue must (or must not) have a certain 49 | approval score (e.g., Code-Review == 2, or ! Verified < 0) 50 | * Workflow function to perform a Gerrit review 51 | * This is just an argument to the `gerrit review [ChangeId] ..` command, so 52 | it could be something like `--verified +1` to give a +1 score; 53 | or `--submit` to submit the change 54 | * The Gerrit user configured in the admin panel must have access to perform 55 | all necessary steps 56 | 57 | TODO 58 | ---- 59 | * Unit Tests (partial) 60 | * Possibly per-user SSH key configurations (instead of everything done as 61 | the JIRA user) 62 | * Possibly allow a second "suexec" SSH key so the JIRA user can spoof the 63 | acting JIRA user as a Gerrit user 64 | * ~~Extend SshConnection in order to obtain stderr content, to know if a 65 | command failed~~; this is no longer required, after our patch was accepted 66 | to the [gerrit-trigger-plugin](https://github.com/jenkinsci/gerrit-trigger-plugin/pull/26) 67 | project 68 | * Resolve `gerrit-events` dependency so it does not rely on a SNAPSHOT version 69 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/SessionKeys.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit; 15 | 16 | public interface SessionKeys { 17 | public static final String VIEWISSUE_REVIEWS_ISSUETYPE = "com.meetme.jira.gerrit.issuetype"; 18 | public static final String VIEWISSUE_REVIEWS_REVIEWSTATUS = "com.meetme.jira.gerrit.reviewstatus"; 19 | public static final String VIEWISSUE_REVIEWS_ISSUESTATUS = "com.meetme.jira.gerrit.issuestatus"; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/GerritCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 17 | 18 | import com.atlassian.core.user.preferences.Preferences; 19 | import com.jcraft.jsch.ChannelExec; 20 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.Authentication; 21 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshConnection; 22 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshConnectionFactory; 23 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshException; 24 | 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | import java.io.BufferedReader; 29 | import java.io.File; 30 | import java.io.IOException; 31 | import java.io.InputStreamReader; 32 | import java.util.List; 33 | 34 | public class GerritCommand { 35 | private static final Logger log = LoggerFactory.getLogger(GerritCommand.class); 36 | private final static String BASE_COMMAND = "gerrit review"; 37 | private GerritConfiguration config; 38 | private Preferences userPreferences; 39 | 40 | public GerritCommand(GerritConfiguration config, Preferences userPreferences) { 41 | this.config = config; 42 | this.userPreferences = userPreferences; 43 | } 44 | 45 | public boolean doReview(GerritChange change, String args) throws IOException { 46 | final String command = getCommand(change, args); 47 | return runCommand(command); 48 | } 49 | 50 | public boolean doReviews(List changes, String args) throws IOException { 51 | String[] commands = new String[changes.size()]; 52 | int i = 0; 53 | 54 | for (GerritChange change : changes) { 55 | commands[i++] = getCommand(change, args); 56 | } 57 | 58 | return runCommands(commands); 59 | } 60 | 61 | private boolean runCommand(String command) throws IOException { 62 | return runCommands(new String[] { command }); 63 | } 64 | 65 | @SuppressWarnings("deprecation") 66 | private String getCommand(GerritChange change, String args) { 67 | 68 | // TODO: escape args? Or build manually with String reviewType,int reviewScore,etc..? 69 | return String.format("%s %s,%s %s", BASE_COMMAND, change.getNumber(), change.getPatchSet().getNumber(), args); 70 | } 71 | 72 | private boolean runCommands(String[] commands) throws IOException { 73 | boolean success = true; 74 | SshConnection ssh = null; 75 | 76 | try { 77 | Authentication auth = getAuthentication(); 78 | ssh = SshConnectionFactory.getConnection(config.getSshHostname(), config.getSshPort(), auth); 79 | 80 | for (String command : commands) { 81 | if (!runCommand(ssh, command)) { 82 | log.warn("runCommand " + command + " returned false"); 83 | success = false; 84 | } 85 | } 86 | } finally { 87 | log.info("Disconnecting from SSH"); 88 | 89 | if (ssh != null) { 90 | ssh.disconnect(); 91 | } 92 | } 93 | 94 | if (log.isDebugEnabled()) { 95 | log.trace("runCommands " + commands.length + " -> success = " + success); 96 | } 97 | return success; 98 | } 99 | 100 | private Authentication getAuthentication() { 101 | Authentication auth = null; 102 | 103 | if (userPreferences != null) { 104 | // Attempt to get a per-user authentication mechanism, so JIRA can act as the user. 105 | try { 106 | String privateKey = userPreferences.getString("gerrit.privateKey"); 107 | String username = userPreferences.getString("gerrit.username"); 108 | 109 | if (privateKey != null && username != null && !privateKey.isEmpty() && !username.isEmpty()) { 110 | File privateKeyFile = new File(privateKey); 111 | 112 | if (privateKeyFile.exists() && privateKeyFile.canRead()) { 113 | auth = new Authentication(privateKeyFile, username); 114 | } 115 | } 116 | } catch (Exception exc) { 117 | auth = null; 118 | } 119 | } 120 | 121 | if (auth == null) { 122 | auth = new Authentication(config.getSshPrivateKey(), config.getSshUsername()); 123 | } 124 | 125 | return auth; 126 | } 127 | 128 | private boolean runCommand(SshConnection ssh, String command) throws SshException, IOException { 129 | boolean success = false; 130 | ChannelExec channel = null; 131 | 132 | log.info("Running command: " + command); 133 | 134 | try { 135 | channel = ssh.executeCommandChannel(command); 136 | 137 | BufferedReader reader; 138 | String incomingLine = null; 139 | 140 | InputStreamReader err = new InputStreamReader(channel.getErrStream()); 141 | InputStreamReader out = new InputStreamReader(channel.getInputStream()); 142 | 143 | reader = new BufferedReader(out); 144 | 145 | while ((incomingLine = reader.readLine()) != null) { 146 | // We don't expect any response anyway.. 147 | // But we can get the response and return it if we need to 148 | log.trace("Incoming line: " + incomingLine); 149 | } 150 | 151 | reader.close(); 152 | reader = new BufferedReader(err); 153 | 154 | while ((incomingLine = reader.readLine()) != null) { 155 | // We don't expect any response anyway.. 156 | // But we can get the response and return it if we need to 157 | log.warn("Error: " + incomingLine); 158 | } 159 | 160 | reader.close(); 161 | 162 | int exitStatus = channel.getExitStatus(); 163 | success = exitStatus == 0; 164 | log.info("Command exit status: " + exitStatus + ", success=" + success); 165 | } finally { 166 | channel.disconnect(); 167 | } 168 | 169 | return success; 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/GerritConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data; 15 | 16 | import java.io.File; 17 | import java.net.URI; 18 | import java.util.List; 19 | 20 | public interface GerritConfiguration { 21 | int DEFAULT_SSH_PORT = 29418; 22 | String DEFAULT_QUERY_ISSUE = "tr:%s"; 23 | String DEFAULT_QUERY_PROJECT = "message:%s-*"; 24 | 25 | String FIELD_SSH_HOSTNAME = "sshHostname"; 26 | String FIELD_SSH_USERNAME = "sshUsername"; 27 | String FIELD_SSH_PORT = "sshPort"; 28 | String FIELD_SSH_PRIVATE_KEY = "sshPrivateKey"; 29 | 30 | String FIELD_QUERY_ISSUE = "issueSearchQuery"; 31 | String FIELD_QUERY_PROJECT = "projectSearchQuery"; 32 | 33 | String FIELD_HTTP_BASE_URL = "httpBaseUrl"; 34 | String FIELD_HTTP_USERNAME = "httpUsername"; 35 | String FIELD_HTTP_PASSWORD = "httpPassword"; 36 | 37 | String FIELD_SHOW_EMPTY_PANEL = "showEmptyPanel"; 38 | String FIELD_ALL_PROJECTS = "allProjects"; 39 | String FIELD_KNOWN_GERRIT_PROJECTS = "knownGerritProjects"; 40 | String FIELD_USE_GERRIT_PROJECT_WHITELIST = "useGerritProjectWhitelist"; 41 | 42 | URI getHttpBaseUrl(); 43 | 44 | String getHttpPassword(); 45 | 46 | String getHttpUsername(); 47 | 48 | String getIssueSearchQuery(); 49 | 50 | String getProjectSearchQuery(); 51 | 52 | String getSshHostname(); 53 | 54 | int getSshPort(); 55 | 56 | File getSshPrivateKey(); 57 | 58 | String getSshUsername(); 59 | 60 | boolean getShowsEmptyPanel(); 61 | 62 | void setHttpBaseUrl(String httpBaseUrl); 63 | 64 | void setHttpPassword(String httpPassword); 65 | 66 | void setHttpUsername(String httpUsername); 67 | 68 | void setIssueSearchQuery(String query); 69 | 70 | void setProjectSearchQuery(String query); 71 | 72 | void setSshHostname(String hostname); 73 | 74 | void setSshPort(int port); 75 | 76 | void setSshPrivateKey(File sshPrivateKey); 77 | 78 | void setSshUsername(String username); 79 | 80 | void setShowEmptyPanel(boolean show); 81 | 82 | boolean isSshValid(); 83 | 84 | List getIdsOfKnownGerritProjects(); 85 | 86 | void setIdsOfKnownGerritProjects(List idsOfSelectedGerritProjects); 87 | 88 | boolean getUseGerritProjectWhitelist(); 89 | 90 | void setUseGerritProjectWhitelist(boolean useGerritProjectWhitelist); 91 | 92 | class NotConfiguredException extends RuntimeException { 93 | public NotConfiguredException() { 94 | } 95 | 96 | public NotConfiguredException(String message) { 97 | super(message); 98 | } 99 | 100 | public NotConfiguredException(String message, Throwable cause) { 101 | super(message, cause); 102 | } 103 | 104 | public NotConfiguredException(Throwable cause) { 105 | super(cause); 106 | } 107 | 108 | public NotConfiguredException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 109 | super(message, cause, enableSuppression, writableStackTrace); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/GerritConfigurationImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data; 15 | 16 | import com.atlassian.sal.api.pluginsettings.PluginSettings; 17 | import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; 18 | import com.google.common.base.Strings; 19 | import com.google.common.collect.Lists; 20 | 21 | import java.io.File; 22 | import java.net.URI; 23 | import java.util.List; 24 | 25 | /** 26 | * {@link GerritConfiguration} implementation that uses {@link PluginSettings} to store 27 | * configuration data. 28 | * 29 | * @author Joe Hansche 30 | */ 31 | public class GerritConfigurationImpl implements GerritConfiguration { 32 | private static final String PLUGIN_STORAGE_KEY = "com.meetme.plugins.jira.gerrit.data"; 33 | private final PluginSettings settings; 34 | 35 | public GerritConfigurationImpl(PluginSettingsFactory pluginSettingsFactory) { 36 | this.settings = pluginSettingsFactory.createSettingsForKey(PLUGIN_STORAGE_KEY); 37 | } 38 | 39 | @Override 40 | public URI getHttpBaseUrl() { 41 | String uri = (String) settings.get(FIELD_HTTP_BASE_URL); 42 | return uri == null ? null : URI.create(uri); 43 | } 44 | 45 | @Override 46 | public void setHttpBaseUrl(String httpBaseUrl) { 47 | settings.put(FIELD_HTTP_BASE_URL, httpBaseUrl == null ? null : URI.create(httpBaseUrl).toASCIIString()); 48 | } 49 | 50 | @Override 51 | public String getHttpPassword() { 52 | return (String) settings.get(FIELD_HTTP_PASSWORD); 53 | } 54 | 55 | @Override 56 | public void setHttpPassword(String httpPassword) { 57 | settings.put(FIELD_HTTP_PASSWORD, httpPassword); 58 | } 59 | 60 | @Override 61 | public String getHttpUsername() { 62 | return (String) settings.get(FIELD_HTTP_USERNAME); 63 | } 64 | 65 | @Override 66 | public void setHttpUsername(String httpUsername) { 67 | settings.put(FIELD_HTTP_USERNAME, httpUsername); 68 | } 69 | 70 | @Override 71 | public String getIssueSearchQuery() { 72 | String query = (String) settings.get(FIELD_QUERY_ISSUE); 73 | return query == null ? DEFAULT_QUERY_ISSUE : query; 74 | } 75 | 76 | @Override 77 | public void setIssueSearchQuery(String query) { 78 | settings.put(FIELD_QUERY_ISSUE, query); 79 | } 80 | 81 | @Override 82 | public String getProjectSearchQuery() { 83 | String query = (String) settings.get(FIELD_QUERY_PROJECT); 84 | return query == null ? DEFAULT_QUERY_PROJECT : query; 85 | } 86 | 87 | @Override 88 | public void setProjectSearchQuery(String query) { 89 | settings.put(FIELD_QUERY_PROJECT, query); 90 | } 91 | 92 | @Override 93 | public String getSshHostname() { 94 | return (String) settings.get(FIELD_SSH_HOSTNAME); 95 | } 96 | 97 | @Override 98 | public void setSshHostname(String hostname) { 99 | settings.put(FIELD_SSH_HOSTNAME, hostname); 100 | } 101 | 102 | @Override 103 | public int getSshPort() { 104 | String port = (String) settings.get(FIELD_SSH_PORT); 105 | return port == null ? DEFAULT_SSH_PORT : Integer.parseInt(port); 106 | } 107 | 108 | @Override 109 | public void setSshPort(int port) { 110 | settings.put(FIELD_SSH_PORT, Integer.toString(port)); 111 | } 112 | 113 | @Override 114 | public File getSshPrivateKey() { 115 | String path = (String) settings.get(FIELD_SSH_PRIVATE_KEY); 116 | return path == null ? null : new File(path); 117 | } 118 | 119 | @Override 120 | public void setSshPrivateKey(File sshPrivateKey) { 121 | settings.put(FIELD_SSH_PRIVATE_KEY, sshPrivateKey == null ? null : sshPrivateKey.getPath()); 122 | } 123 | 124 | @Override 125 | public String getSshUsername() { 126 | return (String) settings.get(FIELD_SSH_USERNAME); 127 | } 128 | 129 | @Override 130 | public void setSshUsername(String username) { 131 | settings.put(FIELD_SSH_USERNAME, username); 132 | } 133 | 134 | @Override 135 | public boolean getShowsEmptyPanel() { 136 | String shows = (String) settings.get(FIELD_SHOW_EMPTY_PANEL); 137 | // if not already set, defaults to true 138 | return shows == null || "true".equals(shows); 139 | } 140 | 141 | @Override 142 | public void setShowEmptyPanel(boolean show) { 143 | settings.put(FIELD_SHOW_EMPTY_PANEL, String.valueOf(show)); 144 | } 145 | 146 | @Override 147 | public boolean isSshValid() { 148 | return !Strings.isNullOrEmpty(getSshHostname()) 149 | && !Strings.isNullOrEmpty(getSshUsername()) 150 | && getSshPrivateKey() != null 151 | && getSshPrivateKey().exists(); 152 | } 153 | 154 | @Override 155 | public List getIdsOfKnownGerritProjects() { 156 | List idsOfKnownGerritProjects = (List) settings.get(FIELD_KNOWN_GERRIT_PROJECTS); 157 | return idsOfKnownGerritProjects != null ? idsOfKnownGerritProjects : Lists.newArrayList(); 158 | } 159 | 160 | @Override 161 | public void setIdsOfKnownGerritProjects(final List idsOfSelectedGerritProjects) { 162 | settings.put(FIELD_KNOWN_GERRIT_PROJECTS, idsOfSelectedGerritProjects); 163 | } 164 | 165 | @Override 166 | public boolean getUseGerritProjectWhitelist() { 167 | String useGerritProjectWhitelist = (String) settings.get(FIELD_USE_GERRIT_PROJECT_WHITELIST); 168 | // Defaults to the behavior without whitelist: 169 | return useGerritProjectWhitelist == null ? false : "true".equals(useGerritProjectWhitelist); 170 | } 171 | 172 | @Override 173 | public void setUseGerritProjectWhitelist(boolean useGerritProjectWhitelist) { 174 | settings.put(FIELD_USE_GERRIT_PROJECT_WHITELIST, String.valueOf(useGerritProjectWhitelist)); 175 | } 176 | 177 | @Override 178 | public String toString() { 179 | return String.format("GerritConfigurationImpl[ssh://{0}@{1}:*****/, {3}; http://{4}:*****@{6}/]", getSshUsername(), getSshHostname(), 180 | getSshPort(), getSshPrivateKey(), getHttpUsername(), getHttpPassword(), getHttpBaseUrl()); 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/IssueReviewsCacheLoader.java: -------------------------------------------------------------------------------- 1 | package com.meetme.plugins.jira.gerrit.data; 2 | 3 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 4 | 5 | import com.atlassian.cache.CacheException; 6 | import com.atlassian.cache.CacheLoader; 7 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 8 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryHandler; 9 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.Authentication; 10 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshException; 11 | 12 | import net.sf.json.JSONObject; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.io.IOException; 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.List; 21 | import java.util.Locale; 22 | 23 | import javax.annotation.Nonnull; 24 | 25 | public class IssueReviewsCacheLoader implements CacheLoader> { 26 | private final Logger log = LoggerFactory.getLogger(IssueReviewsCacheLoader.class); 27 | private final GerritConfiguration configuration; 28 | 29 | public IssueReviewsCacheLoader(GerritConfiguration configuration) { 30 | this.configuration = configuration; 31 | } 32 | 33 | @Nonnull 34 | @Override 35 | public List load(@Nonnull String key) { 36 | String query = String.format(Locale.US, configuration.getIssueSearchQuery(), key); 37 | 38 | try { 39 | return getReviewsFromGerrit(query); 40 | } catch (GerritQueryException e) { 41 | log.error("Error querying for issues", e); 42 | throw new CacheException("Error querying for issues: " + e.getMessage(), e); 43 | } 44 | } 45 | 46 | protected List getReviewsFromGerrit(String searchQuery) throws GerritQueryException { 47 | List changes; 48 | 49 | if (!configuration.isSshValid()) { 50 | // return Collections.emptyList(); 51 | throw new GerritConfiguration.NotConfiguredException("Not configured for SSH access"); 52 | } 53 | 54 | Authentication auth = new Authentication(configuration.getSshPrivateKey(), configuration.getSshUsername()); 55 | GerritQueryHandler query = new GerritQueryHandler(configuration.getSshHostname(), configuration.getSshPort(), null, auth); 56 | List reviews; 57 | 58 | try { 59 | reviews = query.queryJava(searchQuery, false, true, false); 60 | } catch (SshException e) { 61 | throw new GerritQueryException("An ssh error occurred while querying for reviews.", e); 62 | } catch (IOException e) { 63 | throw new GerritQueryException("An error occurred while querying for reviews.", e); 64 | } 65 | 66 | changes = new ArrayList<>(reviews.size()); 67 | 68 | for (JSONObject obj : reviews) { 69 | if (obj.has("type") && "stats".equalsIgnoreCase(obj.getString("type"))) { 70 | // The final JSON object in the query results is just a set of statistics 71 | if (log.isDebugEnabled()) { 72 | log.trace("Results from QUERY: " + obj.optString("rowCount", "(unknown)") + " rows; runtime: " 73 | + obj.optString("runTimeMilliseconds", "(unknown)") + " ms"); 74 | } 75 | continue; 76 | } 77 | 78 | changes.add(new GerritChange(obj)); 79 | } 80 | 81 | Collections.sort(changes); 82 | return changes; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/IssueReviewsImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 17 | 18 | import com.atlassian.cache.Cache; 19 | import com.atlassian.cache.CacheException; 20 | import com.atlassian.cache.CacheManager; 21 | import com.atlassian.cache.CacheSettingsBuilder; 22 | import com.atlassian.core.user.preferences.Preferences; 23 | import com.atlassian.jira.issue.Issue; 24 | import com.atlassian.jira.issue.IssueManager; 25 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 26 | 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | 30 | import java.io.IOException; 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | import java.util.Set; 34 | import java.util.concurrent.TimeUnit; 35 | 36 | public class IssueReviewsImpl implements IssueReviewsManager { 37 | private static final Logger log = LoggerFactory.getLogger(IssueReviewsImpl.class); 38 | 39 | private final Cache> cache; 40 | 41 | private GerritConfiguration configuration; 42 | 43 | private IssueManager jiraIssueManager; 44 | 45 | public IssueReviewsImpl( 46 | GerritConfiguration configuration, 47 | IssueManager jiraIssueManager, 48 | CacheManager cacheManager, 49 | IssueReviewsCacheLoader cacheLoader 50 | ) { 51 | this.configuration = configuration; 52 | this.jiraIssueManager = jiraIssueManager; 53 | this.cache = cacheManager.getCache( 54 | IssueReviewsManager.class.getName() + ".issueChanges.cache", 55 | cacheLoader, //new IssueReviewsCacheLoader(configuration), 56 | new CacheSettingsBuilder() 57 | .flushable() 58 | .statisticsEnabled() 59 | .maxEntries(100) 60 | .replicateAsynchronously() 61 | .expireAfterAccess(30, TimeUnit.MINUTES) 62 | .build() 63 | ); 64 | } 65 | 66 | @Override 67 | public Set getIssueKeys(Issue issue) { 68 | return jiraIssueManager.getAllIssueKeys(issue.getId()); 69 | } 70 | 71 | @Override 72 | public List getReviewsForIssue(Issue issue) throws GerritQueryException { 73 | List gerritChanges = new ArrayList<>(); 74 | 75 | Set allIssueKeys = getIssueKeys(issue); 76 | for (String key : allIssueKeys) { 77 | try { 78 | List changes = cache.get(key); 79 | if (changes != null) gerritChanges.addAll(changes); 80 | } catch (CacheException exc) { 81 | if (exc.getCause() instanceof GerritQueryException) { 82 | // TODO: is this really necessary? 83 | // If we swallow the error, then there's no indication on the UI that an error occurred. 84 | // The CacheLoader has to wrap the underlying exception in CacheException in order to throw it. 85 | throw (GerritQueryException) exc.getCause(); 86 | } 87 | 88 | log.error("Error fetching from cache", exc); 89 | throw exc; 90 | } 91 | } 92 | 93 | return gerritChanges; 94 | } 95 | 96 | @Override 97 | public boolean doApprovals(Issue issue, List changes, String args, Preferences prefs) throws IOException { 98 | Set issueKeys = getIssueKeys(issue); 99 | 100 | boolean result = true; 101 | for (String issueKey : issueKeys) { 102 | GerritCommand command = new GerritCommand(configuration, prefs); 103 | 104 | boolean commandResult = command.doReviews(changes, args); 105 | result &= commandResult; 106 | 107 | if (log.isDebugEnabled()) { 108 | log.trace("doApprovals " + issueKey + ", " + changes + ", " + args + "; result=" + commandResult); 109 | } 110 | 111 | // Something probably changed! 112 | cache.remove(issueKey); 113 | } 114 | 115 | return result; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/IssueReviewsManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 17 | 18 | import com.atlassian.core.user.preferences.Preferences; 19 | import com.atlassian.jira.issue.Issue; 20 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 21 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryHandler; 22 | 23 | import net.sf.json.JSONObject; 24 | 25 | import java.io.IOException; 26 | import java.util.List; 27 | import java.util.Set; 28 | 29 | public interface IssueReviewsManager { 30 | 31 | /** 32 | * Gets all Gerrit reviews related to the {@link Issue#getKey() specified issue key and all previus keys associated with the issue}. 33 | * 34 | * @param issue JIRA issue 35 | * @return A set of unique issue keys, including actual one 36 | */ 37 | Set getIssueKeys(Issue issue); 38 | 39 | /** 40 | * Gets all Gerrit reviews related to the {@link Issue#getKey() specific issue key}. 41 | * 42 | * @param issue the JIRA issue 43 | * @return A list of {@link JSONObject}s, as retrieved from Gerrit. 44 | * @throws GerritQueryException If any failure occurs while querying the Gerrit server. 45 | * @see GerritQueryHandler 46 | */ 47 | List getReviewsForIssue(Issue issue) throws GerritQueryException; 48 | 49 | /** 50 | * Performs approvals/reviews of all changes. 51 | * 52 | * @param issue the JIRA issue 53 | * @param changes the set of Gerrit changes 54 | * @param args arguments to add to each approval 55 | * @param prefs the {@link Preferences} for the viewing user 56 | * @return whether the approvals were successful 57 | * @throws IOException if so 58 | */ 59 | boolean doApprovals(Issue issue, List changes, String args, Preferences prefs) throws IOException; 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/dto/GerritApproval.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data.dto; 15 | 16 | import com.atlassian.jira.user.ApplicationUser; 17 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.attr.Approval; 18 | 19 | import net.sf.json.JSONObject; 20 | 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import static com.meetme.plugins.jira.gerrit.tabpanel.GerritEventKeys.BY; 25 | import static com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEventKeys.EMAIL; 26 | import static com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEventKeys.NAME; 27 | 28 | public class GerritApproval extends Approval implements Comparable { 29 | private static final Logger log = LoggerFactory.getLogger(GerritApproval.class); 30 | 31 | /** The approver's name */ 32 | private String by; 33 | /** The approver's email */ 34 | private String byEmail; 35 | /** The JIRA user associated with the same email */ 36 | private ApplicationUser user; 37 | 38 | public GerritApproval() { 39 | super(); 40 | } 41 | 42 | /** 43 | * Creates the PatchSetApproval from a {@link JSONObject}. 44 | * 45 | * @param json the JSON object with corresponding data. 46 | */ 47 | public GerritApproval(JSONObject json) { 48 | super(json); 49 | } 50 | 51 | public void setUser(ApplicationUser user) { 52 | this.user = user; 53 | } 54 | 55 | public ApplicationUser getUser() { 56 | return this.user; 57 | } 58 | 59 | @Override 60 | public void fromJson(JSONObject json) { 61 | log.debug("GerritApproval from json: " + json.toString(4, 0)); 62 | super.fromJson(json); 63 | 64 | if (json.containsKey(BY)) { 65 | JSONObject by = json.getJSONObject(BY); 66 | 67 | if (by.containsKey(NAME)) { 68 | this.setBy(by.getString(NAME)); 69 | } 70 | 71 | if (by.containsKey(EMAIL)) { 72 | this.setByEmail(by.getString(EMAIL)); 73 | } 74 | } 75 | } 76 | 77 | @Override 78 | public String getType() { 79 | return getUpgradedLabelType(super.getType()); 80 | } 81 | 82 | public static String getUpgradedLabelType(String type) { 83 | // XXX: Older Gerrit versions had compact abbreviations for approval types; 84 | // translate those old abbreviations to the new expected types 85 | 86 | if ("CRVW".equals(type)) { 87 | return "Code-Review"; 88 | } else if ("VRIF".equals(type)) { 89 | return "Verified"; 90 | } 91 | 92 | return type; 93 | } 94 | 95 | /** 96 | * Returns the approver's name. 97 | * 98 | * @return Approver's name as a string. 99 | */ 100 | public String getBy() { 101 | return by; 102 | } 103 | 104 | /** 105 | * Sets the approver's name. 106 | * 107 | * @param by Approver's name 108 | */ 109 | public void setBy(String by) { 110 | this.by = by; 111 | } 112 | 113 | /** 114 | * Returns the approval score as an integer. 115 | * 116 | * @return the integer approval score 117 | */ 118 | public int getValueAsInt() { 119 | String value = getValue(); 120 | 121 | if (value != null) { 122 | return Integer.parseInt(getValue(), 10); 123 | } 124 | 125 | return 0; 126 | } 127 | 128 | public String getByEmail() { 129 | return byEmail; 130 | } 131 | 132 | public void setByEmail(String byEmail) { 133 | this.byEmail = byEmail; 134 | } 135 | 136 | @Override 137 | public int compareTo(GerritApproval o) { 138 | int lhs = getValueAsInt(); 139 | int rhs = o.getValueAsInt(); 140 | 141 | if (lhs == rhs) { 142 | return 0; 143 | } 144 | 145 | return lhs > rhs ? 1 : -1; 146 | } 147 | 148 | @Override 149 | public String toString() { 150 | int value = getValueAsInt(); 151 | return (value > 0 ? "+" : "") + value + " by " + getBy(); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/dto/GerritChange.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data.dto; 15 | 16 | import com.meetme.plugins.jira.gerrit.tabpanel.GerritEventKeys; 17 | 18 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.attr.Change; 19 | 20 | import net.sf.json.JSONObject; 21 | 22 | import java.util.Date; 23 | 24 | import static com.meetme.plugins.jira.gerrit.tabpanel.GerritEventKeys.LAST_UPDATED; 25 | 26 | /** 27 | * @author Joe Hansche 28 | */ 29 | public class GerritChange extends Change implements Comparable { 30 | 31 | private Date lastUpdated; 32 | 33 | private GerritPatchSet patchSet; 34 | 35 | private boolean isOpen; 36 | 37 | private String status; 38 | 39 | public GerritChange() { 40 | super(); 41 | } 42 | 43 | public GerritChange(JSONObject obj) { 44 | super(obj); 45 | } 46 | 47 | /** 48 | * Sorts {@link GerritChange}s in order by their Gerrit change number. 49 | *

50 | * TODO: To be completely accurate, the changes should impose a dependency-tree ordering (via 51 | * --dependencies option) to GerritQuery! It is possible for an earlier ChangeId to be 52 | * refactored such that it is then dependent on a later change! 53 | */ 54 | @Override 55 | @SuppressWarnings("deprecation") 56 | public int compareTo(GerritChange obj) { 57 | if (this != obj && obj != null) { 58 | int aNum = Integer.parseInt(this.getNumber()); 59 | int bNum = Integer.parseInt(obj.getNumber()); 60 | 61 | if (aNum == bNum) { 62 | return 0; 63 | } else { 64 | return aNum < bNum ? -1 : 1; 65 | } 66 | } 67 | 68 | return 0; 69 | } 70 | 71 | @Override 72 | public void fromJson(JSONObject json) { 73 | super.fromJson(json); 74 | 75 | this.lastUpdated = new Date(1000 * json.getLong(LAST_UPDATED)); 76 | 77 | if (json.containsKey(GerritEventKeys.CURRENT_PATCH_SET)) { 78 | this.patchSet = new GerritPatchSet(json.getJSONObject(GerritEventKeys.CURRENT_PATCH_SET)); 79 | } 80 | 81 | if (json.containsKey(GerritEventKeys.STATUS)) { 82 | this.setStatus(json.getString(GerritEventKeys.STATUS)); 83 | } 84 | 85 | this.isOpen = json.getBoolean(GerritEventKeys.OPEN); 86 | } 87 | 88 | public Date getLastUpdated() { 89 | return lastUpdated; 90 | } 91 | 92 | public GerritPatchSet getPatchSet() { 93 | return patchSet; 94 | } 95 | 96 | public String getStatus() { 97 | return status; 98 | } 99 | 100 | public boolean isOpen() { 101 | return isOpen; 102 | } 103 | 104 | public void setLastUpdated(Date lastUpdated) { 105 | this.lastUpdated = lastUpdated; 106 | } 107 | 108 | public void setOpen(boolean isOpen) { 109 | this.isOpen = isOpen; 110 | } 111 | 112 | public void setPatchSet(GerritPatchSet patchSet) { 113 | this.patchSet = patchSet; 114 | } 115 | 116 | public void setStatus(String status) { 117 | this.status = status; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/data/dto/GerritPatchSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data.dto; 15 | 16 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEventKeys; 17 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.attr.PatchSet; 18 | 19 | import net.sf.json.JSONArray; 20 | import net.sf.json.JSONObject; 21 | 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import java.util.ArrayList; 26 | import java.util.HashMap; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | public class GerritPatchSet extends PatchSet { 31 | private static final Logger log = LoggerFactory.getLogger(GerritPatchSet.class); 32 | 33 | private List approvals; 34 | 35 | public GerritPatchSet() { 36 | super(); 37 | } 38 | 39 | public GerritPatchSet(JSONObject json) { 40 | super(json); 41 | } 42 | 43 | @Override 44 | public void fromJson(JSONObject json) { 45 | log.debug("GerritPatchSet from json: " + json.toString(4, 0)); 46 | super.fromJson(json); 47 | 48 | if (json.containsKey(GerritEventKeys.APPROVALS)) { 49 | JSONArray eventApprovals = json.getJSONArray(GerritEventKeys.APPROVALS); 50 | approvals = new ArrayList(eventApprovals.size()); 51 | 52 | for (int i = 0; i < eventApprovals.size(); i++) { 53 | GerritApproval approval = new GerritApproval(eventApprovals.getJSONObject(i)); 54 | approvals.add(approval); 55 | } 56 | } else { 57 | log.warn("GerritPatchSet contains no approvals key."); 58 | } 59 | } 60 | 61 | public List getApprovals() { 62 | return approvals; 63 | } 64 | 65 | public Map> getApprovalsByLabel() { 66 | Map> map = new HashMap<>(); 67 | List l; 68 | 69 | for (GerritApproval approval : approvals) { 70 | String type = approval.getType(); 71 | 72 | l = map.computeIfAbsent(type, k -> new ArrayList<>()); 73 | 74 | l.add(approval); 75 | } 76 | 77 | return map; 78 | } 79 | 80 | public List getApprovalsForLabel(String label) { 81 | List filtered = new ArrayList<>(); 82 | 83 | if (approvals != null) { 84 | for (GerritApproval approval : approvals) { 85 | if (approval.getType().equals(label)) { 86 | filtered.add(approval); 87 | } 88 | } 89 | } 90 | 91 | return filtered; 92 | } 93 | 94 | public void setApprovals(List approvals) { 95 | this.approvals = approvals; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/tabpanel/GerritEventKeys.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | /** 17 | * Extension of {@link com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEventKeys 18 | * sonyericsson.GerritEventKeys} to provide additional missing keys. 19 | * 20 | * @author Joe Hansche 21 | */ 22 | public interface GerritEventKeys { 23 | public static final String APPROVALS = "approvals"; 24 | public static final String BY = "by"; 25 | public static final String CURRENT_PATCH_SET = "currentPatchSet"; 26 | public static final String LAST_UPDATED = "lastUpdated"; 27 | public static final String OPEN = "open"; 28 | public static final String STATUS = "status"; 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/tabpanel/GerritReviewIssueAction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritApproval; 17 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 18 | 19 | import com.atlassian.core.util.map.EasyMap; 20 | import com.atlassian.jira.datetime.DateTimeFormatter; 21 | import com.atlassian.jira.datetime.DateTimeStyle; 22 | import com.atlassian.jira.plugin.issuetabpanel.AbstractIssueAction; 23 | import com.atlassian.jira.plugin.issuetabpanel.IssueAction; 24 | import com.atlassian.jira.plugin.issuetabpanel.IssueTabPanelModuleDescriptor; 25 | 26 | import java.util.*; 27 | 28 | public class GerritReviewIssueAction extends AbstractIssueAction implements IssueAction { 29 | private String baseUrl; 30 | private GerritChange change; 31 | private DateTimeFormatter dateTimeFormatter; 32 | 33 | public GerritReviewIssueAction(IssueTabPanelModuleDescriptor descriptor, GerritChange change, 34 | DateTimeFormatter dateTimeFormatter, String baseUrl) { 35 | super(descriptor); 36 | this.dateTimeFormatter = dateTimeFormatter.forLoggedInUser(); 37 | this.baseUrl = baseUrl; 38 | this.change = change; 39 | } 40 | 41 | @Override 42 | @SuppressWarnings("unchecked") 43 | protected void populateVelocityParams(@SuppressWarnings("rawtypes") Map params) { 44 | params.putAll(EasyMap.build("change", change, 45 | "formatLastUpdated", formatLastUpdated(), 46 | "isoLastUpdated", isoFormatLastUpdated(), 47 | "baseurl", this.baseUrl)); 48 | } 49 | 50 | String formatLastUpdated() { 51 | return dateTimeFormatter.format(change.getLastUpdated()); 52 | } 53 | 54 | String isoFormatLastUpdated() { 55 | return dateTimeFormatter.withStyle(DateTimeStyle.ISO_8601_DATE_TIME).format(change.getLastUpdated()); 56 | } 57 | 58 | @Override 59 | public Date getTimePerformed() { 60 | return change.getLastUpdated(); 61 | } 62 | 63 | @Override 64 | public boolean isDisplayActionAllTab() { 65 | return true; 66 | } 67 | 68 | /** 69 | * Returns the lowest score below 0 if available; otherwise the highest score above 0. 70 | * 71 | * @param approvals the approvals found on the Gerrit review 72 | * @return the approval that is deemed the "most significant" 73 | * @deprecated This functionality can now be found in the velocity template 74 | */ 75 | @Deprecated 76 | GerritApproval getMostSignificantScore(final List approvals) { 77 | if (approvals != null) { 78 | try { 79 | GerritApproval min = Collections.min(approvals); 80 | GerritApproval max = Collections.max(approvals); 81 | 82 | if (min == max) { 83 | // Means there was only 1 vote, so show that one. 84 | return max; 85 | } 86 | 87 | if (min.getValueAsInt() < 0) { 88 | // There exists a negative vote, so show that one. 89 | return min; 90 | } else { 91 | // NOTE: Technically not possible to have a 0-score, but if one exists, use it! 92 | // No negative votes, so show the highest positive vote 93 | return max; 94 | } 95 | } catch (NoSuchElementException nsee) { 96 | // Collection was empty 97 | } 98 | } 99 | 100 | return null; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/tabpanel/GerritReviewsTabPanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 17 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 18 | import com.meetme.plugins.jira.gerrit.data.dto.GerritApproval; 19 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 20 | import com.meetme.plugins.jira.gerrit.data.dto.GerritPatchSet; 21 | 22 | import com.atlassian.jira.bc.user.search.UserSearchService; 23 | import com.atlassian.jira.datetime.DateTimeFormatter; 24 | import com.atlassian.jira.issue.Issue; 25 | import com.atlassian.jira.issue.tabpanels.GenericMessageAction; 26 | import com.atlassian.jira.plugin.issuetabpanel.*; 27 | import com.atlassian.jira.user.ApplicationUser; 28 | import com.atlassian.jira.user.UserUtils; 29 | import com.atlassian.jira.user.util.UserManager; 30 | import com.atlassian.sal.api.ApplicationProperties; 31 | import com.atlassian.sal.api.message.I18nResolver; 32 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 33 | 34 | import org.slf4j.Logger; 35 | import org.slf4j.LoggerFactory; 36 | 37 | import java.util.ArrayList; 38 | import java.util.Iterator; 39 | import java.util.List; 40 | 41 | /** 42 | * An {@link IssueTabPanel2 issue tab panel} for displaying all Gerrit code reviews related to this 43 | * issue. 44 | * 45 | * @author Joe Hansche 46 | */ 47 | public class GerritReviewsTabPanel extends AbstractIssueTabPanel2 implements IssueTabPanel2 { 48 | private static final Logger log = LoggerFactory.getLogger(GerritReviewsTabPanel.class); 49 | 50 | private final DateTimeFormatter dateTimeFormatter; 51 | private final ApplicationProperties applicationProperties; 52 | private final GerritConfiguration configuration; 53 | private final IssueReviewsManager reviewsManager; 54 | private final I18nResolver i18n; 55 | 56 | @Deprecated 57 | private final UserManager userManager; 58 | private final UserSearchService userSearchService; 59 | 60 | public GerritReviewsTabPanel( 61 | @Deprecated UserManager userManager, 62 | UserSearchService userSearchService, 63 | DateTimeFormatter dateTimeFormatter, 64 | ApplicationProperties applicationProperties, 65 | GerritConfiguration configuration, 66 | IssueReviewsManager reviewsManager, 67 | I18nResolver i18n 68 | ) { 69 | this.userManager = userManager; 70 | this.userSearchService = userSearchService; 71 | this.dateTimeFormatter = dateTimeFormatter; 72 | this.applicationProperties = applicationProperties; 73 | this.configuration = configuration; 74 | this.reviewsManager = reviewsManager; 75 | this.i18n = i18n; 76 | } 77 | 78 | @Override 79 | public GetActionsReply getActions(GetActionsRequest request) { 80 | List issueActions; 81 | 82 | if (configuration.getSshHostname() == null || configuration.getSshUsername() == null || configuration.getSshPrivateKey() == null) { 83 | // Show not-configured error. 84 | issueActions = new ArrayList<>(); 85 | issueActions.add(new GenericMessageAction("Configure Gerrit in Administration interface first.")); 86 | } else { 87 | // List of items we will be showing in the tab panel. 88 | issueActions = getActions(request.issue()); 89 | } 90 | 91 | return GetActionsReply.create(issueActions); 92 | } 93 | 94 | @Override 95 | public ShowPanelReply showPanel(ShowPanelRequest arg0) { 96 | boolean isShowing = true; 97 | 98 | if (!isConfigurationReady()) { 99 | isShowing = false; 100 | } 101 | 102 | return ShowPanelReply.create(isShowing); 103 | } 104 | 105 | /** 106 | * Get all {@link GerritReviewIssueAction}s related to the specified {@link Issue#getKey() issue 107 | * key}. 108 | * 109 | * @param issue the JIRA issue key 110 | * @return the set of {@link IssueAction}s for the issue 111 | */ 112 | private List getActions(Issue issue) { 113 | log.debug("Getting actions for issue: {0}", issue.getKey()); 114 | 115 | List issueActions = new ArrayList<>(); 116 | List reviews; 117 | 118 | try { 119 | reviews = reviewsManager.getReviewsForIssue(issue); 120 | } catch (GerritQueryException exc) { 121 | exc.printStackTrace(); 122 | issueActions.add(new GenericMessageAction(exc.getMessage())); 123 | return issueActions; 124 | } 125 | 126 | if (reviews.isEmpty()) { 127 | issueActions.add(new GenericMessageAction(i18n.getText("gerrit.tabpanel.no_changes"))); 128 | } else { 129 | for (GerritChange change : reviews) { 130 | setUsersForChangeApprovals(change); 131 | issueActions.add(new GerritReviewIssueAction(descriptor(), change, dateTimeFormatter, applicationProperties.getBaseUrl())); 132 | // issueActions.add(new GenericMessageAction("

" + obj.toString(4) + "
")); 133 | } 134 | } 135 | 136 | return issueActions; 137 | } 138 | 139 | private ApplicationUser getUserByEmail(String email) { 140 | ApplicationUser user = null; 141 | 142 | if (email != null) { 143 | Iterator users = userSearchService.findUsersByEmail(email).iterator(); 144 | if (users.hasNext()) user = users.next(); 145 | 146 | if (user == null) user = UserUtils.getUserByEmail(email); 147 | 148 | if (user == null) { 149 | for (ApplicationUser iUser : userManager.getUsers()) { 150 | if (email.equalsIgnoreCase(iUser.getEmailAddress())) { 151 | user = iUser; 152 | break; 153 | } 154 | } 155 | } 156 | } 157 | 158 | return user; 159 | } 160 | 161 | private boolean isConfigurationReady() { 162 | return configuration.getSshHostname() != null && configuration.getSshUsername() != null 163 | && configuration.getSshPrivateKey() != null && configuration.getSshPrivateKey().exists(); 164 | } 165 | 166 | private void setUsersForChangeApprovals(GerritChange change) { 167 | GerritPatchSet ps = change.getPatchSet(); 168 | 169 | if (ps != null) { 170 | List approvals = ps.getApprovals(); 171 | 172 | if (approvals != null) { 173 | for (GerritApproval approval : change.getPatchSet().getApprovals()) { 174 | String byEmail = approval.getByEmail(); 175 | approval.setUser(getUserByEmail(byEmail)); 176 | } 177 | } 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/tabpanel/SubtaskReviewsIssueAction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 17 | import com.meetme.plugins.jira.gerrit.workflow.condition.NoOpenReviews; 18 | 19 | import com.atlassian.jira.issue.Issue; 20 | import com.atlassian.jira.plugin.issuetabpanel.AbstractIssueAction; 21 | import com.atlassian.jira.plugin.issuetabpanel.IssueAction; 22 | import com.atlassian.jira.plugin.issuetabpanel.IssueTabPanelModuleDescriptor; 23 | 24 | import java.util.Date; 25 | import java.util.List; 26 | import java.util.Map; 27 | 28 | /** 29 | * @author Joe Hansche 30 | */ 31 | public class SubtaskReviewsIssueAction extends AbstractIssueAction implements IssueAction { 32 | 33 | private Issue subtask; 34 | private List changes; 35 | 36 | public SubtaskReviewsIssueAction(IssueTabPanelModuleDescriptor descriptor, Issue subtask, List changes) { 37 | super(descriptor); 38 | 39 | this.subtask = subtask; 40 | this.changes = changes; 41 | } 42 | 43 | @Override 44 | public Date getTimePerformed() { 45 | return subtask.getUpdated(); 46 | } 47 | 48 | @SuppressWarnings("unchecked") 49 | @Override 50 | protected void populateVelocityParams(@SuppressWarnings("rawtypes") Map velocityParams) { 51 | final int openReviews = changes == null ? 0 : NoOpenReviews.countReviewStatus(changes, true); 52 | final int closedReviews = changes == null ? 0 : NoOpenReviews.countReviewStatus(changes, false); 53 | 54 | // push data 55 | velocityParams.put("subtask", subtask); 56 | velocityParams.put("changes", changes); 57 | velocityParams.put("openReviews", openReviews); 58 | velocityParams.put("closedReviews", closedReviews); 59 | } 60 | 61 | @Override 62 | public boolean isDisplayActionAllTab() { 63 | return false; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/tabpanel/SubtaskReviewsTabPanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 17 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 18 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 19 | 20 | import com.atlassian.jira.issue.Issue; 21 | import com.atlassian.jira.plugin.issuetabpanel.*; 22 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 23 | 24 | import java.util.ArrayList; 25 | import java.util.Collection; 26 | import java.util.List; 27 | 28 | public class SubtaskReviewsTabPanel extends AbstractIssueTabPanel2 implements IssueTabPanel2 { 29 | private final GerritConfiguration configuration; 30 | private final IssueReviewsManager reviewsManager; 31 | 32 | public SubtaskReviewsTabPanel(GerritConfiguration configuration, 33 | IssueReviewsManager reviewsManager) { 34 | this.configuration = configuration; 35 | this.reviewsManager = reviewsManager; 36 | } 37 | 38 | @Override 39 | public GetActionsReply getActions(GetActionsRequest request) { 40 | Collection subtasks = request.issue().getSubTaskObjects(); 41 | List actions = new ArrayList<>(); 42 | List changes; 43 | 44 | for (Issue subtask : subtasks) { 45 | try { 46 | changes = getChanges(subtask); 47 | } catch (GerritQueryException e) { 48 | throw new RuntimeException(e); 49 | } 50 | 51 | actions.add(new SubtaskReviewsIssueAction(descriptor(), subtask, changes)); 52 | } 53 | 54 | return GetActionsReply.create(actions); 55 | } 56 | 57 | @Override 58 | public ShowPanelReply showPanel(ShowPanelRequest request) { 59 | boolean show = false; 60 | 61 | if (isConfigurationReady()) { 62 | Collection subtasks = request.issue().getSubTaskObjects(); 63 | show = subtasks != null && subtasks.size() > 0; 64 | } 65 | 66 | return ShowPanelReply.create(show); 67 | } 68 | 69 | private List getChanges(Issue subtask) throws GerritQueryException { 70 | return reviewsManager.getReviewsForIssue(subtask); 71 | } 72 | 73 | private boolean isConfigurationReady() { 74 | final GerritConfiguration configuration = this.configuration; 75 | 76 | return configuration != null && configuration.getSshHostname() != null && configuration.getSshUsername() != null 77 | && configuration.getSshPrivateKey() != null && configuration.getSshPrivateKey().exists(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/webpanel/GerritReviewsIssueAgilePanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.webpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 17 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 18 | 19 | import com.atlassian.jira.issue.Issue; 20 | import com.atlassian.jira.plugin.webfragment.contextproviders.AbstractJiraContextProvider; 21 | import com.atlassian.jira.plugin.webfragment.model.JiraHelper; 22 | import com.atlassian.jira.user.ApplicationUser; 23 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 24 | 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | @SuppressWarnings("unchecked") 30 | public class GerritReviewsIssueAgilePanel extends AbstractJiraContextProvider { 31 | private static final String KEY_ISSUE = "issue"; 32 | private static final String KEY_CHANGES = "changes"; 33 | private static final String KEY_ERROR = "error"; 34 | 35 | private IssueReviewsManager reviewsManager; 36 | 37 | public GerritReviewsIssueAgilePanel(IssueReviewsManager reviewsManager) { 38 | super(); 39 | this.reviewsManager = reviewsManager; 40 | } 41 | 42 | @Override 43 | public Map getContextMap(ApplicationUser user, JiraHelper jiraHelper) { 44 | HashMap contextMap = new HashMap<>(); 45 | 46 | Issue currentIssue = (Issue) jiraHelper.getContextParams().get(KEY_ISSUE); 47 | 48 | try { 49 | List changes = reviewsManager.getReviewsForIssue(currentIssue); 50 | contextMap.put(KEY_CHANGES, changes); 51 | contextMap.put("atl.gh.issue.details.tab.count", (long) changes.size()); 52 | } catch (GerritQueryException e) { 53 | contextMap.put(KEY_ERROR, e.getMessage()); 54 | } 55 | 56 | return contextMap; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/webpanel/GerritReviewsIssueSidePanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.webpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 17 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 18 | 19 | import com.atlassian.jira.issue.Issue; 20 | import com.atlassian.jira.plugin.webfragment.contextproviders.AbstractJiraContextProvider; 21 | import com.atlassian.jira.plugin.webfragment.model.JiraHelper; 22 | import com.atlassian.jira.user.ApplicationUser; 23 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 24 | 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | @SuppressWarnings("unchecked") 30 | public class GerritReviewsIssueSidePanel extends AbstractJiraContextProvider { 31 | private static final String KEY_ISSUE = "issue"; 32 | private static final String KEY_CHANGES = "changes"; 33 | private static final String KEY_ERROR = "error"; 34 | 35 | private IssueReviewsManager reviewsManager; 36 | 37 | public GerritReviewsIssueSidePanel(IssueReviewsManager reviewsManager) { 38 | super(); 39 | this.reviewsManager = reviewsManager; 40 | } 41 | 42 | @Override 43 | public Map getContextMap(ApplicationUser user, JiraHelper jiraHelper) { 44 | HashMap contextMap = new HashMap<>(); 45 | 46 | Issue currentIssue = (Issue) jiraHelper.getContextParams().get(KEY_ISSUE); 47 | 48 | try { 49 | List changes = reviewsManager.getReviewsForIssue(currentIssue); 50 | contextMap.put(KEY_CHANGES, changes); 51 | } catch (GerritQueryException e) { 52 | contextMap.put(KEY_ERROR, e.getMessage()); 53 | } 54 | 55 | return contextMap; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/webpanel/IssueStatusOptionsProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.webpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.SessionKeys; 17 | 18 | import com.atlassian.jira.issue.Issue; 19 | import com.atlassian.jira.security.JiraAuthenticationContext; 20 | import com.atlassian.jira.util.I18nHelper; 21 | import com.atlassian.jira.util.collect.CollectionBuilder; 22 | import com.atlassian.jira.util.velocity.VelocityRequestContext; 23 | import com.atlassian.jira.util.velocity.VelocityRequestContextFactory; 24 | import com.atlassian.jira.util.velocity.VelocityRequestSession; 25 | import com.atlassian.plugin.web.api.WebItem; 26 | import com.atlassian.plugin.web.api.model.WebFragmentBuilder; 27 | import com.atlassian.plugin.web.api.provider.WebItemProvider; 28 | 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | 32 | import java.util.Collections; 33 | import java.util.Map; 34 | 35 | public class IssueStatusOptionsProvider implements WebItemProvider { 36 | private static final Logger log = LoggerFactory.getLogger(IssueStatusOptionsProvider.class); 37 | 38 | private static final String STATUS_OPEN = "Open"; 39 | private static final String STATUS_ALL = "All"; 40 | static final String DEFAULT_STATUS = STATUS_OPEN; 41 | 42 | private VelocityRequestContextFactory requestContextFactory; 43 | private JiraAuthenticationContext authenticationContext; 44 | 45 | public IssueStatusOptionsProvider(VelocityRequestContextFactory requestContextFactory, JiraAuthenticationContext authenticationContext) { 46 | this.requestContextFactory = requestContextFactory; 47 | this.authenticationContext = authenticationContext; 48 | } 49 | 50 | @Override 51 | public Iterable getItems(Map params) { 52 | final VelocityRequestContext requestContext = requestContextFactory.getJiraVelocityRequestContext(); 53 | final I18nHelper i18n = authenticationContext.getI18nHelper(); 54 | final Issue issue = (Issue) params.get("issue"); 55 | 56 | final VelocityRequestSession session = requestContext.getSession(); 57 | final String baseUrl = requestContext.getBaseUrl(); 58 | 59 | String issueStatus = (String) session.getAttribute(SessionKeys.VIEWISSUE_REVIEWS_ISSUESTATUS); 60 | 61 | if (issueStatus == null) { 62 | issueStatus = DEFAULT_STATUS; 63 | } 64 | 65 | if (issue.getSubTaskObjects().isEmpty() && isIssueOpen(issue)) { 66 | return Collections.emptyList(); 67 | } 68 | 69 | int weight = 10; 70 | 71 | final WebItem allLink = new WebFragmentBuilder(weight += 10) 72 | .id("reviews-issuestatus-all") 73 | .label(i18n.getText("gerrit-reviews-left-panel.options.issuestatus.all")) 74 | .styleClass(getStyleFor(issueStatus, STATUS_ALL)) 75 | .webItem("issuestatus-view-options") 76 | .url(getUrlForType(STATUS_ALL, baseUrl, issue)) 77 | .build(); 78 | 79 | WebItem openLink = new WebFragmentBuilder(weight += 10) 80 | .id("reviews-issuestatus-open") 81 | .label(i18n.getText("gerrit-reviews-left-panel.options.issuestatus.open")) 82 | .styleClass(getStyleFor(issueStatus, STATUS_OPEN)) 83 | .webItem("issuestatus-view-options") 84 | .url(getUrlForType(STATUS_OPEN, baseUrl, issue)) 85 | .build(); 86 | 87 | return CollectionBuilder.list(allLink, openLink); 88 | } 89 | 90 | private String getUrlForType(String type, String baseUrl, Issue issue) { 91 | return baseUrl + "/browse/" + issue.getKey() + "?gerritIssueStatus=" + type + "#gerrit-reviews-left-panel"; 92 | } 93 | 94 | private String getStyleFor(String type, String expecting) { 95 | return expecting.equals(type) ? "aui-list-checked aui-checked" : "aui-list-checked"; 96 | } 97 | 98 | static boolean isIssueOpen(Issue issue) { 99 | log.debug("Checking if " + issue.getKey() + " is open: " + issue.getResolutionObject()); 100 | return issue.getResolutionObject() == null; 101 | } 102 | 103 | static boolean wantsUnresolved(final String gerritIssueStatus) { 104 | return STATUS_ALL.equals(gerritIssueStatus); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/webpanel/IssueTypeOptionsProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.webpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.SessionKeys; 17 | 18 | import com.atlassian.jira.issue.Issue; 19 | import com.atlassian.jira.security.JiraAuthenticationContext; 20 | import com.atlassian.jira.util.I18nHelper; 21 | import com.atlassian.jira.util.collect.CollectionBuilder; 22 | import com.atlassian.jira.util.velocity.VelocityRequestContext; 23 | import com.atlassian.jira.util.velocity.VelocityRequestContextFactory; 24 | import com.atlassian.jira.util.velocity.VelocityRequestSession; 25 | import com.atlassian.plugin.web.api.WebItem; 26 | import com.atlassian.plugin.web.api.model.WebFragmentBuilder; 27 | import com.atlassian.plugin.web.api.provider.WebItemProvider; 28 | 29 | import org.apache.commons.lang.StringUtils; 30 | import org.slf4j.Logger; 31 | import org.slf4j.LoggerFactory; 32 | 33 | import java.util.Map; 34 | 35 | public class IssueTypeOptionsProvider implements WebItemProvider { 36 | private static final Logger log = LoggerFactory.getLogger(IssueTypeOptionsProvider.class); 37 | 38 | public static final String ISSUE_ONLY = "IssueOnly"; 39 | public static final String SUBTASK_ONLY = "SubtaskOnly"; 40 | public static final String ALL_ISSUES = "All"; 41 | 42 | public static final String DEFAULT_ISSUE_TYPE = ISSUE_ONLY; 43 | 44 | private VelocityRequestContextFactory requestContextFactory; 45 | private JiraAuthenticationContext authenticationContext; 46 | 47 | public IssueTypeOptionsProvider(VelocityRequestContextFactory requestContextFactory, JiraAuthenticationContext authenticationContext) { 48 | this.requestContextFactory = requestContextFactory; 49 | this.authenticationContext = authenticationContext; 50 | } 51 | 52 | @Override 53 | public Iterable getItems(Map params) { 54 | final VelocityRequestContext requestContext = requestContextFactory.getJiraVelocityRequestContext(); 55 | final I18nHelper i18n = authenticationContext.getI18nHelper(); 56 | final Issue issue = (Issue) params.get("issue"); 57 | 58 | final VelocityRequestSession session = requestContext.getSession(); 59 | final String baseUrl = requestContext.getBaseUrl(); 60 | 61 | String issueType = (String) session.getAttribute(SessionKeys.VIEWISSUE_REVIEWS_ISSUETYPE); 62 | 63 | if (StringUtils.isEmpty(issueType) || issue.getSubTaskObjects().isEmpty()) { 64 | issueType = DEFAULT_ISSUE_TYPE; 65 | } 66 | 67 | int weight = 10; 68 | WebItem issueOnlyLink = new WebFragmentBuilder(weight += 10) 69 | .id("reviews-issuetype-issueonly") 70 | .label(i18n.getText("gerrit-reviews-left-panel.options.issuetype.issue_only")) 71 | .styleClass(getStyleFor(issueType, ISSUE_ONLY)) 72 | .webItem("issuetype-view-options") 73 | .url(getUrlForType(ISSUE_ONLY, baseUrl, issue)) 74 | .build(); 75 | 76 | if (issue.getSubTaskObjects().isEmpty()) { 77 | // Contains no subtasks, so no reason to show the others 78 | return CollectionBuilder.list(issueOnlyLink); 79 | } 80 | 81 | // Contains subtasks, expose the other options now 82 | final WebItem subtaskOnlyLink = new WebFragmentBuilder(weight += 10) 83 | .id("reviews-issuetype-subtasksonly") 84 | .label(i18n.getText("gerrit-reviews-left-panel.options.issuetype.subtasks_only")) 85 | .styleClass(getStyleFor(issueType, SUBTASK_ONLY)) 86 | .webItem("issuetype-view-options") 87 | .url(getUrlForType(SUBTASK_ONLY, baseUrl, issue)) 88 | .build(); 89 | 90 | final WebItem allLink = new WebFragmentBuilder(weight += 10) 91 | .id("reviews-issuetype-all") 92 | .label(i18n.getText("gerrit-reviews-left-panel.options.issuetype.all")) 93 | .styleClass(getStyleFor(issueType, ALL_ISSUES)) 94 | .webItem("issuetype-view-options") 95 | .url(getUrlForType(ALL_ISSUES, baseUrl, issue)) 96 | .build(); 97 | 98 | return CollectionBuilder.list(issueOnlyLink, subtaskOnlyLink, allLink); 99 | } 100 | 101 | private String getUrlForType(String type, String baseUrl, Issue issue) { 102 | return baseUrl + "/browse/" + issue.getKey() + "?gerritIssueType=" + type 103 | + "#gerrit-reviews-left-panel"; 104 | } 105 | 106 | private String getStyleFor(String type, String expecting) { 107 | return expecting.equals(type) ? "aui-list-checked aui-checked" : "aui-list-checked"; 108 | } 109 | 110 | public static final boolean wantsSubtasks(final String gerritIssueType) { 111 | return SUBTASK_ONLY.equals(gerritIssueType) || ALL_ISSUES.equals(gerritIssueType); 112 | } 113 | 114 | public static final boolean wantsIssue(final String gerritIssueType) { 115 | return ISSUE_ONLY.equals(gerritIssueType) || ALL_ISSUES.equals(gerritIssueType); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/webpanel/ReviewStatusOptionsProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.webpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.SessionKeys; 17 | 18 | import com.atlassian.jira.issue.Issue; 19 | import com.atlassian.jira.security.JiraAuthenticationContext; 20 | import com.atlassian.jira.util.I18nHelper; 21 | import com.atlassian.jira.util.collect.CollectionBuilder; 22 | import com.atlassian.jira.util.velocity.VelocityRequestContext; 23 | import com.atlassian.jira.util.velocity.VelocityRequestContextFactory; 24 | import com.atlassian.jira.util.velocity.VelocityRequestSession; 25 | import com.atlassian.plugin.web.api.WebItem; 26 | import com.atlassian.plugin.web.api.model.WebFragmentBuilder; 27 | import com.atlassian.plugin.web.api.provider.WebItemProvider; 28 | 29 | import java.util.Map; 30 | 31 | public class ReviewStatusOptionsProvider implements WebItemProvider { 32 | public static final String STATUS_OPEN = "Open"; 33 | public static final String STATUS_ALL = "All"; 34 | public static final String DEFAULT_STATUS = STATUS_ALL; 35 | 36 | private VelocityRequestContextFactory requestContextFactory; 37 | private JiraAuthenticationContext authenticationContext; 38 | 39 | public ReviewStatusOptionsProvider(VelocityRequestContextFactory requestContextFactory, JiraAuthenticationContext authenticationContext) { 40 | this.requestContextFactory = requestContextFactory; 41 | this.authenticationContext = authenticationContext; 42 | } 43 | 44 | @Override 45 | public Iterable getItems(Map params) { 46 | final VelocityRequestContext requestContext = requestContextFactory.getJiraVelocityRequestContext(); 47 | final I18nHelper i18n = authenticationContext.getI18nHelper(); 48 | final Issue issue = (Issue) params.get("issue"); 49 | 50 | final VelocityRequestSession session = requestContext.getSession(); 51 | final String baseUrl = requestContext.getBaseUrl(); 52 | 53 | String reviewStatus = (String) session.getAttribute(SessionKeys.VIEWISSUE_REVIEWS_REVIEWSTATUS); 54 | 55 | if (reviewStatus == null) { 56 | reviewStatus = DEFAULT_STATUS; 57 | } 58 | 59 | int weight = 10; 60 | 61 | final WebItem allLink = new WebFragmentBuilder(weight += 10) 62 | .id("reviews-reviewstatus-all") 63 | .label(i18n.getText("gerrit-reviews-left-panel.options.reviewstatus.all")) 64 | .styleClass(getStyleFor(reviewStatus, STATUS_ALL)) 65 | .webItem("reviewstatus-view-options") 66 | .url(getUrlForType(STATUS_ALL, baseUrl, issue)) 67 | .build(); 68 | 69 | final WebItem openLink = new WebFragmentBuilder(weight += 10) 70 | .id("reviews-reviewstatus-open") 71 | .label(i18n.getText("gerrit-reviews-left-panel.options.reviewstatus.open")) 72 | .styleClass(getStyleFor(reviewStatus, STATUS_OPEN)) 73 | .webItem("reviewstatus-view-options") 74 | .url(getUrlForType(STATUS_OPEN, baseUrl, issue)) 75 | .build(); 76 | 77 | return CollectionBuilder.list(allLink, openLink); 78 | } 79 | 80 | private String getUrlForType(String type, String baseUrl, Issue issue) { 81 | return baseUrl + "/browse/" + issue.getKey() + "?gerritReviewStatus=" + type + "#gerrit-reviews-left-panel"; 82 | } 83 | 84 | private String getStyleFor(String type, String expecting) { 85 | return expecting.equals(type) ? "aui-list-checked aui-checked" : "aui-list-checked"; 86 | } 87 | 88 | public static boolean wantsClosedReviews(String gerritReviewStatus) { 89 | return STATUS_ALL.equals(gerritReviewStatus); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/webpanel/ShowReviewsWebPanelCondition.java: -------------------------------------------------------------------------------- 1 | package com.meetme.plugins.jira.gerrit.webpanel; 2 | 3 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 4 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 5 | 6 | import com.atlassian.jira.issue.Issue; 7 | import com.atlassian.plugin.web.Condition; 8 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 9 | 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import java.util.Map; 14 | 15 | import static org.apache.commons.collections.CollectionUtils.isEmpty; 16 | 17 | /** 18 | * Created by jhansche on 9/2/16. 19 | */ 20 | public class ShowReviewsWebPanelCondition implements Condition { 21 | 22 | private static final Logger log = LoggerFactory.getLogger(ShowReviewsWebPanelCondition.class); 23 | 24 | private static final String KEY_ISSUE = "issue"; 25 | 26 | private final GerritConfiguration gerritConfiguration; 27 | private final IssueReviewsManager issueReviewsManager; 28 | 29 | public ShowReviewsWebPanelCondition(IssueReviewsManager reviewsManager, GerritConfiguration configurationManager) { 30 | 31 | issueReviewsManager = reviewsManager; 32 | gerritConfiguration = configurationManager; 33 | } 34 | 35 | @Override 36 | public void init(Map map) { 37 | } 38 | 39 | @Override 40 | public boolean shouldDisplay(Map map) { 41 | 42 | if (map == null) { 43 | return false; 44 | } 45 | 46 | final Issue issue = (Issue) map.get(KEY_ISSUE); 47 | 48 | if (issue == null) { 49 | return false; 50 | } 51 | 52 | // Shall the system use the white list and does the issue belongs to a project, that uses gerrit: 53 | if (gerritConfiguration.getUseGerritProjectWhitelist() && !isGerritProject(issue)) { 54 | return false; 55 | } 56 | 57 | // Even though there are no reviews, the gerrit panel shall be displayed: 58 | if (gerritConfiguration.getShowsEmptyPanel()) { 59 | return true; 60 | } 61 | 62 | try { 63 | 64 | return !isEmpty(issueReviewsManager.getReviewsForIssue(issue)); 65 | } catch (GerritQueryException gerritQueryException) { 66 | 67 | log.warn(gerritQueryException.getLocalizedMessage(), gerritQueryException); 68 | return false; 69 | } 70 | } 71 | 72 | private boolean isGerritProject(final Issue issue) { 73 | 74 | return issue.getProjectId() != null 75 | && !isEmpty(gerritConfiguration.getIdsOfKnownGerritProjects()) 76 | && gerritConfiguration.getIdsOfKnownGerritProjects().contains(issue.getProjectId().toString()); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/workflow/ApprovalScoreConditionFactoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritApproval; 17 | import com.meetme.plugins.jira.gerrit.workflow.condition.ApprovalScore; 18 | 19 | import com.atlassian.core.util.map.EasyMap; 20 | import com.atlassian.jira.plugin.workflow.AbstractWorkflowPluginFactory; 21 | import com.atlassian.jira.plugin.workflow.WorkflowPluginConditionFactory; 22 | import com.opensymphony.workflow.loader.AbstractDescriptor; 23 | import com.opensymphony.workflow.loader.ConditionDescriptor; 24 | 25 | import java.util.Arrays; 26 | import java.util.Collections; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | public class ApprovalScoreConditionFactoryImpl extends AbstractWorkflowPluginFactory implements WorkflowPluginConditionFactory { 31 | private static final List ALL_PARAMS = Collections.unmodifiableList(Arrays.asList(ApprovalScore.KEY_NEGATIVE, 32 | ApprovalScore.KEY_COMPARISON, ApprovalScore.KEY_TARGET, ApprovalScore.KEY_LABEL)); 33 | 34 | private static final boolean DEFAULT_NEGATIVE = false; 35 | private static final ApprovalScore.ComparisonOperator DEFAULT_COMPARISON = ApprovalScore.ComparisonOperator.EQUAL_TO; 36 | private static final int DEFAULT_TARGET = 0; 37 | private static final String DEFAULT_LABEL = "Code-Review"; 38 | 39 | @SuppressWarnings("unchecked") 40 | @Override 41 | public Map getDescriptorParams(Map conditionParams) { 42 | if (conditionParams != null && conditionParams.containsKey(ApprovalScore.KEY_NEGATIVE) 43 | && conditionParams.containsKey(ApprovalScore.KEY_COMPARISON) && conditionParams.containsKey(ApprovalScore.KEY_TARGET) 44 | && conditionParams.containsKey(ApprovalScore.KEY_LABEL)) { 45 | return extractMultipleParams(conditionParams, ALL_PARAMS); 46 | } 47 | 48 | return EasyMap.build(); 49 | } 50 | 51 | @Override 52 | protected void getVelocityParamsForEdit(Map velocityParams, AbstractDescriptor descriptor) { 53 | velocityParams.put(ApprovalScore.KEY_NEGATIVE, isReversed(descriptor)); 54 | velocityParams.put(ApprovalScore.KEY_COMPARISON, getComparison(descriptor)); 55 | velocityParams.put(ApprovalScore.KEY_TARGET, getTarget(descriptor)); 56 | velocityParams.put(ApprovalScore.KEY_LABEL, getLabel(descriptor)); 57 | } 58 | 59 | @Override 60 | protected void getVelocityParamsForInput(Map velocityParams) { 61 | velocityParams.put(ApprovalScore.KEY_NEGATIVE, DEFAULT_NEGATIVE); 62 | velocityParams.put(ApprovalScore.KEY_COMPARISON, DEFAULT_COMPARISON); 63 | velocityParams.put(ApprovalScore.KEY_TARGET, DEFAULT_TARGET); 64 | velocityParams.put(ApprovalScore.KEY_LABEL, DEFAULT_LABEL); 65 | } 66 | 67 | @Override 68 | protected void getVelocityParamsForView(Map velocityParams, AbstractDescriptor descriptor) { 69 | velocityParams.put(ApprovalScore.KEY_NEGATIVE, isReversed(descriptor)); 70 | velocityParams.put(ApprovalScore.KEY_COMPARISON, getComparison(descriptor)); 71 | velocityParams.put(ApprovalScore.KEY_TARGET, getTarget(descriptor)); 72 | velocityParams.put(ApprovalScore.KEY_LABEL, getLabel(descriptor)); 73 | } 74 | 75 | private String getStringFromDescriptor(AbstractDescriptor descriptor, String key) { 76 | if (!(descriptor instanceof ConditionDescriptor)) { 77 | throw new IllegalArgumentException("Descriptor must be a ConditionDescriptor."); 78 | } 79 | 80 | ConditionDescriptor conditionDescriptor = (ConditionDescriptor) descriptor; 81 | 82 | return (String) conditionDescriptor.getArgs().get(key); 83 | } 84 | 85 | private boolean isReversed(AbstractDescriptor descriptor) { 86 | String value = getStringFromDescriptor(descriptor, ApprovalScore.KEY_NEGATIVE); 87 | return Boolean.parseBoolean(value); 88 | } 89 | 90 | private String getLabel(AbstractDescriptor descriptor) { 91 | return GerritApproval.getUpgradedLabelType(getStringFromDescriptor(descriptor, ApprovalScore.KEY_LABEL)); 92 | } 93 | 94 | private int getTarget(AbstractDescriptor descriptor) { 95 | String value = getStringFromDescriptor(descriptor, ApprovalScore.KEY_TARGET); 96 | return Integer.parseInt(value); 97 | } 98 | 99 | private ApprovalScore.ComparisonOperator getComparison(AbstractDescriptor descriptor) { 100 | String value = getStringFromDescriptor(descriptor, ApprovalScore.KEY_COMPARISON); 101 | return ApprovalScore.ComparisonOperator.valueOf(value); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/workflow/ApproveReviewFactoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow; 15 | 16 | import com.meetme.plugins.jira.gerrit.workflow.function.ApprovalFunction; 17 | 18 | import com.atlassian.core.util.map.EasyMap; 19 | import com.atlassian.jira.plugin.workflow.AbstractWorkflowPluginFactory; 20 | import com.atlassian.jira.plugin.workflow.WorkflowPluginFunctionFactory; 21 | import com.opensymphony.workflow.loader.AbstractDescriptor; 22 | import com.opensymphony.workflow.loader.FunctionDescriptor; 23 | 24 | import java.util.Map; 25 | 26 | public class ApproveReviewFactoryImpl extends AbstractWorkflowPluginFactory implements 27 | WorkflowPluginFunctionFactory { 28 | 29 | // 1. Review type and score (e.g., "--verified 1") -- one input or two? 30 | // 2. Message (e.g., --message "Ready for Test") 31 | // 3. Submit (--submit) 32 | 33 | // OR: [args] and let the admin fill it out? 34 | 35 | @SuppressWarnings("unchecked") 36 | @Override 37 | public Map getDescriptorParams(Map params) { 38 | if (params != null && params.containsKey(ApprovalFunction.KEY_CMD_ARGS)) { 39 | return EasyMap.build(ApprovalFunction.KEY_CMD_ARGS, extractSingleParam(params, ApprovalFunction.KEY_CMD_ARGS)); 40 | } 41 | 42 | // Create a 'hard coded' parameter 43 | return EasyMap.build(ApprovalFunction.KEY_CMD_ARGS, ApprovalFunction.DEFAULT_CMD_ARGS); 44 | } 45 | 46 | @Override 47 | protected void getVelocityParamsForEdit(Map velocityParams, AbstractDescriptor descriptor) { 48 | velocityParams.put(ApprovalFunction.KEY_CMD_ARGS, getCommandArgs(descriptor)); 49 | } 50 | 51 | @Override 52 | protected void getVelocityParamsForInput(Map velocityParams) { 53 | velocityParams.put(ApprovalFunction.KEY_CMD_ARGS, ApprovalFunction.DEFAULT_CMD_ARGS); 54 | } 55 | 56 | @Override 57 | protected void getVelocityParamsForView(Map velocityParams, AbstractDescriptor descriptor) { 58 | velocityParams.put(ApprovalFunction.KEY_CMD_ARGS, getCommandArgs(descriptor)); 59 | } 60 | 61 | private Object getCommandArgs(AbstractDescriptor descriptor) { 62 | if (!(descriptor instanceof FunctionDescriptor)) { 63 | throw new IllegalArgumentException("Descriptor must be a FunctionDescriptor."); 64 | } 65 | 66 | FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor; 67 | String args = (String) functionDescriptor.getArgs().get(ApprovalFunction.KEY_CMD_ARGS); 68 | 69 | if (args != null && args.trim().length() > 0) { 70 | return args; 71 | } else { 72 | return ApprovalFunction.DEFAULT_CMD_ARGS; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/workflow/NoOpenReviewsConditionFactoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow; 15 | 16 | import com.meetme.plugins.jira.gerrit.workflow.condition.NoOpenReviews; 17 | 18 | import com.atlassian.core.util.map.EasyMap; 19 | import com.atlassian.jira.plugin.workflow.AbstractWorkflowPluginFactory; 20 | import com.atlassian.jira.plugin.workflow.WorkflowPluginConditionFactory; 21 | import com.opensymphony.workflow.loader.AbstractDescriptor; 22 | import com.opensymphony.workflow.loader.ConditionDescriptor; 23 | 24 | import java.util.Map; 25 | 26 | public class NoOpenReviewsConditionFactoryImpl extends AbstractWorkflowPluginFactory implements WorkflowPluginConditionFactory { 27 | 28 | @SuppressWarnings("unchecked") 29 | @Override 30 | public Map getDescriptorParams(Map conditionParams) { 31 | if (conditionParams != null && conditionParams.containsKey(NoOpenReviews.KEY_REVERSED)) { 32 | return EasyMap.build(NoOpenReviews.KEY_REVERSED, extractSingleParam(conditionParams, NoOpenReviews.KEY_REVERSED)); 33 | } 34 | 35 | return EasyMap.build(); 36 | } 37 | 38 | @Override 39 | protected void getVelocityParamsForEdit(Map velocityParams, AbstractDescriptor descriptor) { 40 | velocityParams.put(NoOpenReviews.KEY_REVERSED, isReversed(descriptor)); 41 | } 42 | 43 | @Override 44 | protected void getVelocityParamsForInput(Map velocityParams) { 45 | // Nothing to choose from, because boolean is only ON/OFF 46 | } 47 | 48 | @Override 49 | protected void getVelocityParamsForView(Map velocityParams, AbstractDescriptor descriptor) { 50 | velocityParams.put(NoOpenReviews.KEY_REVERSED, isReversed(descriptor)); 51 | } 52 | 53 | private boolean isReversed(AbstractDescriptor descriptor) { 54 | if (!(descriptor instanceof ConditionDescriptor)) { 55 | throw new IllegalArgumentException("Descriptor must be a ConditionDescriptor."); 56 | } 57 | 58 | ConditionDescriptor conditionDescriptor = (ConditionDescriptor) descriptor; 59 | 60 | String value = (String) conditionDescriptor.getArgs().get(NoOpenReviews.KEY_REVERSED); 61 | return Boolean.parseBoolean(value); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/workflow/condition/ApprovalScore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow.condition; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 17 | import com.meetme.plugins.jira.gerrit.data.dto.GerritApproval; 18 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 19 | 20 | import com.atlassian.jira.issue.Issue; 21 | import com.atlassian.jira.workflow.condition.AbstractJiraCondition; 22 | import com.opensymphony.module.propertyset.PropertySet; 23 | import com.opensymphony.workflow.WorkflowException; 24 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 25 | 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | /** 33 | * A workflow condition that requires (or rejects) a certain Gerrit approval score. 34 | *

35 | * An example use case might be to require, for example, "{@literal MUST have a Code-Review score >= 2}", or 36 | * "{@literal Must NOT have a Code-Review score < 0}" (these could even be combined into a single transition to 37 | * require both conditions be met). 38 | * 39 | * @author Joe Hansche 40 | */ 41 | public class ApprovalScore extends AbstractJiraCondition { 42 | private static final Logger log = LoggerFactory.getLogger(ApprovalScore.class); 43 | 44 | // Must [or not] have [ operator ] N score for [type] 45 | public static final String KEY_NEGATIVE = "negative"; 46 | public static final String KEY_COMPARISON = "comparison"; 47 | public static final String KEY_TARGET = "target"; 48 | public static final String KEY_LABEL = "label"; 49 | 50 | private IssueReviewsManager reviewsManager; 51 | 52 | public ApprovalScore(final IssueReviewsManager reviewsManager) { 53 | this.reviewsManager = reviewsManager; 54 | } 55 | 56 | @Override 57 | public boolean passesCondition(@SuppressWarnings("rawtypes") Map transientVars, @SuppressWarnings("rawtypes") Map args, PropertySet ps) 58 | throws WorkflowException { 59 | Issue issue = getIssue(transientVars); 60 | List reviews; 61 | 62 | try { 63 | reviews = reviewsManager.getReviewsForIssue(issue); 64 | } catch (GerritQueryException e) { 65 | // If there's an error, best not to block the workflow, and just act like it passes?? 66 | throw new WorkflowException(e); 67 | } 68 | 69 | boolean isReverse = Boolean.parseBoolean((String) args.get(KEY_NEGATIVE)); 70 | ComparisonOperator op = ComparisonOperator.valueOf((String) args.get(KEY_COMPARISON)); 71 | String label = (String) args.get(KEY_LABEL); 72 | int targetScore = Integer.parseInt((String) args.get(KEY_TARGET)); 73 | 74 | String description = describe(isReverse, label, op, targetScore); 75 | log.debug("Condition description: " + description); 76 | 77 | boolean matches = false; 78 | int matchingChanges = 0; 79 | int blockingChanges = 0; 80 | 81 | for (GerritChange ch : reviews) { 82 | int matchingApprovals = 0; 83 | 84 | for (GerritApproval approval : ch.getPatchSet().getApprovals()) { 85 | if (approval.getType().equals(label)) { 86 | if (compareScore(op, approval.getValueAsInt(), targetScore)) { 87 | log.debug("Found a match on review " + ch + " for condition: " + description + "; Approver=" + approval); 88 | 89 | matchingApprovals++; 90 | } 91 | } 92 | } 93 | 94 | if (matchingApprovals > 0) { 95 | matchingChanges++; 96 | } else { 97 | blockingChanges++; 98 | } 99 | } 100 | 101 | // To be considered a match, every change must have at least one matching approval, and no 102 | // change can be missing a matching approval 103 | matches = matchingChanges > 0 && blockingChanges == 0; 104 | 105 | if (isReverse) { 106 | matches = !matches; 107 | log.debug("Negating logic, due to 'MUST NOT' condition. NEW matches=" + matches); 108 | } 109 | 110 | log.trace("Evaluating conditions: " + matches); 111 | 112 | return matches; 113 | } 114 | 115 | private String describe(boolean isReverse, String label, ComparisonOperator op, int targetScore) { 116 | return "isReverse=" + isReverse + ", label=" + label + ", op=" + op.name() + ", targetScore=" + targetScore; 117 | } 118 | 119 | /** 120 | * Compare two scores using the provided {@link ComparisonOperator} 121 | * 122 | * @param oper the comparison operator 123 | * @param score the score that is being compared 124 | * @param target the target score against which {@code score} is being compared 125 | * @return the result of the comparison 126 | */ 127 | private boolean compareScore(ComparisonOperator oper, int score, int target) { 128 | log.debug("Comparing score: " + score + oper + target); 129 | 130 | switch (oper) { 131 | case EQUAL_TO: 132 | return score == target; 133 | case LESS_THAN: 134 | return score < target; 135 | case LESS_OR_EQUAL: 136 | return score <= target; 137 | case GREATER_OR_EQUAL: 138 | return score >= target; 139 | case GREATER_THAN: 140 | return score > target; 141 | } 142 | 143 | throw new IllegalArgumentException("Unknown operator: " + oper); 144 | } 145 | 146 | /** 147 | * Text-based selection of comparison operators. 148 | * 149 | * @author Joe Hansche 150 | */ 151 | public static enum ComparisonOperator { 152 | LESS_THAN("<"), LESS_OR_EQUAL("<="), EQUAL_TO("=="), GREATER_OR_EQUAL(">="), GREATER_THAN(">"); 153 | 154 | private final String display; 155 | 156 | private ComparisonOperator(final String display) { 157 | this.display = display; 158 | } 159 | 160 | @Override 161 | public String toString() { 162 | return display; 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/workflow/condition/NoOpenReviews.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow.condition; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 17 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 18 | 19 | import com.atlassian.jira.issue.Issue; 20 | import com.atlassian.jira.workflow.condition.AbstractJiraCondition; 21 | import com.opensymphony.module.propertyset.PropertySet; 22 | import com.opensymphony.workflow.WorkflowException; 23 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 24 | 25 | import java.util.List; 26 | import java.util.Map; 27 | 28 | /** 29 | * Workflow condition that can be used to enforce that an issue "MUST", or "MUST NOT" have any open 30 | * Gerrit reviews. 31 | * 32 | * @author Joe Hansche 33 | */ 34 | public class NoOpenReviews extends AbstractJiraCondition { 35 | public static final String KEY_REVERSED = "reversed"; 36 | 37 | private IssueReviewsManager reviewsManager; 38 | 39 | public NoOpenReviews(IssueReviewsManager reviewsManager) { 40 | this.reviewsManager = reviewsManager; 41 | } 42 | 43 | @Override 44 | public boolean passesCondition(@SuppressWarnings("rawtypes") Map transientVars, @SuppressWarnings("rawtypes") Map args, PropertySet ps) 45 | throws WorkflowException { 46 | Issue issue = getIssue(transientVars); 47 | List reviews; 48 | 49 | try { 50 | reviews = reviewsManager.getReviewsForIssue(issue); 51 | } catch (GerritQueryException e) { 52 | // If there's an error, best not to block the workflow, and just act like it passes?? 53 | throw new WorkflowException(e); 54 | } 55 | 56 | String value = (String) args.get(KEY_REVERSED); 57 | boolean isReversed = Boolean.parseBoolean(value); 58 | 59 | // The ReviewsManager will only return issues that are "status:open" by default. 60 | int numOpenReviews = countReviewStatus(reviews, true); 61 | 62 | return isReversed ? numOpenReviews > 0 : numOpenReviews == 0; 63 | } 64 | 65 | /** 66 | * Counts the number of reviews that are open or closed. 67 | * 68 | * @param reviews a set of Gerrit changes 69 | * @param isOpen {@code true} to count all open reviews, {@code false} to 70 | * count all non-open reviews. 71 | * @return the number of changes within {@code reviews} that match the 72 | * {@code isOpen} flag. 73 | */ 74 | public static int countReviewStatus(List reviews, boolean isOpen) { 75 | int count = 0; 76 | 77 | for (GerritChange change : reviews) { 78 | if (change.isOpen() == isOpen) { 79 | count += 1; 80 | } 81 | } 82 | 83 | return count; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/meetme/plugins/jira/gerrit/workflow/function/ApprovalFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow.function; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 17 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 18 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 19 | import com.meetme.plugins.jira.gerrit.workflow.condition.ApprovalScore; 20 | 21 | import com.atlassian.core.user.preferences.Preferences; 22 | import com.atlassian.jira.issue.Issue; 23 | import com.atlassian.jira.user.ApplicationUser; 24 | import com.atlassian.jira.user.preferences.UserPreferencesManager; 25 | import com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider; 26 | import com.opensymphony.module.propertyset.PropertySet; 27 | import com.opensymphony.workflow.WorkflowException; 28 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 29 | 30 | import org.slf4j.Logger; 31 | import org.slf4j.LoggerFactory; 32 | 33 | import java.io.IOException; 34 | import java.util.List; 35 | import java.util.Map; 36 | 37 | /** 38 | * A Workflow Function that can be used to perform Gerrit approvals as the result of a workflow 39 | * transition. The input argument is simply a command line argument string (such as "--verified +1", 40 | * or "--submit", etc). The argument will be appended to the gerrit review [ChangeId] ... 41 | * command line. 42 | *

43 | * This function can be used in combination with {@link ApprovalScore} workflow conditions, such 44 | * that, e.g., a "Merge Change" workflow transition can be used to automatically "submit" a Gerrit 45 | * review, iff all of the following conditions are met: 46 | *

    47 | *
  • MUST have a Code-Review score >= 2
  • 48 | *
  • MUST have a Verified score >= 1
  • 49 | *
  • Must NOT have a Code-Review score < 0
  • 50 | *
51 | *

52 | * This ensures that the workflow transition is only available if the "submit" step will be 53 | * successful. 54 | *

55 | * Another common use for this function would be to automatically provide a "Verified +1" score, via 56 | * another workflow step, e.g., "Ready for Merge". In that way, a "Ready for Merge" transition may 57 | * then automatically enable the "Merge Change" transition, as a result of giving the Verified +1 58 | * score. 59 | * 60 | * @author Joe Hansche 61 | */ 62 | public class ApprovalFunction extends AbstractJiraFunctionProvider { 63 | private static final Logger log = LoggerFactory.getLogger(ApprovalFunction.class); 64 | 65 | public static final String KEY_CMD_ARGS = "cmdArgs"; 66 | public static final String DEFAULT_CMD_ARGS = "--verified 1 --submit"; 67 | 68 | private final IssueReviewsManager reviewsManager; 69 | private final GerritConfiguration configuration; 70 | private final UserPreferencesManager prefsManager; 71 | 72 | public ApprovalFunction(GerritConfiguration configuration, IssueReviewsManager reviewsManager, UserPreferencesManager prefsManager) { 73 | super(); 74 | 75 | this.configuration = configuration; 76 | this.reviewsManager = reviewsManager; 77 | this.prefsManager = prefsManager; 78 | } 79 | 80 | @Override 81 | public void execute(@SuppressWarnings("rawtypes") Map transientVars, @SuppressWarnings("rawtypes") Map args, PropertySet ps) 82 | throws WorkflowException { 83 | if (!isConfigurationReady()) { 84 | throw new IllegalStateException("Configure the Gerrit integration from the Administration panel first."); 85 | } 86 | 87 | final Issue issue = getIssue(transientVars); 88 | final List issueReviews = getReviews(issue); 89 | final Preferences prefs = getUserPrefs(transientVars, args); 90 | final String cmdArgs = (String) args.get(KEY_CMD_ARGS); 91 | 92 | boolean success = false; 93 | 94 | try { 95 | success = reviewsManager.doApprovals(issue, issueReviews, cmdArgs, prefs); 96 | } catch (IOException e) { 97 | throw new WorkflowException("An error occurred while approving the changes", e); 98 | } 99 | 100 | if (!success) { 101 | log.warn("doApprovals() returned false!"); 102 | // throw new WorkflowException("Gerrit failed to perform the approvals!"); 103 | } 104 | } 105 | 106 | protected Preferences getUserPrefs(@SuppressWarnings("rawtypes") Map transientVars, @SuppressWarnings("rawtypes") Map args) { 107 | final ApplicationUser user = getCaller(transientVars, args); 108 | return prefsManager.getPreferences(user); 109 | } 110 | 111 | protected String getIssueKey(@SuppressWarnings("rawtypes") Map transientVars) { 112 | return getIssue(transientVars).getKey(); 113 | } 114 | 115 | protected List getReviews(Issue issue) throws WorkflowException { 116 | try { 117 | return reviewsManager.getReviewsForIssue(issue); 118 | } catch (GerritQueryException e) { 119 | throw new WorkflowException("Unable to retrieve associated reviews", e); 120 | } 121 | } 122 | 123 | protected boolean isConfigurationReady() { 124 | return configuration != null && configuration.getSshHostname() != null && configuration.getSshUsername() != null 125 | && configuration.getSshPrivateKey() != null && configuration.getSshPrivateKey().exists(); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/main/resources/i18n/admin.properties: -------------------------------------------------------------------------------- 1 | # Copyright 2012 MeetMe, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | gerrit.admin.label=Gerrit Settings 16 | 17 | gerrit.admin.ssh.label=SSH Connection 18 | gerrit.admin.host.label=SSH Host 19 | gerrit.admin.host.description=Example: gerrit.company.com 20 | gerrit.admin.port.label=SSH Port 21 | gerrit.admin.port.description=Example: 29418 22 | gerrit.admin.username.label=SSH Username 23 | gerrit.admin.username.description=Example: jira 24 | gerrit.admin.sshKey.label=SSH Private Key 25 | gerrit.admin.sshKey.description=Example: id_rsa file 26 | gerrit.admin.sshKey.isOnFile=Private Key is already on file. Upload a new one to replace it. 27 | gerrit.admin.sshKey.missing=A private key is required! 28 | 29 | gerrit.admin.search.label=Search Queries 30 | gerrit.admin.issueSearchQuery.label=Issue Search 31 | gerrit.admin.issueSearchQuery.description=Enter a search query used to locate reviews for a given issue (via gerrit query [...]). Use "%s" as a placeholder for the issue key. To reference the issue key multiple times in the query, use "%1$s" instead. \ 32 | Examples: "tr:%s"; "topic:%s"; "message:%s"; "tr:%s OR topic:%1$s"; etc. 33 | gerrit.admin.projectSearchQuery.label=Project Search 34 | gerrit.admin.projectSearchQuery.description=Enter a search query used to locate reviews for a given project (via gerrit query [...]). Use "%s" or "%1$s" as a placeholder for the project key. \ 35 | Examples: project:%s, topic:%s, or message:%s-*. 36 | 37 | ## Not yet implemented (JSON-RPC): 38 | gerrit.admin.http.label=HTTP Settings (optional) 39 | gerrit.admin.httpBaseUrl.label=HTTP Base URL 40 | gerrit.admin.httpBaseUrl.description=Example: http://gerrit.company.com/ 41 | gerrit.admin.httpUsername.label=HTTP Username 42 | gerrit.admin.httpUsername.description=Example: jira 43 | gerrit.admin.httpPassword.label=HTTP Password 44 | 45 | gerrit.admin.project.settings=Project Settings 46 | gerrit.admin.showEmptyPanel.label=Show Gerrit Reviews panel even if there are no reviews 47 | gerrit.admin.showEmptyPanel.description=If there are no matching Gerrit reviews for the issue, the panel will still display with a note that nothing matches. \ 48 | Uncheck this box to remove the panel instead. 49 | gerrit.admin.project.whitelist=Gerrit Projects Whitelist 50 | gerrit.admin.project.whitelist.description=List of projects, that use gerrit. 51 | gerrit.admin.project.useWhiteList.label=Use Gerrit Project Whitelist 52 | gerrit.admin.project.useWhiteList.description=If a list of projects, that use Gerrit, shall be maintained. -------------------------------------------------------------------------------- /src/main/resources/i18n/tabpanel.properties: -------------------------------------------------------------------------------- 1 | # Copyright 2012 MeetMe, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | gerrit.tabpanel.label=Gerrit Reviews 16 | gerrit.tabpanel.Review=Gerrit Review 17 | gerrit.tabpanel.Project=Project 18 | gerrit.tabpanel.Branch=Branch 19 | gerrit.tabpanel.Approver=Approver 20 | gerrit.tabpanel.Type=Type 21 | gerrit.tabpanel.Score=Score 22 | gerrit.tabpanel.Status=Status 23 | gerrit.tabpanel.status.open=Open 24 | gerrit.tabpanel.status.closed=Closed 25 | gerrit.tabpanel.permalink=A permanent link to this Gerrit change 26 | gerrit.tabpanel.no_approvals=There are no approvals yet for this Gerrit change. 27 | gerrit.tabpanel.no_changes=There are no open Gerrit changes for this issue. 28 | 29 | gerrit.tabpanel.most_significant_score=This is the most significant approval score for the Gerrit change. 30 | 31 | gerrit.tabpanel.subtasks.label=Subtask Gerrit Reviews 32 | gerrit.tabpanel.subtasks.permalink=A permanent link to this Sub-Task 33 | gerrit.tabpanel.subtasks.has_open_reviews=There {0,choice, 0#are no| 1#is 1| 1zero open Gerrit review. 25 | gerrit.workflow.no-open-reviews.view.reversed-true=The issue must have at least one open Gerrit reviews. 26 | 27 | 28 | ## Approval Score condition 29 | gerrit.workflow.score-condition.label=Gerrit Approval Score Condition 30 | 31 | gerrit.workflow.score-condition.edit.negative.label=Logic 32 | gerrit.workflow.score-condition.edit.negative.description=Whether the condition MUST or MUST NOT be met. 33 | gerrit.workflow.score-condition.edit.comparison.label=Comparison Operator 34 | gerrit.workflow.score-condition.edit.comparison.description=Choose an operator to compare the actual score to the target score. E.g., ACTUAL <operator> TARGET 35 | gerrit.workflow.score-condition.edit.target-score.label=Target Approval Score 36 | gerrit.workflow.score-condition.edit.target-score.description=The target approval score to compare actual approvals against. 37 | gerrit.workflow.score-condition.edit.approval-category.label=Approval Type 38 | gerrit.workflow.score-condition.edit.approval-category.description=The internal approval category label. E.g., Code-Review, Verified, etc. 39 | # Select drop-down options for $negative 40 | gerrit.workflow.score-condition.edit.negative-false.label=MUST 41 | gerrit.workflow.score-condition.edit.negative-true.label=Must NOT 42 | 43 | #args: [$comparison, $target, $label] 44 | gerrit.workflow.score-condition.view.positive=MUST have approval score {0} {1} for category {2} 45 | gerrit.workflow.score-condition.view.negative=Must NOT have approval score {0} {1} for category {2} 46 | 47 | 48 | ## Modify Gerrit review, function 49 | gerrit.workflow.approve.label=Approve Gerrit Review 50 | 51 | gerrit.workflow.approve.edit.cmdArgs.label=Command Arguments 52 | gerrit.workflow.approve.edit.cmdArgs.description=Enter the command arguments to pass to the gerrit review ... command. For example: --verified 1; or --submit 53 | 54 | gerrit.workflow.approve.view=Approve all Gerrit reviews with: gerrit review [ChangeId] {0} 55 | -------------------------------------------------------------------------------- /src/main/resources/images/gerrit-check.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MeetMe/jira-gerrit-plugin/a0be628cc1ad676235cef1ab174fbeb12ddb45ed/src/main/resources/images/gerrit-check.png -------------------------------------------------------------------------------- /src/main/resources/images/gerrit-icon16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MeetMe/jira-gerrit-plugin/a0be628cc1ad676235cef1ab174fbeb12ddb45ed/src/main/resources/images/gerrit-icon16.png -------------------------------------------------------------------------------- /src/main/resources/images/gerrit-x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MeetMe/jira-gerrit-plugin/a0be628cc1ad676235cef1ab174fbeb12ddb45ed/src/main/resources/images/gerrit-x.png -------------------------------------------------------------------------------- /src/main/resources/images/meetme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MeetMe/jira-gerrit-plugin/a0be628cc1ad676235cef1ab174fbeb12ddb45ed/src/main/resources/images/meetme.png -------------------------------------------------------------------------------- /src/main/resources/images/meetme_75.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MeetMe/jira-gerrit-plugin/a0be628cc1ad676235cef1ab174fbeb12ddb45ed/src/main/resources/images/meetme_75.png -------------------------------------------------------------------------------- /src/main/resources/styles/gerrit-reviews-tabpanel.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | .module table.gerrit-review-approvals 15 | { 16 | width: 400px; 17 | } 18 | 19 | table td.gerrit-review-score 20 | { 21 | text-align: right; 22 | } 23 | 24 | table.gerrit-review-approvals td.review-negative, 25 | div.flooded span.review-negative, 26 | .gerrit-review-score.review-negative 27 | { 28 | color: #f00; 29 | } 30 | 31 | table.gerrit-review-approvals td.review-positive, 32 | div.flooded span.review-positive, 33 | .gerrit-review-score.review-positive 34 | { 35 | color: #08A400; 36 | } 37 | 38 | .gerrit-status-ABANDONED span.gerrit-review 39 | { 40 | background-image: url(images/gerrit-x.png); 41 | } 42 | 43 | .gerrit-status-MERGED span.gerrit-review, 44 | .gerrit-status-SUBMITTED span.gerrit-review 45 | { 46 | background-image: url(images/gerrit-check.png); 47 | } 48 | 49 | span.gerrit-review 50 | { 51 | display: inline-block; 52 | text-indent: -9999px; 53 | width: 16px; 54 | height: 16px; 55 | background-color: transparent; 56 | background-image: url(images/gerrit-icon16.png); 57 | background-repeat: no-repeat; 58 | background-position: 50% 50%; 59 | } 60 | 61 | span.gerrit-open-reviews 62 | { 63 | color: #900; 64 | } 65 | 66 | span.gerrit-no-reviews 67 | { 68 | font-style: italic; 69 | } 70 | 71 | #gerrit-reviews-side-panel ul.item-details dl dt 72 | { 73 | white-space: nowrap; 74 | overflow: hidden; 75 | text-overflow: none; 76 | width: 81%; 77 | text-align: left; 78 | } 79 | 80 | #gerrit-reviews-side-panel ul.item-details dl dd 81 | { 82 | width: 18%; 83 | text-align: right; 84 | } 85 | 86 | #gerrit-reviews-side-panel ul.item-details dl dd span.gerrit-review 87 | { 88 | text-indent: 9999px; 89 | vertical-align: middle; 90 | overflow: hidden; 91 | } 92 | 93 | #gerrit-reviews-side-panel span.twixi 94 | { 95 | cursor: pointer 96 | } 97 | 98 | #gerrit-reviews-left-panel 99 | { 100 | width: 100%; 101 | margin: 0 0 8px 0; 102 | background-color: white; 103 | border-collapse: collapse; 104 | text-align: left; 105 | } 106 | 107 | #gerrit-reviews-left-panel tr.issuerow:hover 108 | { 109 | background-color: #f0f0f0; 110 | } 111 | 112 | #gerrit-reviews-left-panel tr td.gerrit-subject 113 | { 114 | min-width: 200px; 115 | margin: 0; 116 | max-width: 1400px; 117 | white-space: normal; 118 | } 119 | 120 | #gerrit-reviews-left-panel td 121 | { 122 | height: 25px; 123 | line-height: 1.286; 124 | padding: 5px 7px 0 0; 125 | overflow: hidden; 126 | } 127 | 128 | #gerrit-reviews-left-panel .nav 129 | { 130 | border-bottom: 1px solid #eee; 131 | vertical-align: middle; 132 | } 133 | 134 | #gerrit-reviews-left-panel img 135 | { 136 | vertical-align: middle; 137 | } 138 | 139 | #gerrit-reviews-left-panel .gerrit-changeid, 140 | #gerrit-reviews-left-panel .gerrit-patchset 141 | { 142 | white-space: nowrap; 143 | width: 16px; 144 | } 145 | 146 | #gerrit-reviews-left-panel .gerrit-status, 147 | #gerrit-reviews-left-panel .gerrit-review-score 148 | { 149 | white-space: nowrap; 150 | width: 16px; 151 | max-width: 150px; 152 | } 153 | 154 | #gerrit-reviews-left-panel th.dashboardHeader 155 | { 156 | font-weight: normal; 157 | text-align: left; 158 | } 159 | 160 | #gerrit-reviews-left-panel td.gerrit-review-score 161 | { 162 | text-align: left; 163 | } -------------------------------------------------------------------------------- /src/main/resources/templates/gerrit-reviews-agile-panel.vm: -------------------------------------------------------------------------------- 1 | 72 |

73 | 74 |
75 | $i18n.getText("gerrit-reviews-side-panel.open_reviews", $numOpen) 76 |
77 | 78 | #if ($numOpen > 0) 79 |
    80 | #foreach ($change in $changes) 81 | 82 | #if ($change.isOpen()) 83 | #set( $statusClass = "gerrit-status-$change.status" ) 84 |
  • #sideReviewDetail( $change )
  • 85 | #end 86 | 87 | #end 88 |
89 | #end 90 | 91 | #if ($numClosed > 0) 92 | 127 | #end 128 |
129 | -------------------------------------------------------------------------------- /src/main/resources/templates/gerrit-reviews-left-panel.vm: -------------------------------------------------------------------------------- 1 | #* 2 | Copyright 2012 MeetMe, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | *# 16 | 17 | ### See utility.vm 18 | 19 | 20 | #* Calculates and displays the most significant approval score *# 21 | #macro( mostSignificantScore $approvals ) 22 | #set( $significant = 0 ) 23 | #set( $by = "No votes" ) 24 | 25 | #foreach( $approval in $approvals ) 26 | #set( $value = $approval.valueAsInt ) 27 | 28 | #if( 0 > $value && $significant > $value ) 29 | #set( $significant = $value ) 30 | #set( $by = "By ${approval.by}" ) 31 | #elseif( $value > 0 && $value > $significant && $significant >= 0 ) 32 | #set( $significant = $value ) 33 | #set( $by = "By ${approval.by}" ) 34 | #end 35 | #end 36 | 37 | #if ($significant > 0) 38 | #set( $cssClass = "review-positive" ) 39 | #elseif( 0 > $significant ) 40 | #set( $cssClass = "review-negative" ) 41 | #else 42 | #set( $cssClass = "" ) 43 | #end 44 | 45 | 46 | #if ( $significant > 0 ) 47 | +$significant 48 | #else 49 | $significant 50 | #end 51 | 52 | #end 53 | 54 | 55 | 56 | #* Displays a single Review Detail record, in the expanded subtasks list *# 57 | #macro( leftReviewDetail $change ) 58 | 59 | 60 | 61 | $change.number,$change.patchSet.number 62 | 63 | 64 | 65 | $change.subject 66 | 67 | 68 | 69 | $change.branch 70 | 71 | 72 | 73 | $change.project 74 | 75 | 76 | 77 | $i18n.getText('gerrit.tabpanel.Status'): 78 | $change.status 79 | 80 | 81 | 82 | #mostSignificantScore(${change.patchSet.getApprovalsForLabel("Code-Review")}) 83 | 84 | 85 | 86 | #mostSignificantScore(${change.patchSet.getApprovalsForLabel("Verified")}) 87 | 88 | 89 | #end 90 | 91 | 92 | #set( $numClosed = 0 ) 93 | #set( $numOpen = 0 ) 94 | #foreach ($change in $changes) 95 | #if ($change.isOpen()) 96 | #set( $numOpen = $numOpen + 1 ) 97 | #else 98 | #set( $numClosed = $numClosed + 1 ) 99 | #end 100 | #end 101 | 102 | 103 | #if ($numOpen == 0 && $numClosed == 0) 104 | 105 |
106 | 107 | $i18n.getText("gerrit-reviews-left-panel.no_matching_reviews") 108 |
109 | 110 | #else 111 | 112 | 113 | 114 | #if ( $dashboardUrl && $dashboardKey) 115 | 116 | 119 | 120 | #end 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | #foreach ($change in $changes) 133 | #if ($change.isOpen()) 134 | #leftReviewDetail( $change ) 135 | #end 136 | #end 137 | 138 | 139 | 140 | #foreach ( $change in $changes) 141 | #if (!$change.isOpen()) 142 | #leftReviewDetail( $change ) 143 | #end 144 | #end 145 | 146 |
117 | For Gerrit Dashboard: $dashboardKey 118 |
#SubjectBranchProjectStatusCRV
147 | 148 | #end -------------------------------------------------------------------------------- /src/main/resources/templates/gerrit-reviews-side-panel.vm: -------------------------------------------------------------------------------- 1 | 72 |
73 | 74 |
75 | $i18n.getText("gerrit-reviews-side-panel.open_reviews", $numOpen) 76 |
77 | 78 | #if ($numOpen > 0) 79 |
    80 | #foreach ($change in $changes) 81 | 82 | #if ($change.isOpen()) 83 | #set( $statusClass = "gerrit-status-$change.status" ) 84 |
  • #sideReviewDetail( $change )
  • 85 | #end 86 | 87 | #end 88 |
89 | #end 90 | 91 | #if ($numClosed > 0) 92 | 127 | #end 128 |
129 | -------------------------------------------------------------------------------- /src/main/resources/templates/gerrit-reviews-tabpanel-item.vm: -------------------------------------------------------------------------------- 1 | 67 | 163 | -------------------------------------------------------------------------------- /src/main/resources/templates/subtask-reviews-tabpanel-item.vm: -------------------------------------------------------------------------------- 1 | 75 | 143 | -------------------------------------------------------------------------------- /src/main/resources/templates/utility.vm: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/templates/workflow/approve-function-edit.vm: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | $i18n.getText("gerrit.workflow.approve.edit.cmdArgs.label"): 19 | 20 | 21 | 22 |
23 | $i18n.getText("gerrit.workflow.approve.edit.cmdArgs.description") 24 | 25 | -------------------------------------------------------------------------------- /src/main/resources/templates/workflow/approve-function-view.vm: -------------------------------------------------------------------------------- 1 | 16 | $i18n.getText("gerrit.workflow.approve.view", [$cmdArgs]) -------------------------------------------------------------------------------- /src/main/resources/templates/workflow/no-open-reviews-condition-edit.vm: -------------------------------------------------------------------------------- 1 | 16 | 17 | #macro( option $value $isSelected $label ) 18 | #if ($isSelected) 19 | 20 | #else 21 | 22 | #end 23 | #end 24 | 25 | 26 | 27 | $i18n.getText("gerrit.workflow.no-open-reviews.edit.label"): 28 | 29 | 30 | 36 |
37 | $i18n.getText("gerrit.workflow.no-open-reviews.edit.description") 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/main/resources/templates/workflow/no-open-reviews-condition-view.vm: -------------------------------------------------------------------------------- 1 | 16 | 17 | #if ($reversed) 18 | $i18n.getText("gerrit.workflow.no-open-reviews.view.reversed-true") 19 | #else 20 | $i18n.getText("gerrit.workflow.no-open-reviews.view.reversed-false") 21 | #end 22 | -------------------------------------------------------------------------------- /src/main/resources/templates/workflow/score-condition-edit.vm: -------------------------------------------------------------------------------- 1 | 16 | 17 | #macro( option $value $isSelected $label ) 18 | #if ($isSelected) 19 | 20 | #else 21 | 22 | #end 23 | #end 24 | 25 | 26 | 27 | $i18n.getText("gerrit.workflow.score-condition.edit.negative.label"): 28 | 29 | 30 | 36 |
37 | $i18n.getText("gerrit.workflow.score-condition.edit.negative.description") 38 | 39 | 40 | 41 | 42 | 43 | $i18n.getText("gerrit.workflow.score-condition.edit.comparison.label"): 44 | 45 | 46 | #set( $comparisonName = $comparison.name() ) 47 | 63 |
64 | $i18n.getText("gerrit.workflow.score-condition.edit.comparison.description") 65 | 66 | 67 | 68 | 69 | 70 | $i18n.getText("gerrit.workflow.score-condition.edit.approval-category.label"): 71 | 72 | 73 | 74 |
75 | $i18n.getText("gerrit.workflow.score-condition.edit.approval-category.description") 76 | 77 | 78 | 79 | 80 | 81 | $i18n.getText("gerrit.workflow.score-condition.edit.target-score.label"): 82 | 83 | 84 | 85 |
86 | $i18n.getText("gerrit.workflow.score-condition.edit.target-score.description") 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/main/resources/templates/workflow/score-condition-view.vm: -------------------------------------------------------------------------------- 1 | 16 | 17 | #* Must [or not] have score [ operator ] [ target ] for [ label ] *# 18 | 19 | #if ($negative) 20 | $i18n.getText("gerrit.workflow.score-condition.view.negative", [$comparison, $target, $label]) 21 | #else 22 | $i18n.getText("gerrit.workflow.score-condition.view.positive", [$comparison, $target, $label]) 23 | #end 24 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/data/IssueReviewsManagerTest.java: -------------------------------------------------------------------------------- 1 | package com.meetme.plugins.jira.gerrit.data; 2 | 3 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 4 | 5 | import com.atlassian.cache.Cache; 6 | import com.atlassian.cache.CacheLoader; 7 | import com.atlassian.cache.CacheManager; 8 | import com.atlassian.jira.issue.IssueManager; 9 | import com.atlassian.jira.issue.MutableIssue; 10 | 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | import org.mockito.Mock; 14 | import org.mockito.Mockito; 15 | 16 | import java.util.Collections; 17 | import java.util.HashSet; 18 | import java.util.List; 19 | import java.util.Set; 20 | 21 | import static org.hamcrest.Matchers.containsInAnyOrder; 22 | import static org.junit.Assert.assertEquals; 23 | import static org.junit.Assert.assertThat; 24 | import static org.mockito.Matchers.any; 25 | import static org.mockito.Matchers.eq; 26 | import static org.mockito.Mockito.mock; 27 | import static org.mockito.Mockito.when; 28 | import static org.mockito.MockitoAnnotations.initMocks; 29 | 30 | /* 31 | * Copyright 2016 Pavel Tarasenko 32 | * 33 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 34 | * in compliance with the License. You may obtain a copy of the License at 35 | * 36 | * http://www.apache.org/licenses/LICENSE-2.0 37 | * 38 | * Unless required by applicable law or agreed to in writing, software distributed under the License 39 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 40 | * or implied. See the License for the specific language governing permissions and limitations under 41 | * the License. 42 | */ 43 | 44 | public class IssueReviewsManagerTest { 45 | public static final String ISSUE_KEY_OLD = "OLD-123"; 46 | private static final String ISSUE_KEY_NEW = "NEW-123"; 47 | 48 | @Mock 49 | private MutableIssue mockIssue; 50 | 51 | @Mock 52 | private GerritConfiguration configuration; 53 | 54 | @Mock 55 | private IssueManager mockJiraIssueManager; 56 | 57 | @Mock 58 | private CacheManager mockCacheManager; 59 | 60 | @Mock 61 | private Cache> mockCache; 62 | 63 | private IssueReviewsManager issueReviewsManager; 64 | 65 | @Before 66 | public void setUp() { 67 | initMocks(this); 68 | 69 | // gerrit configuration 70 | when(configuration.getIssueSearchQuery()).thenReturn(GerritConfiguration.DEFAULT_QUERY_ISSUE); 71 | when(configuration.getProjectSearchQuery()).thenReturn(GerritConfiguration.DEFAULT_QUERY_PROJECT); 72 | 73 | // issue 74 | when(mockIssue.getKey()).thenReturn(ISSUE_KEY_NEW); 75 | 76 | // issue key history 77 | when(mockJiraIssueManager.getIssueByKeyIgnoreCase(Mockito.anyString())).thenReturn(mockIssue); 78 | Set allIssueKeys = new HashSet<>(); 79 | allIssueKeys.add(ISSUE_KEY_OLD); 80 | allIssueKeys.add(ISSUE_KEY_NEW); 81 | when(mockJiraIssueManager.getAllIssueKeys(mockIssue.getId())).thenReturn(allIssueKeys); 82 | 83 | // mock gerrit review retrieval 84 | when(mockCacheManager.getCache( 85 | eq("com.meetme.plugins.jira.gerrit.data.IssueReviewsManager.issueChanges.cache"), 86 | Mockito.>>any(), 87 | any() 88 | )).thenReturn(mockCache); 89 | issueReviewsManager = new IssueReviewsImpl(configuration, mockJiraIssueManager, mockCacheManager, null); 90 | 91 | GerritChange oldChange = createMockChange(ISSUE_KEY_OLD); 92 | GerritChange newChange = createMockChange(ISSUE_KEY_NEW); 93 | when(mockCache.get(eq(ISSUE_KEY_OLD))).thenReturn(Collections.singletonList(oldChange)); 94 | when(mockCache.get(eq(ISSUE_KEY_NEW))).thenReturn(Collections.singletonList(newChange)); 95 | } 96 | 97 | private GerritChange createMockChange(String key) { 98 | GerritChange change = mock(GerritChange.class); 99 | when(change.getSubject()).thenReturn(key); 100 | return change; 101 | } 102 | 103 | @Test 104 | public void testGetReviewsForIssue() throws Exception { 105 | List reviewsForIssue = issueReviewsManager.getReviewsForIssue(mockIssue); 106 | assertEquals(2, reviewsForIssue.size()); 107 | 108 | Set reviewSubjects = new HashSet<>(); 109 | for (GerritChange review : reviewsForIssue) { 110 | reviewSubjects.add(review.getSubject()); 111 | } 112 | 113 | assertThat(reviewSubjects, containsInAnyOrder(ISSUE_KEY_OLD, ISSUE_KEY_NEW)); 114 | } 115 | 116 | @Test 117 | public void testDoApprovals() throws Exception { 118 | 119 | } 120 | 121 | @Test 122 | public void testGetIssueKeys() throws Exception { 123 | Set issueKeys = issueReviewsManager.getIssueKeys(mockIssue); 124 | assertEquals(2, issueKeys.size()); 125 | assertThat(issueKeys, containsInAnyOrder(mockIssue.getKey(), ISSUE_KEY_OLD)); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/data/dto/GerritApprovalTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.data.dto; 15 | 16 | import com.atlassian.jira.user.ApplicationUser; 17 | 18 | import net.sf.json.JSONObject; 19 | 20 | import org.junit.After; 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | import org.mockito.Mock; 24 | 25 | import static org.junit.Assert.*; 26 | import static org.mockito.MockitoAnnotations.initMocks; 27 | 28 | public class GerritApprovalTest { 29 | 30 | private final JSONObject BASE_TEST = new JSONObject(); 31 | 32 | private static final String EXPECTED_NAME = "Name"; 33 | private static final String EXPECTED_EMAIL = "user@email.local"; 34 | private static final String EXPECTED_TYPE = "Code-Review"; 35 | private static final String EXPECTED_VALUE = "1"; 36 | 37 | private static final String GREATER_VALUE = "2"; 38 | 39 | @Mock 40 | private ApplicationUser EXPECTED_USER; 41 | 42 | @Before 43 | public void setUp() throws Exception { 44 | initMocks(this); 45 | 46 | BASE_TEST.element("type", EXPECTED_TYPE).element("value", EXPECTED_VALUE); 47 | } 48 | 49 | @After 50 | public void tearDown() throws Exception { 51 | BASE_TEST.clear(); 52 | } 53 | 54 | private static void setUpJson(JSONObject obj) { 55 | JSONObject by = new JSONObject(); 56 | by.element("name", EXPECTED_NAME).element("email", EXPECTED_EMAIL); 57 | obj.element("by", by); 58 | } 59 | 60 | private static void assertFull(GerritApproval obj) { 61 | assertEquals(EXPECTED_NAME, obj.getBy()); 62 | assertEquals(EXPECTED_EMAIL, obj.getByEmail()); 63 | assertEquals(EXPECTED_TYPE, obj.getType()); 64 | assertEquals(EXPECTED_VALUE, obj.getValue()); 65 | assertEquals(1, obj.getValueAsInt()); 66 | } 67 | 68 | @Test 69 | public void testEmpty() { 70 | GerritApproval obj = new GerritApproval(new JSONObject()); 71 | 72 | assertNull(obj.getType()); 73 | assertNull(obj.getValue()); 74 | 75 | assertNull(obj.getBy()); 76 | assertNull(obj.getByEmail()); 77 | assertEquals(0, obj.getValueAsInt()); 78 | } 79 | 80 | @Test 81 | public void testBaseOnly() { 82 | GerritApproval obj = new GerritApproval(BASE_TEST); 83 | 84 | assertNull(obj.getBy()); 85 | assertNull(obj.getByEmail()); 86 | 87 | assertEquals(EXPECTED_TYPE, obj.getType()); 88 | assertEquals(EXPECTED_VALUE, obj.getValue()); 89 | assertEquals(1, obj.getValueAsInt()); 90 | } 91 | 92 | @Test 93 | public void testParseByFromJson() { 94 | setUpJson(BASE_TEST); 95 | 96 | GerritApproval obj = new GerritApproval(BASE_TEST); 97 | assertFull(obj); 98 | } 99 | 100 | @Test 101 | public void testParseFromJson_NoEmail() { 102 | JSONObject by = new JSONObject(); 103 | by.element("name", EXPECTED_NAME); 104 | BASE_TEST.element("by", by); 105 | 106 | GerritApproval obj = new GerritApproval(BASE_TEST); 107 | assertNull(obj.getByEmail()); 108 | assertEquals(EXPECTED_NAME, obj.getBy()); 109 | } 110 | 111 | @Test 112 | public void testParseFromJson_NoName() { 113 | JSONObject by = new JSONObject(); 114 | by.element("email", EXPECTED_EMAIL); 115 | BASE_TEST.element("by", by); 116 | 117 | GerritApproval obj = new GerritApproval(BASE_TEST); 118 | assertNull(obj.getBy()); 119 | assertEquals(EXPECTED_EMAIL, obj.getByEmail()); 120 | } 121 | 122 | @Test 123 | public void testSetters() { 124 | GerritApproval obj = new GerritApproval(BASE_TEST); 125 | 126 | obj.setType(EXPECTED_TYPE); 127 | obj.setValue(EXPECTED_VALUE); 128 | obj.setBy(EXPECTED_NAME); 129 | obj.setByEmail(EXPECTED_EMAIL); 130 | obj.setUser(EXPECTED_USER); 131 | 132 | assertFull(obj); 133 | assertNotNull(obj.getUser()); 134 | assertEquals(EXPECTED_USER, obj.getUser()); 135 | } 136 | 137 | @Test 138 | public void testToString() { 139 | setUpJson(BASE_TEST); 140 | GerritApproval obj = new GerritApproval(BASE_TEST); 141 | 142 | assertEquals("+1 by Name", obj.toString()); 143 | } 144 | 145 | @Test 146 | public void testCompareEquals() { 147 | GerritApproval obj = new GerritApproval(BASE_TEST); 148 | GerritApproval obj2 = new GerritApproval(BASE_TEST); 149 | 150 | assertEquals(0, obj.compareTo(obj)); 151 | assertTrue(obj.equals(obj)); 152 | 153 | assertEquals(0, obj.compareTo(obj2)); 154 | assertTrue(obj.equals(obj2)); 155 | } 156 | 157 | @Test 158 | public void testCompareNotEquals() { 159 | GerritApproval obj = new GerritApproval(BASE_TEST); 160 | GerritApproval obj2 = new GerritApproval(BASE_TEST); 161 | obj2.setValue(GREATER_VALUE); 162 | 163 | // obj1 < obj2 164 | assertEquals(-1, obj.compareTo(obj2)); 165 | assertFalse(obj.equals(obj2)); 166 | 167 | // obj1 > obj2 168 | assertEquals(1, obj2.compareTo(obj)); 169 | assertFalse(obj2.equals(obj)); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/tabpanel/GerritReviewIssueActionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritApproval; 17 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 18 | import com.meetme.plugins.jira.gerrit.data.dto.GerritPatchSet; 19 | 20 | import com.atlassian.core.util.map.EasyMap; 21 | import com.atlassian.jira.datetime.DateTimeFormatter; 22 | import com.atlassian.jira.datetime.DateTimeStyle; 23 | import com.atlassian.jira.plugin.issuetabpanel.IssueTabPanelModuleDescriptor; 24 | 25 | import org.junit.After; 26 | import org.junit.Before; 27 | import org.junit.Test; 28 | import org.mockito.Mock; 29 | 30 | import java.util.*; 31 | 32 | import static org.junit.Assert.*; 33 | import static org.mockito.Matchers.eq; 34 | import static org.mockito.Mockito.mock; 35 | import static org.mockito.Mockito.when; 36 | import static org.mockito.MockitoAnnotations.initMocks; 37 | 38 | public class GerritReviewIssueActionTest { 39 | private static final String BASE_URL = "http://localhost:2990/jira"; 40 | 41 | private static final long TEST_LAST_UPDATED_TIMESTAMP = 1339987664000L; 42 | private static final String TEST_PROJECT = "Development/project"; 43 | private static final String TEST_BRANCH = "master"; 44 | private static final String TEST_NUMBER = "1234"; 45 | private static final String TEST_PATCHSET_NUMBER = "2"; 46 | private static final String TEST_SUBJECT = "FOO-1: Hello world"; 47 | private static final String TEST_URL = "http://gerrit.local/1234"; 48 | private static final String TEST_REF = "refs/changes/34/1234/1"; 49 | private static final Date TEST_LAST_UPDATED = new Date(TEST_LAST_UPDATED_TIMESTAMP); 50 | 51 | private static final String TEST_FORMATTED_LAST_UPDATED = "Today 11:16 PM"; 52 | private static final String TEST_ISO_LAST_UPDATED = "2012-06-17T23:16:00-0400"; 53 | 54 | private static final ArrayList TEST_APPROVALS = new ArrayList<>(); 55 | private static final GerritApproval APPROVAL_NEGATIVE = new GerritApproval(); 56 | private static final GerritApproval APPROVAL_POSITIVE = new GerritApproval(); 57 | private static final GerritApproval APPROVAL_POSITIVE_2 = new GerritApproval(); 58 | 59 | @Mock 60 | private IssueTabPanelModuleDescriptor descriptor; 61 | 62 | private DateTimeFormatter dateTimeFormatter; 63 | 64 | private GerritChange change; 65 | 66 | private GerritReviewIssueAction action; 67 | 68 | @Before 69 | public void setUp() throws Exception { 70 | initMocks(this); 71 | 72 | setUpDateTimeFormatter(); 73 | setUpApprovals(); 74 | setUpGerritChange(); 75 | action = new GerritReviewIssueAction(descriptor, change, dateTimeFormatter, BASE_URL); 76 | } 77 | 78 | @After 79 | public void tearDown() throws Exception { 80 | change = null; 81 | action = null; 82 | } 83 | 84 | private void setUpDateTimeFormatter() { 85 | dateTimeFormatter = mock(DateTimeFormatter.class); 86 | when(dateTimeFormatter.forLoggedInUser()).thenReturn(dateTimeFormatter); 87 | when(dateTimeFormatter.format(eq(TEST_LAST_UPDATED))).thenReturn(TEST_FORMATTED_LAST_UPDATED); 88 | 89 | DateTimeFormatter isoFormatter = mock(DateTimeFormatter.class); 90 | when(isoFormatter.format(eq(TEST_LAST_UPDATED))).thenReturn(TEST_ISO_LAST_UPDATED); 91 | when(dateTimeFormatter.withStyle(eq(DateTimeStyle.ISO_8601_DATE_TIME))).thenReturn(isoFormatter); 92 | } 93 | 94 | private void setUpApprovals() { 95 | // setup negative approval 96 | APPROVAL_NEGATIVE.setValue("-1"); 97 | APPROVAL_NEGATIVE.setType("NEG"); 98 | 99 | // setup positive approval 100 | APPROVAL_POSITIVE.setValue("1"); 101 | APPROVAL_POSITIVE.setType("POS"); 102 | 103 | // setup more-positive approval 104 | APPROVAL_POSITIVE_2.setValue("2"); 105 | APPROVAL_POSITIVE_2.setType("POS"); 106 | 107 | TEST_APPROVALS.clear(); 108 | TEST_APPROVALS.add(APPROVAL_NEGATIVE); 109 | TEST_APPROVALS.add(APPROVAL_POSITIVE); 110 | TEST_APPROVALS.add(APPROVAL_POSITIVE_2); 111 | } 112 | 113 | @SuppressWarnings("deprecation") 114 | private void setUpGerritChange() { 115 | change = new GerritChange(); 116 | change.setBranch(TEST_BRANCH); 117 | change.setProject(TEST_PROJECT); 118 | change.setSubject(TEST_SUBJECT); 119 | change.setLastUpdated(TEST_LAST_UPDATED); 120 | change.setNumber(TEST_NUMBER); 121 | change.setUrl(TEST_URL); 122 | 123 | GerritPatchSet patchSet = new GerritPatchSet(); 124 | patchSet.setNumber(TEST_PATCHSET_NUMBER); 125 | patchSet.setRef(TEST_REF); 126 | patchSet.setApprovals(TEST_APPROVALS); 127 | change.setPatchSet(patchSet); 128 | } 129 | 130 | @Test 131 | public void testAllTab() { 132 | assertTrue(action.isDisplayActionAllTab()); 133 | } 134 | 135 | @Test 136 | public void testLastUpdated() { 137 | assertEquals(TEST_LAST_UPDATED, action.getTimePerformed()); 138 | } 139 | 140 | @SuppressWarnings("deprecation") 141 | @Test 142 | public void testMostSignificantScore() { 143 | // null input = null output 144 | assertNull(action.getMostSignificantScore(null)); 145 | 146 | List approvals = new ArrayList<>(); 147 | // empty input = null output 148 | assertNull(action.getMostSignificantScore(approvals)); 149 | 150 | // Zero-score is not possible, but if it were = null output 151 | GerritApproval nulApproval = new GerritApproval(); 152 | nulApproval.setValue("0"); 153 | nulApproval.setType("NUL"); 154 | approvals.add(nulApproval); 155 | assertSame(nulApproval, action.getMostSignificantScore(approvals)); 156 | 157 | // One negative input = negative output 158 | approvals.add(APPROVAL_NEGATIVE); 159 | assertSame(APPROVAL_NEGATIVE, action.getMostSignificantScore(approvals)); 160 | 161 | // One negative + one positive = still negative output 162 | approvals.add(APPROVAL_POSITIVE); 163 | approvals.add(APPROVAL_POSITIVE_2); 164 | assertSame(APPROVAL_NEGATIVE, action.getMostSignificantScore(approvals)); 165 | 166 | // Only positive input(s) = positive output 167 | approvals.remove(APPROVAL_NEGATIVE); 168 | assertSame(APPROVAL_POSITIVE_2, action.getMostSignificantScore(approvals)); 169 | 170 | approvals.remove(APPROVAL_POSITIVE_2); 171 | assertSame(APPROVAL_POSITIVE, action.getMostSignificantScore(approvals)); 172 | } 173 | 174 | @Test 175 | public void testPopulateVelocityParams() { 176 | HashMap velocityParams = new HashMap<>(); 177 | @SuppressWarnings("rawtypes") 178 | Map expected = setUpExpectedVelocityParams(); 179 | action.populateVelocityParams(velocityParams); 180 | assertEquals(expected, velocityParams); 181 | } 182 | 183 | @SuppressWarnings("unchecked") 184 | private Map setUpExpectedVelocityParams() { 185 | return (Map) EasyMap.build("change", (Object) change, 186 | "formatLastUpdated", (Object) TEST_FORMATTED_LAST_UPDATED, 187 | "isoLastUpdated", (Object) TEST_ISO_LAST_UPDATED, 188 | "baseurl", (Object) BASE_URL); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/tabpanel/SubtaskReviewsIssueActionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 17 | 18 | import com.atlassian.core.util.collection.EasyList; 19 | import com.atlassian.jira.issue.Issue; 20 | import com.atlassian.jira.plugin.issuetabpanel.IssueTabPanelModuleDescriptor; 21 | 22 | import org.junit.After; 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | import org.mockito.Mock; 26 | 27 | import java.sql.Timestamp; 28 | import java.util.HashMap; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | import static org.junit.Assert.*; 33 | import static org.mockito.Mockito.mock; 34 | import static org.mockito.Mockito.when; 35 | import static org.mockito.MockitoAnnotations.initMocks; 36 | 37 | /** 38 | * @author Joe Hansche 39 | */ 40 | public class SubtaskReviewsIssueActionTest { 41 | 42 | @Mock 43 | IssueTabPanelModuleDescriptor descriptor; 44 | 45 | @Mock 46 | Issue subtask; 47 | 48 | @Mock 49 | GerritChange change1; 50 | 51 | @Mock 52 | GerritChange change2; 53 | 54 | @Before 55 | public void setUp() throws Exception { 56 | initMocks(this); 57 | } 58 | 59 | @After 60 | public void tearDown() throws Exception { 61 | } 62 | 63 | /** 64 | * Test method for 65 | * {@link SubtaskReviewsIssueAction#SubtaskReviewsIssueAction(IssueTabPanelModuleDescriptor, Issue, List)} 66 | * . 67 | */ 68 | @Test 69 | public void testCtor() { 70 | SubtaskReviewsIssueAction obj = new SubtaskReviewsIssueAction(descriptor, null, null); 71 | assertTrue(obj instanceof SubtaskReviewsIssueAction); 72 | } 73 | 74 | /** 75 | * Test method for {@link SubtaskReviewsIssueAction#isDisplayActionAllTab()} . 76 | */ 77 | @Test 78 | public void testIsDisplayActionAllTab() { 79 | SubtaskReviewsIssueAction obj = new SubtaskReviewsIssueAction(descriptor, null, null); 80 | assertFalse(obj.isDisplayActionAllTab()); 81 | } 82 | 83 | /** 84 | * Test method for {@link SubtaskReviewsIssueAction#getTimePerformed()}. 85 | */ 86 | @Test 87 | public void testGetTimePerformed() { 88 | Timestamp ts = mock(Timestamp.class); 89 | when(subtask.getUpdated()).thenReturn(ts); 90 | 91 | SubtaskReviewsIssueAction obj = new SubtaskReviewsIssueAction(descriptor, subtask, null); 92 | 93 | assertSame(ts, obj.getTimePerformed()); 94 | } 95 | 96 | /** 97 | * Test method for {@link SubtaskReviewsIssueAction#populateVelocityParams(Map)} . 98 | */ 99 | @Test 100 | public void testPopulateVelocityParamsMap_nullChanges() { 101 | Map params = new HashMap<>(); 102 | SubtaskReviewsIssueAction obj = new SubtaskReviewsIssueAction(descriptor, subtask, null); 103 | 104 | obj.populateVelocityParams(params); 105 | 106 | assertSame(subtask, params.get("subtask")); 107 | assertNull(params.get("changes")); 108 | } 109 | 110 | /** 111 | * Test method for {@link SubtaskReviewsIssueAction#populateVelocityParams(Map)} . 112 | */ 113 | @SuppressWarnings("rawtypes") 114 | @Test 115 | public void testPopulateVelocityParamsMap() { 116 | Map params = new HashMap<>(); 117 | List changes = EasyList.build(change1, change2); 118 | 119 | @SuppressWarnings("unchecked") 120 | SubtaskReviewsIssueAction obj = new SubtaskReviewsIssueAction(descriptor, subtask, changes); 121 | 122 | obj.populateVelocityParams(params); 123 | 124 | assertSame(subtask, params.get("subtask")); 125 | assertNotNull(params.get("changes")); 126 | assertEquals(2, ((List) params.get("changes")).size()); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/tabpanel/SubtaskReviewsTabPanelTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.tabpanel; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 17 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 18 | 19 | import com.atlassian.jira.issue.Issue; 20 | import com.atlassian.jira.plugin.issuetabpanel.IssueAction; 21 | import com.atlassian.jira.user.ApplicationUser; 22 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 23 | 24 | import org.junit.After; 25 | import org.junit.Before; 26 | import org.junit.Test; 27 | import org.mockito.Mock; 28 | 29 | import java.io.File; 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | 33 | import static org.junit.Assert.*; 34 | import static org.mockito.Mockito.mock; 35 | import static org.mockito.Mockito.when; 36 | import static org.mockito.MockitoAnnotations.initMocks; 37 | 38 | /** 39 | * @author Joe Hansche 40 | */ 41 | public class SubtaskReviewsTabPanelTest { 42 | 43 | @Mock 44 | private GerritConfiguration configuration; 45 | @Mock 46 | private IssueReviewsManager reviewsManager; 47 | 48 | @Mock 49 | Issue issue; 50 | @Mock 51 | ApplicationUser user; 52 | 53 | Issue subtask1; 54 | Issue subtask2; 55 | Issue subtask3; 56 | 57 | @Before 58 | public void setUp() throws Exception { 59 | initMocks(this); 60 | 61 | setUpConfiguration(); 62 | } 63 | 64 | @After 65 | public void tearDown() throws Exception { 66 | } 67 | 68 | private void setUpConfiguration() { 69 | when(configuration.getSshHostname()).thenReturn("gerrit.company.com"); 70 | when(configuration.getSshUsername()).thenReturn("jira"); 71 | File file = mock(File.class); 72 | when(configuration.getSshPrivateKey()).thenReturn(file); 73 | when(file.exists()).thenReturn(true); 74 | } 75 | 76 | private List setUpSubtasks() { 77 | List issues = new ArrayList<>(); 78 | 79 | subtask1 = mock(Issue.class); 80 | subtask2 = mock(Issue.class); 81 | subtask3 = mock(Issue.class); 82 | 83 | when(subtask1.getKey()).thenReturn("SUB-1"); 84 | when(subtask2.getKey()).thenReturn("SUB-2"); 85 | when(subtask3.getKey()).thenReturn("SUB-3"); 86 | 87 | issues.add(subtask1); 88 | issues.add(subtask2); 89 | issues.add(subtask3); 90 | 91 | return issues; 92 | } 93 | 94 | /** 95 | * Test method for 96 | * {@link SubtaskReviewsTabPanel#SubtaskReviewsTabPanel(GerritConfiguration, IssueReviewsManager)} 97 | */ 98 | @Test 99 | public void testCtor() { 100 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 101 | assertTrue(obj instanceof SubtaskReviewsTabPanel); 102 | } 103 | 104 | /** 105 | * Test method for 106 | * {@link SubtaskReviewsTabPanel#showPanel(com.atlassian.jira.plugin.issuetabpanel.ShowPanelRequest)} 107 | */ 108 | @Test 109 | public void testShowPanelShowPanelRequest_empty() { 110 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 111 | // Returns false because the subtasks are empty 112 | assertFalse(obj.showPanel(issue, user)); 113 | 114 | when(issue.getSubTaskObjects()).thenReturn(null); 115 | // Returns false because subtasks is null 116 | assertFalse(obj.showPanel(issue, user)); 117 | } 118 | 119 | /** 120 | * Test method for 121 | * {@link SubtaskReviewsTabPanel#showPanel(com.atlassian.jira.plugin.issuetabpanel.ShowPanelRequest)} 122 | */ 123 | @Test 124 | public void testShowPanelShowPanelRequest_nullSubtasks() { 125 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 126 | // Returns false because the configuration is empty 127 | assertFalse(obj.showPanel(issue, user)); 128 | } 129 | 130 | /** 131 | * Test method for 132 | * {@link SubtaskReviewsTabPanel#showPanel(com.atlassian.jira.plugin.issuetabpanel.ShowPanelRequest)} 133 | */ 134 | @Test 135 | public void testShowPanelShowPanelRequest_noSubtasks() { 136 | when(issue.getSubTaskObjects()).thenReturn(new ArrayList<>()); 137 | 138 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 139 | // Returns false because the configuration is empty 140 | assertFalse(obj.showPanel(issue, user)); 141 | } 142 | 143 | @Test 144 | public void testGetActions_noSubtasks() { 145 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 146 | // Returns false because the configuration is empty 147 | List actions = obj.getActions(issue, user); 148 | assertEquals(0, actions.size()); 149 | } 150 | 151 | @Test 152 | public void testGetActions_someSubtasks() { 153 | List subtasks = setUpSubtasks(); 154 | when(issue.getSubTaskObjects()).thenReturn(subtasks); 155 | 156 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 157 | // Returns false because the configuration is empty 158 | List actions = obj.getActions(issue, user); 159 | assertEquals(3, actions.size()); 160 | } 161 | 162 | @Test(expected = RuntimeException.class) 163 | public void testGetActions_gerritError() throws RuntimeException, GerritQueryException { 164 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 165 | 166 | List subtasks = setUpSubtasks(); 167 | when(issue.getSubTaskObjects()).thenReturn(subtasks); 168 | 169 | GerritQueryException exc = new GerritQueryException(); 170 | when(reviewsManager.getReviewsForIssue(subtask2)).thenThrow(exc); 171 | 172 | obj.getActions(issue, user); 173 | } 174 | 175 | /** 176 | * Test method for {@link SubtaskReviewsTabPanel#isConfigurationReady()} to indicate 177 | * Configuration is not ready if certain conditions are not met. 178 | */ 179 | @Test 180 | public void testConfigurationNotReady() { 181 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(null, null); 182 | // False because configuration == null 183 | assertFalse(obj.showPanel(issue, user)); 184 | 185 | // Now setup the normal mock configuration 186 | obj = new SubtaskReviewsTabPanel(configuration, null); 187 | 188 | // SSH file not exist 189 | when(configuration.getSshPrivateKey().exists()).thenReturn(false); 190 | assertFalse(obj.showPanel(issue, user)); 191 | 192 | // SSH file is null 193 | when(configuration.getSshPrivateKey()).thenReturn(null); 194 | assertFalse(obj.showPanel(issue, user)); 195 | 196 | // Username is null 197 | when(configuration.getSshUsername()).thenReturn(null); 198 | assertFalse(obj.showPanel(issue, user)); 199 | 200 | // Hostname is null 201 | when(configuration.getSshHostname()).thenReturn(null); 202 | assertFalse(obj.showPanel(issue, user)); 203 | } 204 | 205 | /** 206 | * Test method for 207 | * {@link SubtaskReviewsTabPanel#showPanel(com.atlassian.jira.plugin.issuetabpanel.ShowPanelRequest)} 208 | * when the issue has subtasks. 209 | */ 210 | @Test 211 | public void testShowPanelShowPanelRequest_withSubtasks() { 212 | List subtasks = setUpSubtasks(); 213 | when(issue.getSubTaskObjects()).thenReturn(subtasks); 214 | 215 | SubtaskReviewsTabPanel obj = new SubtaskReviewsTabPanel(configuration, reviewsManager); 216 | assertTrue(obj.showPanel(issue, user)); 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/webpanel/ShowReviewsWebPanelConditionTest.java: -------------------------------------------------------------------------------- 1 | package com.meetme.plugins.jira.gerrit.webpanel; 2 | 3 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 4 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 5 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 6 | 7 | import com.atlassian.jira.issue.Issue; 8 | import com.atlassian.jira.project.MockProject; 9 | import com.atlassian.jira.project.Project; 10 | import com.atlassian.jira.project.ProjectManager; 11 | import com.google.common.collect.Lists; 12 | import com.google.common.collect.Maps; 13 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 14 | 15 | import org.hamcrest.core.Is; 16 | import org.junit.Assert; 17 | import org.junit.Before; 18 | import org.junit.Test; 19 | import org.mockito.Mock; 20 | 21 | import java.util.*; 22 | import java.util.stream.Collectors; 23 | 24 | import static java.util.Collections.singletonList; 25 | import static java.util.Collections.singletonMap; 26 | import static org.junit.Assert.assertFalse; 27 | import static org.junit.Assert.assertTrue; 28 | import static org.mockito.Matchers.any; 29 | import static org.mockito.Mockito.mock; 30 | import static org.mockito.Mockito.when; 31 | import static org.mockito.MockitoAnnotations.initMocks; 32 | 33 | public class ShowReviewsWebPanelConditionTest { 34 | 35 | ShowReviewsWebPanelCondition showReviewsWebPanelCondition; 36 | 37 | @Mock 38 | private GerritConfiguration gerritConfiguration; 39 | 40 | @Mock 41 | private Issue issue; 42 | 43 | @Mock 44 | private IssueReviewsManager issueReviewsManager; 45 | 46 | @Mock 47 | private ProjectManager projectManager; 48 | 49 | private static final List projects = Collections.unmodifiableList(new ArrayList() {{ 50 | add(new MockProject(0L, "KEY_0L", "NAME_0L")); 51 | add(new MockProject(1L, "KEY_1L", "NAME_1L")); 52 | add(new MockProject(2L, "KEY_2L", "NAME_2L")); 53 | }}); 54 | 55 | @Before 56 | public void setUp() { 57 | initMocks(this); 58 | when(issue.getProjectId()).thenReturn(1L); 59 | when(issue.getId()).thenReturn(10000000L); 60 | when(projectManager.getProjects()).thenReturn(projects); 61 | showReviewsWebPanelCondition = new ShowReviewsWebPanelCondition(issueReviewsManager, gerritConfiguration); 62 | when(gerritConfiguration.getUseGerritProjectWhitelist()).thenReturn(true); 63 | } 64 | 65 | @Test 66 | public void shouldDisplayWithAlwaysFlag() throws GerritQueryException { 67 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(true); 68 | when(issueReviewsManager.getReviewsForIssue(any(Issue.class))).thenReturn(Lists.newArrayList()); 69 | when(gerritConfiguration.getIdsOfKnownGerritProjects()).thenReturn(projects.stream().map(p -> p.getId() 70 | .toString()).collect(Collectors.toList())); 71 | 72 | assertTrue(showReviewsWebPanelCondition.shouldDisplay(singletonMap("issue", issue))); 73 | } 74 | 75 | @Test 76 | public void shouldDisplayMapEqualsNull() { 77 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(false); 78 | 79 | assertFalse(showReviewsWebPanelCondition.shouldDisplay(null)); 80 | } 81 | 82 | @Test 83 | public void shouldDisplayMapWithoutIssue() { 84 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(false); 85 | 86 | assertFalse(showReviewsWebPanelCondition.shouldDisplay(Maps.newHashMap())); 87 | } 88 | 89 | @Test 90 | public void shouldDisplayEmptyWhiteList() { 91 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(false); 92 | when(gerritConfiguration.getIdsOfKnownGerritProjects()).thenReturn(Lists.newArrayList()); 93 | 94 | assertFalse(showReviewsWebPanelCondition.shouldDisplay(singletonMap("issue", issue))); 95 | } 96 | 97 | @Test 98 | public void shouldDisplayProjectIsOnWhiteList() throws Exception { 99 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(false); 100 | when(issueReviewsManager.getReviewsForIssue(any(Issue.class))).thenReturn(singletonList(new GerritChange())); 101 | when(gerritConfiguration.getIdsOfKnownGerritProjects()).thenReturn(projects.stream().map(p -> p.getId() 102 | .toString()).collect(Collectors.toList())); 103 | assertTrue(showReviewsWebPanelCondition.shouldDisplay(singletonMap("issue", issue))); 104 | } 105 | 106 | @Test 107 | public void shouldDisplayProjectIsNotOnWhiteList() { 108 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(false); 109 | when(gerritConfiguration.getIdsOfKnownGerritProjects()).thenReturn(projects.stream().filter(project -> !project 110 | .getId().equals(1L)).map(project -> project.getId().toString()).collect(Collectors.toList())); 111 | assertFalse(showReviewsWebPanelCondition.shouldDisplay(singletonMap("issue", issue))); 112 | } 113 | 114 | @Test 115 | public void shouldDisplayNoConnectionToGerrit() throws GerritQueryException { 116 | 117 | when(gerritConfiguration.getIdsOfKnownGerritProjects()).thenReturn(projects.stream().map(p -> p.getId() 118 | .toString()).collect(Collectors.toList())); 119 | when(issueReviewsManager.getReviewsForIssue(any(Issue.class))).thenThrow(new GerritQueryException()); 120 | 121 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(true); 122 | assertTrue(showReviewsWebPanelCondition.shouldDisplay(singletonMap("issue", issue))); 123 | 124 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(false); 125 | assertFalse(showReviewsWebPanelCondition.shouldDisplay(singletonMap("issue", issue))); 126 | } 127 | 128 | @Test 129 | public void issuePanelshouldDisplayEvenGerritWhitelistIsOff() { 130 | final GerritConfiguration gerritConfiguration = mock(GerritConfiguration.class); 131 | when(gerritConfiguration.getUseGerritProjectWhitelist()).thenReturn(false); 132 | final Issue issue = mock(Issue.class); 133 | when(gerritConfiguration.getShowsEmptyPanel()).thenReturn(true); 134 | Map map = new HashMap<>(); 135 | map.put("issue", issue); 136 | ShowReviewsWebPanelCondition showReviewsWebPanelCondition = new ShowReviewsWebPanelCondition(null, 137 | gerritConfiguration); 138 | final boolean shouldDisplay = showReviewsWebPanelCondition.shouldDisplay(map); 139 | Assert.assertThat(shouldDisplay, Is.is(true)); 140 | } 141 | } -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/workflow/AbstractWorkflowTest.java: -------------------------------------------------------------------------------- 1 | package com.meetme.plugins.jira.gerrit.workflow; 2 | 3 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 4 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 5 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 6 | 7 | import com.atlassian.core.util.collection.EasyList; 8 | import com.atlassian.core.util.map.EasyMap; 9 | import com.atlassian.jira.component.ComponentAccessor; 10 | import com.atlassian.jira.issue.MutableIssue; 11 | import com.atlassian.jira.mock.component.MockComponentWorker; 12 | import com.atlassian.jira.mock.issue.MockIssue; 13 | import com.atlassian.jira.user.ApplicationUser; 14 | import com.opensymphony.workflow.WorkflowContext; 15 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 16 | 17 | import org.mockito.Mock; 18 | 19 | import java.io.File; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | import static org.mockito.Mockito.mock; 24 | import static org.mockito.Mockito.when; 25 | import static org.mockito.MockitoAnnotations.initMocks; 26 | 27 | /** 28 | * Base class for setting up mocks 29 | * 30 | * @since v5.0 31 | */ 32 | public abstract class AbstractWorkflowTest { 33 | @SuppressWarnings("rawtypes") 34 | protected Map transientVars, args; 35 | protected MockComponentWorker mockComponents; 36 | protected MutableIssue mockIssue; 37 | 38 | @Mock 39 | protected ApplicationUser mockUser; 40 | @Mock 41 | protected IssueReviewsManager reviewsManager; 42 | @Mock 43 | protected GerritConfiguration configuration; 44 | @Mock 45 | protected WorkflowContext workflowContext; 46 | 47 | public void setUp() throws Exception { 48 | initMocks(this); 49 | createMocks(); 50 | stubMockMethods(); 51 | } 52 | 53 | public void tearDown() throws Exception { 54 | } 55 | 56 | protected void setUpConfiguration() { 57 | when(configuration.getSshHostname()).thenReturn("gerrit.company.com"); 58 | when(configuration.getSshUsername()).thenReturn("jira"); 59 | File file = mock(File.class); 60 | when(configuration.getSshPrivateKey()).thenReturn(file); 61 | when(file.exists()).thenReturn(true); 62 | } 63 | 64 | protected void setUpUser() { 65 | when(workflowContext.getCaller()).thenReturn(mockUser.getName()); 66 | } 67 | 68 | private void createMocks() { 69 | mockComponents = new MockComponentWorker(); 70 | mockIssue = new MockIssue(); 71 | 72 | when(mockUser.getName()).thenReturn("milton"); 73 | } 74 | 75 | private void stubMockMethods() { 76 | ComponentAccessor.initialiseWorker(mockComponents); 77 | setUpConfiguration(); 78 | 79 | mockIssue.setKey("FOO-123"); 80 | 81 | transientVars = EasyMap.build("issue", mockIssue, "context", workflowContext); 82 | args = EasyMap.build("username", mockUser.getName()); 83 | } 84 | 85 | protected void stubFailingReviews() throws GerritQueryException { 86 | GerritQueryException gqe = new GerritQueryException("Expected exception"); 87 | when(reviewsManager.getReviewsForIssue(mockIssue)).thenThrow(gqe); 88 | } 89 | 90 | @SuppressWarnings("unchecked") 91 | protected void stubEmptyReviews() throws GerritQueryException { 92 | @SuppressWarnings("rawtypes") 93 | List reviews = EasyList.build(); 94 | when(reviewsManager.getReviewsForIssue(mockIssue)).thenReturn(reviews); 95 | } 96 | 97 | @SuppressWarnings("unchecked") 98 | protected void stubOneReview() throws GerritQueryException { 99 | GerritChange change = mock(GerritChange.class); 100 | @SuppressWarnings("rawtypes") 101 | List reviews = EasyList.build(change); 102 | when(reviewsManager.getReviewsForIssue(mockIssue)).thenReturn(reviews); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/test/java/com/meetme/plugins/jira/gerrit/workflow/function/ApprovalFunctionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 MeetMe, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.meetme.plugins.jira.gerrit.workflow.function; 15 | 16 | import com.meetme.plugins.jira.gerrit.data.GerritConfiguration; 17 | import com.meetme.plugins.jira.gerrit.data.IssueReviewsManager; 18 | import com.meetme.plugins.jira.gerrit.data.dto.GerritChange; 19 | import com.meetme.plugins.jira.gerrit.workflow.AbstractWorkflowTest; 20 | 21 | import com.atlassian.core.user.preferences.Preferences; 22 | import com.atlassian.jira.user.preferences.UserPreferencesManager; 23 | import com.opensymphony.module.propertyset.PropertySet; 24 | import com.opensymphony.workflow.WorkflowException; 25 | import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritQueryException; 26 | 27 | import org.junit.After; 28 | import org.junit.Before; 29 | import org.junit.Test; 30 | import org.mockito.Mock; 31 | import org.mockito.Mockito; 32 | 33 | import java.io.IOException; 34 | import java.util.List; 35 | import java.util.Map; 36 | 37 | import static org.junit.Assert.*; 38 | import static org.mockito.Mockito.*; 39 | 40 | /** 41 | * @author Joe Hansche 42 | */ 43 | public abstract class ApprovalFunctionTest extends AbstractWorkflowTest { 44 | @Mock 45 | PropertySet ps; 46 | @Mock 47 | UserPreferencesManager userPrefsManager; 48 | @Mock 49 | Preferences mockPrefs; 50 | 51 | @Before 52 | public void setUp() throws Exception { 53 | super.setUp(); 54 | 55 | setUpUser(); 56 | setUpUserPrefs(); 57 | } 58 | 59 | private void setUpUserPrefs() { 60 | when(userPrefsManager.getPreferences(mockUser)).thenReturn(mockPrefs); 61 | } 62 | 63 | @After 64 | public void tearDown() throws Exception { 65 | super.tearDown(); 66 | } 67 | 68 | /** 69 | * Test method for 70 | * {@link ApprovalFunction#ApprovalFunction(GerritConfiguration, IssueReviewsManager, UserPreferencesManager)} 71 | * . 72 | */ 73 | @Test 74 | public void testCtor() { 75 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 76 | assertTrue(obj instanceof ApprovalFunction); 77 | } 78 | 79 | /** 80 | * Test method for {@link ApprovalFunction#isConfigurationReady()}. 81 | */ 82 | @Test 83 | public void testConfigurationReady() { 84 | ApprovalFunction obj = new ApprovalFunction(null, null, null); 85 | // configuration is null 86 | assertFalse(obj.isConfigurationReady()); 87 | 88 | obj = new ApprovalFunction(configuration, null, null); 89 | // configuration is null 90 | assertTrue(obj.isConfigurationReady()); 91 | 92 | // SSH file not exist 93 | when(configuration.getSshPrivateKey().exists()).thenReturn(false); 94 | assertFalse(obj.isConfigurationReady()); 95 | 96 | // SSH file is null 97 | when(configuration.getSshPrivateKey()).thenReturn(null); 98 | assertFalse(obj.isConfigurationReady()); 99 | 100 | // Username is null 101 | when(configuration.getSshUsername()).thenReturn(null); 102 | assertFalse(obj.isConfigurationReady()); 103 | 104 | // Hostname is null 105 | when(configuration.getSshHostname()).thenReturn(null); 106 | assertFalse(obj.isConfigurationReady()); 107 | } 108 | 109 | /** 110 | * Test method for {@link ApprovalFunction#execute(Map, Map, PropertySet)}. 111 | * 112 | * @throws WorkflowException 113 | */ 114 | @Test(expected = IllegalStateException.class) 115 | public void testExecute_notReady() throws WorkflowException { 116 | ApprovalFunction obj = new ApprovalFunction(null, null, null); 117 | obj.execute(null, null, null); 118 | } 119 | 120 | @Test 121 | public void testGetIssueKey() { 122 | ApprovalFunction obj = new ApprovalFunction(configuration, null, null); 123 | String actual = obj.getIssueKey(transientVars); 124 | assertEquals("FOO-123", actual); 125 | } 126 | 127 | @Test 128 | public void testGetUserPrefs() { 129 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 130 | Preferences actual = obj.getUserPrefs(transientVars, args); 131 | assertSame(mockPrefs, actual); 132 | } 133 | 134 | @Test(expected = WorkflowException.class) 135 | public void testGetReviews_failure() throws WorkflowException, GerritQueryException { 136 | stubFailingReviews(); 137 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 138 | obj.getReviews(mockIssue); 139 | } 140 | 141 | @Test 142 | public void testGetReviews_success() throws WorkflowException, GerritQueryException { 143 | stubOneReview(); 144 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 145 | List actual = obj.getReviews(mockIssue); 146 | assertEquals(1, actual.size()); 147 | } 148 | 149 | @SuppressWarnings("unchecked") 150 | @Test(expected = WorkflowException.class) 151 | public void testExecute_gerritFailed() throws WorkflowException, IOException { 152 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 153 | when(reviewsManager.doApprovals(mockIssue, Mockito.anyList(), Mockito.anyString(), eq(mockPrefs))).thenReturn(false); 154 | obj.execute(transientVars, args, ps); 155 | 156 | verify(reviewsManager, times(1)).doApprovals(mockIssue, anyList(), anyString(), eq(mockPrefs)); 157 | } 158 | 159 | @SuppressWarnings("unchecked") 160 | @Test(expected = WorkflowException.class) 161 | public void testExecute_gerritThrows() throws WorkflowException, IOException { 162 | IOException exc = new IOException(); 163 | 164 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 165 | when(reviewsManager.doApprovals(mockIssue, Mockito.anyList(), Mockito.anyString(), eq(mockPrefs))).thenThrow(exc); 166 | obj.execute(transientVars, args, ps); 167 | 168 | verify(reviewsManager, times(1)).doApprovals(mockIssue, anyList(), anyString(), eq(mockPrefs)); 169 | } 170 | 171 | @SuppressWarnings("unchecked") 172 | @Test 173 | public void testExecute_success() throws WorkflowException, IOException { 174 | ApprovalFunction obj = new ApprovalFunction(configuration, reviewsManager, userPrefsManager); 175 | when(reviewsManager.doApprovals(mockIssue, Mockito.anyList(), Mockito.anyString(), eq(mockPrefs))).thenReturn(true); 176 | obj.execute(transientVars, args, ps); 177 | 178 | verify(reviewsManager, times(1)).doApprovals(mockIssue, anyList(), anyString(), eq(mockPrefs)); 179 | } 180 | } 181 | --------------------------------------------------------------------------------