From 649638d30d2d32cd6d7bb32d00b80f84adfb08b8 Mon Sep 17 00:00:00 2001 From: Tomas Bjerre Date: Sun, 25 Dec 2016 22:25:23 +0100 Subject: [PATCH] Adjustments after merge of #173 * Adding fmt-maven-plugin to format code on Google Java Format. * Correcting warnings from Grunt / JSHint. * Adding, and using, enum, RENDER_FOR, in PrnfbRenderer. --- CHANGELOG.md | 25 +- pom.xml | 22 +- .../se/bjurr/prnfb/http/ClientKeyStore.java | 61 +- .../se/bjurr/prnfb/http/HttpResponse.java | 126 +- .../java/se/bjurr/prnfb/http/Invoker.java | 2 +- .../prnfb/http/NotificationResponse.java | 138 +- .../java/se/bjurr/prnfb/http/UrlInvoker.java | 646 +++---- .../listener/PrnfbPullRequestAction.java | 68 +- .../PrnfbPullRequestEventListener.java | 476 ++--- .../prnfb/presentation/ButtonServlet.java | 293 +-- .../presentation/GlobalAdminServlet.java | 157 +- .../presentation/NotificationServlet.java | 165 +- .../presentation/SettingsDataServlet.java | 58 +- .../prnfb/presentation/dto/ButtonDTO.java | 316 ++-- .../presentation/dto/ButtonPressDTO.java | 102 +- .../prnfb/presentation/dto/HeaderDTO.java | 107 +- .../presentation/dto/NotificationDTO.java | 756 ++++---- .../dto/NotificationResponseDTO.java | 170 +- .../prnfb/presentation/dto/ON_OR_OFF.java | 3 +- .../presentation/dto/SettingsDataDTO.java | 205 ++- .../bjurr/prnfb/service/ButtonsService.java | 339 ++-- .../se/bjurr/prnfb/service/PrnfbRenderer.java | 192 +- .../prnfb/service/PrnfbRendererFactory.java | 69 +- .../se/bjurr/prnfb/service/PrnfbVariable.java | 1581 +++++++++++------ .../prnfb/service/PrnfbVariableResolver.java | 15 +- .../se/bjurr/prnfb/service/RepoProtocol.java | 3 +- .../bjurr/prnfb/service/SettingsService.java | 644 +++---- .../bjurr/prnfb/service/UserCheckService.java | 261 +-- .../java/se/bjurr/prnfb/settings/HasUuid.java | 3 +- .../se/bjurr/prnfb/settings/PrnfbButton.java | 252 +-- .../se/bjurr/prnfb/settings/PrnfbHeader.java | 105 +- .../prnfb/settings/PrnfbNotification.java | 677 +++---- .../settings/PrnfbNotificationBuilder.java | 533 +++--- .../bjurr/prnfb/settings/PrnfbSettings.java | 122 +- .../prnfb/settings/PrnfbSettingsBuilder.java | 132 +- .../prnfb/settings/PrnfbSettingsData.java | 195 +- .../settings/PrnfbSettingsDataBuilder.java | 144 +- .../prnfb/settings/TRIGGER_IF_MERGE.java | 4 +- .../se/bjurr/prnfb/settings/USER_LEVEL.java | 4 +- .../prnfb/settings/ValidationException.java | 42 +- .../settings/legacy/AdminFormValues.java | 95 +- .../bjurr/prnfb/settings/legacy/Header.java | 26 +- .../prnfb/settings/legacy/PrnfbButton.java | 52 +- .../settings/legacy/PrnfbNotification.java | 285 +-- .../legacy/PrnfbNotificationBuilder.java | 399 +++-- .../settings/legacy/PrnfbPredicates.java | 20 +- .../prnfb/settings/legacy/PrnfbSettings.java | 84 +- .../settings/legacy/PrnfbSettingsBuilder.java | 179 +- .../settings/legacy/SettingsStorage.java | 457 ++--- .../settings/legacy/ValidationException.java | 42 +- .../prnfb/transformer/ButtonTransformer.java | 88 +- .../transformer/NotificationTransformer.java | 222 +-- .../transformer/SettingsTransformer.java | 36 +- src/main/resources/admin.vm | 6 +- src/main/resources/atlassian-plugin.xml | 2 +- src/main/resources/pr-triggerbutton.js | 258 +-- .../bjurr/prnfb/http/ClientKeyStoreTest.java | 98 +- .../se/bjurr/prnfb/http/UrlInvokerTest.java | 372 ++-- .../prnfb/listener/FakeExecutorService.java | 110 +- .../PrnfbPullRequestEventListenerTest.java | 783 ++++---- .../prnfb/presentation/ButtonServletTest.java | 360 ++-- .../presentation/GlobalAdminServletTest.java | 77 +- .../presentation/NotificationServletTest.java | 189 +- .../presentation/SettingsDataServletTest.java | 109 +- .../prnfb/service/ButtonsServiceTest.java | 499 +++--- .../prnfb/service/PluginSettingsMap.java | 52 +- .../prnfb/service/PrnfbRendererTest.java | 348 ++-- .../prnfb/service/PrnfbVariableTest.java | 89 +- .../prnfb/service/SettingsServiceTest.java | 526 +++--- .../prnfb/service/UserCheckServiceTest.java | 233 ++- src/test/java/se/bjurr/prnfb/test/Podam.java | 8 +- .../integration/PrnfbTestIntegration.java | 282 +-- .../transformer/ButtonTransformerTest.java | 23 +- .../NotificationTransformerTest.java | 29 +- .../SettingsDataTransformerTest.java | 23 +- 75 files changed, 8407 insertions(+), 7267 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f27884f..70629dca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,10 +3,33 @@ Changelog of Pull Request Notifier for Bitbucket. ## Unreleased +### GitHub [#173](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/pull/173) Add the ability to specify forms for buttons + Adjustments after merge of + + * Adding fmt-maven-plugin to format code on Google Java Format. + * Correcting warnings from Grunt / JSHint. + * Adding, and using, enum, RENDER_FOR, in PrnfbRenderer. + + [95fcfc4f334fb1e](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/commit/95fcfc4f334fb1e) Tomas Bjerre *2016-12-25 21:29:22* + +### No issue + Add interactive forms to buttons + +This change adds the ability to specify a JSON-based form for a given +button, which will get automatically rendered when the button is pressed. +The submitted data is available as serialized JSON in the ${BUTTON_FORM_DATA} +variable. + +For the specification of what a form looks like and it's serialized result, +look at README.md in the change. + + [2a5c79347b713c8](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/commit/2a5c79347b713c8) Itay Neeman *2016-12-24 20:55:47* + +## 2.43 ### GitHub [#169](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/issues/169) What about pull request description ? Removing PULL_REQUEST_DESCRIPTION from EVERYTHING_URL - [c616c4c575be53a](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/commit/c616c4c575be53a) Tomas Bjerre *2016-12-15 21:18:37* + [5af97f531cae647](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/commit/5af97f531cae647) Tomas Bjerre *2016-12-15 21:19:12* ## 2.42 ### GitHub [#169](https://github.com/tomasbjerre/pull-request-notifier-for-bitbucket/issues/169) What about pull request description ? diff --git a/pom.xml b/pom.xml index b6d0746f..39b4773f 100644 --- a/pom.xml +++ b/pom.xml @@ -207,9 +207,9 @@ Changelog of Pull Request Notifier for Bitbucket. true - com.atlassian.labs.plugins - quickreload - ${quick.reload.version} + com.atlassian.labs.plugins + quickreload + ${quick.reload.version} @@ -244,6 +244,18 @@ Changelog of Pull Request Notifier for Bitbucket. + + com.coveo + fmt-maven-plugin + 1.3.0 + + + + format + + + + @@ -275,7 +287,7 @@ Changelog of Pull Request Notifier for Bitbucket. 4.11.1 ${bitbucket.version} - 2.0.0 + 2.0.0 6.1.0 - + \ No newline at end of file diff --git a/src/main/java/se/bjurr/prnfb/http/ClientKeyStore.java b/src/main/java/se/bjurr/prnfb/http/ClientKeyStore.java index ccd99f8d..0cbe95fb 100644 --- a/src/main/java/se/bjurr/prnfb/http/ClientKeyStore.java +++ b/src/main/java/se/bjurr/prnfb/http/ClientKeyStore.java @@ -19,39 +19,40 @@ */ public class ClientKeyStore { - private KeyStore keyStore = null; - private char[] password = null; - - public ClientKeyStore(PrnfbSettingsData settings) { - if (settings.getKeyStore().isPresent()) { - File keyStoreFile = new File(settings.getKeyStore().get()); - try { - this.keyStore = getKeyStore(settings.getKeyStoreType()); - - if (settings.getKeyStorePassword().isPresent()) { - this.password = settings.getKeyStorePassword().get().toCharArray(); + private KeyStore keyStore = null; + private char[] password = null; + + public ClientKeyStore(PrnfbSettingsData settings) { + if (settings.getKeyStore().isPresent()) { + File keyStoreFile = new File(settings.getKeyStore().get()); + try { + this.keyStore = getKeyStore(settings.getKeyStoreType()); + + if (settings.getKeyStorePassword().isPresent()) { + this.password = settings.getKeyStorePassword().get().toCharArray(); + } + + this.keyStore.load(new FileInputStream(keyStoreFile), this.password); + } catch (Exception e) { + throw new RuntimeException( + "Unable to build keystore from " + keyStoreFile.getAbsolutePath(), e); + } } - - this.keyStore.load(new FileInputStream(keyStoreFile), this.password); - } catch (Exception e) { - throw new RuntimeException("Unable to build keystore from " + keyStoreFile.getAbsolutePath(), e); - } } - } - public Optional getKeyStore() { - return fromNullable(this.keyStore); - } + public Optional getKeyStore() { + return fromNullable(this.keyStore); + } - public char[] getPassword() { - return this.password; - } + public char[] getPassword() { + return this.password; + } - private KeyStore getKeyStore(String keyStoreType) throws KeyStoreException { - if (keyStoreType != null) { - return KeyStore.getInstance(keyStoreType); - } else { - return KeyStore.getInstance(KeyStore.getDefaultType()); + private KeyStore getKeyStore(String keyStoreType) throws KeyStoreException { + if (keyStoreType != null) { + return KeyStore.getInstance(keyStoreType); + } else { + return KeyStore.getInstance(KeyStore.getDefaultType()); + } } - } -} \ No newline at end of file +} diff --git a/src/main/java/se/bjurr/prnfb/http/HttpResponse.java b/src/main/java/se/bjurr/prnfb/http/HttpResponse.java index ba23c78a..a653318b 100644 --- a/src/main/java/se/bjurr/prnfb/http/HttpResponse.java +++ b/src/main/java/se/bjurr/prnfb/http/HttpResponse.java @@ -3,74 +3,80 @@ import java.net.URI; public class HttpResponse { - private final String content; + private final String content; - private final int status; + private final int status; - private final URI uri; + private final URI uri; - public HttpResponse(URI uri, int status, String content) { - this.uri = uri; - this.status = status; - this.content = content; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; + public HttpResponse(URI uri, int status, String content) { + this.uri = uri; + this.status = status; + this.content = content; } - HttpResponse other = (HttpResponse) obj; - if (this.content == null) { - if (other.content != null) { - return false; - } - } else if (!this.content.equals(other.content)) { - return false; - } - if (this.status != other.status) { - return false; - } - if (this.uri == null) { - if (other.uri != null) { - return false; - } - } else if (!this.uri.equals(other.uri)) { - return false; + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + HttpResponse other = (HttpResponse) obj; + if (this.content == null) { + if (other.content != null) { + return false; + } + } else if (!this.content.equals(other.content)) { + return false; + } + if (this.status != other.status) { + return false; + } + if (this.uri == null) { + if (other.uri != null) { + return false; + } + } else if (!this.uri.equals(other.uri)) { + return false; + } + return true; } - return true; - } - public String getContent() { - return this.content; - } + public String getContent() { + return this.content; + } - public int getStatus() { - return this.status; - } + public int getStatus() { + return this.status; + } - public URI getUri() { - return this.uri; - } + public URI getUri() { + return this.uri; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.content == null) ? 0 : this.content.hashCode()); - result = prime * result + this.status; - result = prime * result + ((this.uri == null) ? 0 : this.uri.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.content == null) ? 0 : this.content.hashCode()); + result = prime * result + this.status; + result = prime * result + ((this.uri == null) ? 0 : this.uri.hashCode()); + return result; + } - @Override - public String toString() { - return "HttpResponse [content=" + this.content + ", status=" + this.status + ", uri=" + this.uri + "]"; - } + @Override + public String toString() { + return "HttpResponse [content=" + + this.content + + ", status=" + + this.status + + ", uri=" + + this.uri + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/http/Invoker.java b/src/main/java/se/bjurr/prnfb/http/Invoker.java index 907cd012..6db7fe4e 100644 --- a/src/main/java/se/bjurr/prnfb/http/Invoker.java +++ b/src/main/java/se/bjurr/prnfb/http/Invoker.java @@ -1,5 +1,5 @@ package se.bjurr.prnfb.http; public interface Invoker { - HttpResponse invoke(UrlInvoker urlInvoker); + HttpResponse invoke(UrlInvoker urlInvoker); } diff --git a/src/main/java/se/bjurr/prnfb/http/NotificationResponse.java b/src/main/java/se/bjurr/prnfb/http/NotificationResponse.java index f8452259..0932c026 100644 --- a/src/main/java/se/bjurr/prnfb/http/NotificationResponse.java +++ b/src/main/java/se/bjurr/prnfb/http/NotificationResponse.java @@ -3,78 +3,84 @@ import java.util.UUID; public class NotificationResponse { - private final HttpResponse httpResponse; - private final UUID notification; - private final String notificationName; + private final HttpResponse httpResponse; + private final UUID notification; + private final String notificationName; - public NotificationResponse(UUID notification, String notificationName, HttpResponse httpResponse) { - this.notification = notification; - this.notificationName = notificationName; - this.httpResponse = httpResponse; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - NotificationResponse other = (NotificationResponse) obj; - if (this.httpResponse == null) { - if (other.httpResponse != null) { - return false; - } - } else if (!this.httpResponse.equals(other.httpResponse)) { - return false; - } - if (this.notification == null) { - if (other.notification != null) { - return false; - } - } else if (!this.notification.equals(other.notification)) { - return false; - } - if (this.notificationName == null) { - if (other.notificationName != null) { - return false; - } - } else if (!this.notificationName.equals(other.notificationName)) { - return false; + public NotificationResponse( + UUID notification, String notificationName, HttpResponse httpResponse) { + this.notification = notification; + this.notificationName = notificationName; + this.httpResponse = httpResponse; } - return true; - } - public HttpResponse getHttpResponse() { - return this.httpResponse; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NotificationResponse other = (NotificationResponse) obj; + if (this.httpResponse == null) { + if (other.httpResponse != null) { + return false; + } + } else if (!this.httpResponse.equals(other.httpResponse)) { + return false; + } + if (this.notification == null) { + if (other.notification != null) { + return false; + } + } else if (!this.notification.equals(other.notification)) { + return false; + } + if (this.notificationName == null) { + if (other.notificationName != null) { + return false; + } + } else if (!this.notificationName.equals(other.notificationName)) { + return false; + } + return true; + } - public UUID getNotification() { - return this.notification; - } + public HttpResponse getHttpResponse() { + return this.httpResponse; + } - public String getNotificationName() { - return this.notificationName; - } + public UUID getNotification() { + return this.notification; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.httpResponse == null) ? 0 : this.httpResponse.hashCode()); - result = prime * result + ((this.notification == null) ? 0 : this.notification.hashCode()); - result = prime * result + ((this.notificationName == null) ? 0 : this.notificationName.hashCode()); - return result; - } + public String getNotificationName() { + return this.notificationName; + } - @Override - public String toString() { - return "NotificationResponse [httpResponse=" + this.httpResponse + ", notification=" + this.notification - + ", notificationName=" + this.notificationName + "]"; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.httpResponse == null) ? 0 : this.httpResponse.hashCode()); + result = prime * result + ((this.notification == null) ? 0 : this.notification.hashCode()); + result = + prime * result + ((this.notificationName == null) ? 0 : this.notificationName.hashCode()); + return result; + } + @Override + public String toString() { + return "NotificationResponse [httpResponse=" + + this.httpResponse + + ", notification=" + + this.notification + + ", notificationName=" + + this.notificationName + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/http/UrlInvoker.java b/src/main/java/se/bjurr/prnfb/http/UrlInvoker.java index 743e13e6..90b715f4 100644 --- a/src/main/java/se/bjurr/prnfb/http/UrlInvoker.java +++ b/src/main/java/se/bjurr/prnfb/http/UrlInvoker.java @@ -55,8 +55,7 @@ /** * If told to accept all certificates, an unsafe X509 trust manager is used.
*
- * If setup of the "trust-all" HttpClient fails, a non-configured HttpClient is - * returned.
+ * If setup of the "trust-all" HttpClient fails, a non-configured HttpClient is returned.
*
* Inspired by:
* Philip Dodds (pdodds) https://github.com/pdodds
@@ -64,331 +63,344 @@ */ public class UrlInvoker { - public enum HTTP_METHOD { - DELETE, GET, POST, PUT - } + public enum HTTP_METHOD { + DELETE, + GET, + POST, + PUT + } + + private static final Logger LOG = getLogger(UrlInvoker.class); + + @VisibleForTesting + public static String getHeaderValue(PrnfbHeader header) { + return header.getValue(); + } + + public static UrlInvoker urlInvoker() { + return new UrlInvoker(); + } + + private ClientKeyStore clientKeyStore; + private final List headers = newArrayList(); + private HTTP_METHOD method = GET; + private Optional postContent = absent(); + private Optional proxyHost = absent(); + private Optional proxyPassword = absent(); + private Optional proxyPort = absent(); + private Optional proxyUser = absent(); + private HttpResponse response; + + private boolean shouldAcceptAnyCertificate; + + private String urlParam; + + UrlInvoker() {} + + public UrlInvoker appendBasicAuth(PrnfbNotification notification) { + if (notification.getUser().isPresent() && notification.getPassword().isPresent()) { + final String userpass = notification.getUser().get() + ":" + notification.getPassword().get(); + final String basicAuth = "Basic " + new String(printBase64Binary(userpass.getBytes(UTF_8))); + withHeader(AUTHORIZATION, basicAuth); + } + return this; + } + + public ClientKeyStore getClientKeyStore() { + return this.clientKeyStore; + } + + public List getHeaders() { + return this.headers; + } + + public HTTP_METHOD getMethod() { + return this.method; + } + + public Optional getPostContent() { + return this.postContent; + } + + public Optional getProxyHost() { + return this.proxyHost; + } + + public Optional getProxyPassword() { + return this.proxyPassword; + } + + public Optional getProxyPort() { + return this.proxyPort; + } + + public Optional getProxyUser() { + return this.proxyUser; + } + + public HttpResponse getResponse() { + return this.response; + } + + public InputStream getResponseStringStream() { + return new ByteArrayInputStream(getResponse().getContent().getBytes(UTF_8)); + } + + public String getUrlParam() { + return this.urlParam; + } + + public HttpResponse invoke() { + LOG.info("Url: \"" + this.urlParam + "\""); + + HttpRequestBase httpRequestBase = newHttpRequestBase(); + configureUrl(httpRequestBase); + addHeaders(httpRequestBase); + + HttpClientBuilder builder = HttpClientBuilder.create(); + configureSsl(builder); + configureProxy(builder); + + this.response = doInvoke(httpRequestBase, builder); + if (LOG.isDebugEnabled()) { + if (this.response != null) { + LOG.debug(this.response.getContent()); + } + } + + return this.response; + } + + public void setResponse(HttpResponse response) { + this.response = response; + } + + @VisibleForTesting + public boolean shouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; + } + + public UrlInvoker shouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { + this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; + return this; + } - private static final Logger LOG = getLogger(UrlInvoker.class); + @VisibleForTesting + public boolean shouldAuthenticateProxy() { + return getProxyUser().isPresent() && getProxyPassword().isPresent(); + } + + @VisibleForTesting + public boolean shouldPostContent() { + return (this.method == POST || this.method == PUT) && this.postContent.isPresent(); + } + + @VisibleForTesting + public boolean shouldUseProxy() { + return getProxyHost().isPresent() && getProxyPort().isPresent() && getProxyPort().get() > 0; + } + + public UrlInvoker withClientKeyStore(ClientKeyStore clientKeyStore) { + this.clientKeyStore = clientKeyStore; + return this; + } + + public UrlInvoker withHeader(String name, String value) { + this.headers.add(new PrnfbHeader(name, value)); + return this; + } + + public UrlInvoker withMethod(HTTP_METHOD method) { + this.method = method; + return this; + } + + public UrlInvoker withPostContent(Optional postContent) { + this.postContent = postContent; + return this; + } + + public UrlInvoker withProxyPassword(Optional proxyPassword) { + this.proxyPassword = proxyPassword; + return this; + } + + public UrlInvoker withProxyPort(Integer proxyPort) { + this.proxyPort = fromNullable(proxyPort); + return this; + } + + public UrlInvoker withProxyServer(Optional proxyHost) { + this.proxyHost = proxyHost; + return this; + } + + public UrlInvoker withProxyUser(Optional proxyUser) { + this.proxyUser = proxyUser; + return this; + } + + public UrlInvoker withUrlParam(String urlParam) { + this.urlParam = urlParam.replaceAll("\\s", "%20"); + return this; + } + + private void addHeaders(HttpRequestBase httpRequestBase) { + for (PrnfbHeader header : this.headers) { - @VisibleForTesting - public static String getHeaderValue(PrnfbHeader header) { - return header.getValue(); - } + if (header.getName().equals(AUTHORIZATION)) { + LOG.debug("header: \"" + header.getName() + "\" value: \"**********\""); + } else { + LOG.debug("header: \"" + header.getName() + "\" value: \"" + header.getValue() + "\""); + } - public static UrlInvoker urlInvoker() { - return new UrlInvoker(); - } + httpRequestBase.addHeader(header.getName(), getHeaderValue(header)); + } + } + + private void configureUrl(HttpRequestBase httpRequestBase) { + try { + httpRequestBase.setURI(new URI(this.urlParam)); + } catch (URISyntaxException e) { + propagate(e); + } + } + + private SSLContextBuilder doAcceptAnyCertificate(SSLContextBuilder customContext) + throws Exception { + TrustStrategy easyStrategy = + new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] chain, String authType) { + return true; + } + }; + customContext = customContext.loadTrustMaterial(null, easyStrategy); + + return customContext; + } + + private SSLContext newSslContext() throws Exception { + SSLContextBuilder sslContextBuilder = SSLContexts.custom(); + if (this.shouldAcceptAnyCertificate) { + doAcceptAnyCertificate(sslContextBuilder); + if (this.clientKeyStore.getKeyStore().isPresent()) { + sslContextBuilder.loadKeyMaterial( + this.clientKeyStore.getKeyStore().get(), this.clientKeyStore.getPassword()); + } + } + + return sslContextBuilder.build(); + } + + private boolean shouldUseSsl() { + return this.urlParam.startsWith("https"); + } - private ClientKeyStore clientKeyStore; - private final List headers = newArrayList(); - private HTTP_METHOD method = GET; - private Optional postContent = absent(); - private Optional proxyHost = absent(); - private Optional proxyPassword = absent(); - private Optional proxyPort = absent(); - private Optional proxyUser = absent(); - private HttpResponse response; + @VisibleForTesting + HttpClientBuilder configureProxy(HttpClientBuilder builder) { + if (!shouldUseProxy()) { + return builder; + } - private boolean shouldAcceptAnyCertificate; + if (this.proxyUser.isPresent() && this.proxyPassword.isPresent()) { + String username = this.proxyUser.get(); + String password = this.proxyPassword.get(); + UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials( + new AuthScope(this.proxyHost.get(), this.proxyPort.get()), creds); + builder.setDefaultCredentialsProvider(credsProvider); + } - private String urlParam; + builder.useSystemProperties(); + builder.setProxy(new HttpHost(this.proxyHost.get(), this.proxyPort.get())); + builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); + return builder; + } - UrlInvoker() { - } + @VisibleForTesting + HttpClientBuilder configureSsl(HttpClientBuilder builder) { + if (shouldUseSsl()) { + try { + SSLContext s = newSslContext(); + SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(s); + builder.setSSLSocketFactory(sslConnSocketFactory); + + Registry registry = + RegistryBuilder.create() + .register("https", sslConnSocketFactory) + .build(); + + HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); + + builder.setConnectionManager(ccm); + } catch (Exception e) { + propagate(e); + } + } + return builder; + } - public UrlInvoker appendBasicAuth(PrnfbNotification notification) { - if (notification.getUser().isPresent() && notification.getPassword().isPresent()) { - final String userpass = notification.getUser().get() + ":" + notification.getPassword().get(); - final String basicAuth = "Basic " + new String(printBase64Binary(userpass.getBytes(UTF_8))); - withHeader(AUTHORIZATION, basicAuth); + @VisibleForTesting + HttpResponse doInvoke(HttpRequestBase httpRequestBase, HttpClientBuilder builder) { + CloseableHttpResponse httpResponse = null; + try { + httpResponse = + builder // + .build() // + .execute(httpRequestBase); + + HttpEntity entity = httpResponse.getEntity(); + return new HttpResponse( + httpRequestBase.getURI(), + httpResponse.getStatusLine().getStatusCode(), + EntityUtils.toString(entity, UTF_8)); + } catch (final Exception e) { + LOG.error("", e); + } finally { + try { + if (httpResponse != null) { + httpResponse.close(); + } + } catch (IOException e) { + propagate(e); + } + } + return null; } - return this; - } - public ClientKeyStore getClientKeyStore() { - return this.clientKeyStore; - } + @VisibleForTesting + HttpEntityEnclosingRequestBase newHttpEntityEnclosingRequestBase( + HTTP_METHOD method, String entity) { + HttpEntityEnclosingRequestBase entityEnclosing = + new HttpEntityEnclosingRequestBase() { + @Override + public String getMethod() { + return method.name(); + } + }; + if (entity != null) { + entityEnclosing.setEntity(new ByteArrayEntity(entity.getBytes())); + } + return entityEnclosing; + } - public List getHeaders() { - return this.headers; - } - - public HTTP_METHOD getMethod() { - return this.method; - } - - public Optional getPostContent() { - return this.postContent; - } - - public Optional getProxyHost() { - return this.proxyHost; - } - - public Optional getProxyPassword() { - return this.proxyPassword; - } - - public Optional getProxyPort() { - return this.proxyPort; - } - - public Optional getProxyUser() { - return this.proxyUser; - } - - public HttpResponse getResponse() { - return this.response; - } - - public InputStream getResponseStringStream() { - return new ByteArrayInputStream(getResponse().getContent().getBytes(UTF_8)); - } - - public String getUrlParam() { - return this.urlParam; - } - - public HttpResponse invoke() { - LOG.info("Url: \"" + this.urlParam + "\""); - - HttpRequestBase httpRequestBase = newHttpRequestBase(); - configureUrl(httpRequestBase); - addHeaders(httpRequestBase); - - HttpClientBuilder builder = HttpClientBuilder.create(); - configureSsl(builder); - configureProxy(builder); - - this.response = doInvoke(httpRequestBase, builder); - if (LOG.isDebugEnabled()) { - if (this.response != null) { - LOG.debug(this.response.getContent()); - } - } - - return this.response; - } - - public void setResponse(HttpResponse response) { - this.response = response; - } - - @VisibleForTesting - public boolean shouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } - - public UrlInvoker shouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { - this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; - return this; - } - - @VisibleForTesting - public boolean shouldAuthenticateProxy() { - return getProxyUser().isPresent() && getProxyPassword().isPresent(); - } - - @VisibleForTesting - public boolean shouldPostContent() { - return (this.method == POST || this.method == PUT) && this.postContent.isPresent(); - } - - @VisibleForTesting - public boolean shouldUseProxy() { - return getProxyHost().isPresent() && getProxyPort().isPresent() && getProxyPort().get() > 0; - } - - public UrlInvoker withClientKeyStore(ClientKeyStore clientKeyStore) { - this.clientKeyStore = clientKeyStore; - return this; - } - - public UrlInvoker withHeader(String name, String value) { - this.headers.add(new PrnfbHeader(name, value)); - return this; - } - - public UrlInvoker withMethod(HTTP_METHOD method) { - this.method = method; - return this; - } - - public UrlInvoker withPostContent(Optional postContent) { - this.postContent = postContent; - return this; - } - - public UrlInvoker withProxyPassword(Optional proxyPassword) { - this.proxyPassword = proxyPassword; - return this; - } - - public UrlInvoker withProxyPort(Integer proxyPort) { - this.proxyPort = fromNullable(proxyPort); - return this; - } - - public UrlInvoker withProxyServer(Optional proxyHost) { - this.proxyHost = proxyHost; - return this; - } - - public UrlInvoker withProxyUser(Optional proxyUser) { - this.proxyUser = proxyUser; - return this; - } - - public UrlInvoker withUrlParam(String urlParam) { - this.urlParam = urlParam.replaceAll("\\s", "%20"); - return this; - } - - private void addHeaders(HttpRequestBase httpRequestBase) { - for (PrnfbHeader header : this.headers) { - - if (header.getName().equals(AUTHORIZATION)) { - LOG.debug("header: \"" + header.getName() + "\" value: \"**********\""); - } else { - LOG.debug("header: \"" + header.getName() + "\" value: \"" + header.getValue() + "\""); - } - - httpRequestBase.addHeader(header.getName(), getHeaderValue(header)); - } - } - - private void configureUrl(HttpRequestBase httpRequestBase) { - try { - httpRequestBase.setURI(new URI(this.urlParam)); - } catch (URISyntaxException e) { - propagate(e); - } - } - - private SSLContextBuilder doAcceptAnyCertificate(SSLContextBuilder customContext) throws Exception { - TrustStrategy easyStrategy = new TrustStrategy() { - @Override - public boolean isTrusted(X509Certificate[] chain, String authType) { - return true; - } - }; - customContext = customContext.loadTrustMaterial(null, easyStrategy); - - return customContext; - } - - private SSLContext newSslContext() throws Exception { - SSLContextBuilder sslContextBuilder = SSLContexts.custom(); - if (this.shouldAcceptAnyCertificate) { - doAcceptAnyCertificate(sslContextBuilder); - if (this.clientKeyStore.getKeyStore().isPresent()) { - sslContextBuilder.loadKeyMaterial(this.clientKeyStore.getKeyStore().get(), this.clientKeyStore.getPassword()); - } - } - - return sslContextBuilder.build(); - } - - private boolean shouldUseSsl() { - return this.urlParam.startsWith("https"); - } - - @VisibleForTesting - HttpClientBuilder configureProxy(HttpClientBuilder builder) { - if (!shouldUseProxy()) { - return builder; - } - - if (this.proxyUser.isPresent() && this.proxyPassword.isPresent()) { - String username = this.proxyUser.get(); - String password = this.proxyPassword.get(); - UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(this.proxyHost.get(), this.proxyPort.get()), creds); - builder.setDefaultCredentialsProvider(credsProvider); - } - - builder.useSystemProperties(); - builder.setProxy(new HttpHost(this.proxyHost.get(), this.proxyPort.get())); - builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); - return builder; - } - - @VisibleForTesting - HttpClientBuilder configureSsl(HttpClientBuilder builder) { - if (shouldUseSsl()) { - try { - SSLContext s = newSslContext(); - SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(s); - builder.setSSLSocketFactory(sslConnSocketFactory); - - Registry registry = RegistryBuilder.create() - .register("https", sslConnSocketFactory).build(); - - HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); - - builder.setConnectionManager(ccm); - } catch (Exception e) { - propagate(e); - } - } - return builder; - } - - @VisibleForTesting - HttpResponse doInvoke(HttpRequestBase httpRequestBase, HttpClientBuilder builder) { - CloseableHttpResponse httpResponse = null; - try { - httpResponse = builder// - .build()// - .execute(httpRequestBase); - - HttpEntity entity = httpResponse.getEntity(); - return new HttpResponse(httpRequestBase.getURI(), httpResponse.getStatusLine().getStatusCode(), - EntityUtils.toString(entity, UTF_8)); - } catch (final Exception e) { - LOG.error("", e); - } finally { - try { - if (httpResponse != null) { - httpResponse.close(); + @VisibleForTesting + HttpRequestBase newHttpRequestBase() { + if (shouldPostContent()) { + return newHttpEntityEnclosingRequestBase(this.method, this.postContent.get()); } - } catch (IOException e) { - propagate(e); - } - } - return null; - } - - @VisibleForTesting - HttpEntityEnclosingRequestBase newHttpEntityEnclosingRequestBase(HTTP_METHOD method, String entity) { - HttpEntityEnclosingRequestBase entityEnclosing = new HttpEntityEnclosingRequestBase() { - @Override - public String getMethod() { - return method.name(); - } - }; - if (entity != null) { - entityEnclosing.setEntity(new ByteArrayEntity(entity.getBytes())); - } - return entityEnclosing; - } - - @VisibleForTesting - HttpRequestBase newHttpRequestBase() { - if (shouldPostContent()) { - return newHttpEntityEnclosingRequestBase(this.method, this.postContent.get()); - } - return newHttpRequestBase(this.method); - } - - @VisibleForTesting - HttpRequestBase newHttpRequestBase(HTTP_METHOD method) { - return new HttpRequestBase() { - @Override - public String getMethod() { - return method.name(); - } - }; - } + return newHttpRequestBase(this.method); + } + + @VisibleForTesting + HttpRequestBase newHttpRequestBase(HTTP_METHOD method) { + return new HttpRequestBase() { + @Override + public String getMethod() { + return method.name(); + } + }; + } } diff --git a/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestAction.java b/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestAction.java index bd7d89c4..7135f44f 100644 --- a/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestAction.java +++ b/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestAction.java @@ -6,39 +6,43 @@ import com.atlassian.bitbucket.event.pull.PullRequestRescopedEvent; public enum PrnfbPullRequestAction { + APPROVED, // + BUTTON_TRIGGER, // + COMMENTED, // + DECLINED, // + MERGED, // + OPENED, // + REOPENED, // + RESCOPED, // + RESCOPED_FROM, // + RESCOPED_TO, // + UNAPPROVED, // + UPDATED; - APPROVED, // - BUTTON_TRIGGER, // - COMMENTED, // - DECLINED, // - MERGED, // - OPENED, // - REOPENED, // - RESCOPED, // - RESCOPED_FROM, // - RESCOPED_TO, // - UNAPPROVED, // - UPDATED; - - public static PrnfbPullRequestAction fromPullRequestEvent(PullRequestEvent event, PrnfbNotification notification) { - if (event instanceof PullRequestRescopedEvent) { - PullRequestRescopedEvent rescopedEvent = (PullRequestRescopedEvent) event; - boolean toChanged = !rescopedEvent.getPreviousToHash() - .equals(rescopedEvent.getPullRequest().getToRef().getLatestCommit()); - boolean fromChanged = !rescopedEvent.getPreviousFromHash() - .equals(rescopedEvent.getPullRequest().getFromRef().getLatestCommit()); - if (fromChanged && !toChanged) { - return RESCOPED_FROM; - } else if (toChanged && !fromChanged) { - return RESCOPED_TO; - } else { - if (notification.getTriggers().contains(RESCOPED_FROM)) { - return RESCOPED_FROM; - } else if (notification.getTriggers().contains(RESCOPED_TO)) { - return RESCOPED_TO; + public static PrnfbPullRequestAction fromPullRequestEvent( + PullRequestEvent event, PrnfbNotification notification) { + if (event instanceof PullRequestRescopedEvent) { + PullRequestRescopedEvent rescopedEvent = (PullRequestRescopedEvent) event; + boolean toChanged = + !rescopedEvent + .getPreviousToHash() + .equals(rescopedEvent.getPullRequest().getToRef().getLatestCommit()); + boolean fromChanged = + !rescopedEvent + .getPreviousFromHash() + .equals(rescopedEvent.getPullRequest().getFromRef().getLatestCommit()); + if (fromChanged && !toChanged) { + return RESCOPED_FROM; + } else if (toChanged && !fromChanged) { + return RESCOPED_TO; + } else { + if (notification.getTriggers().contains(RESCOPED_FROM)) { + return RESCOPED_FROM; + } else if (notification.getTriggers().contains(RESCOPED_TO)) { + return RESCOPED_TO; + } + } } - } + return PrnfbPullRequestAction.valueOf(event.getAction().name()); } - return PrnfbPullRequestAction.valueOf(event.getAction().name()); - } } diff --git a/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestEventListener.java b/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestEventListener.java index eb1be6ee..2bd8d9d0 100644 --- a/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestEventListener.java +++ b/src/main/java/se/bjurr/prnfb/listener/PrnfbPullRequestEventListener.java @@ -48,6 +48,7 @@ import se.bjurr.prnfb.http.NotificationResponse; import se.bjurr.prnfb.http.UrlInvoker; import se.bjurr.prnfb.service.PrnfbRenderer; +import se.bjurr.prnfb.service.PrnfbRenderer.ENCODE_FOR; import se.bjurr.prnfb.service.PrnfbRendererFactory; import se.bjurr.prnfb.service.PrnfbVariable; import se.bjurr.prnfb.service.SettingsService; @@ -58,232 +59,303 @@ public class PrnfbPullRequestEventListener { - private static final Logger LOG = getLogger(PrnfbPullRequestEventListener.class); - private static Invoker mockedInvoker = null; + private static final Logger LOG = getLogger(PrnfbPullRequestEventListener.class); + private static Invoker mockedInvoker = null; - @VisibleForTesting - public static void setInvoker(Invoker invoker) { - PrnfbPullRequestEventListener.mockedInvoker = invoker; - } + @VisibleForTesting + public static void setInvoker(Invoker invoker) { + PrnfbPullRequestEventListener.mockedInvoker = invoker; + } + + private final ExecutorService executorService; + private final PrnfbRendererFactory prnfbRendererFactory; + private final PullRequestService pullRequestService; + + private final SettingsService settingsService; + + public PrnfbPullRequestEventListener( + PrnfbRendererFactory prnfbRendererFactory, + PullRequestService pullRequestService, + ExecutorService executorService, + SettingsService settingsService) { + this.prnfbRendererFactory = prnfbRendererFactory; + this.pullRequestService = pullRequestService; + this.executorService = executorService; + this.settingsService = settingsService; + } + + private Invoker createInvoker() { + if (mockedInvoker != null) { + return mockedInvoker; + } + return new Invoker() { + @Override + public HttpResponse invoke(UrlInvoker urlInvoker) { + return urlInvoker.invoke(); + } + }; + } + + private void handleEvent(final PullRequestEvent pullRequestEvent) { + if (pullRequestEvent.getPullRequest().isClosed() + && pullRequestEvent instanceof PullRequestCommentEvent) { + return; + } + final PrnfbSettingsData settings = settingsService.getPrnfbSettingsData(); + ClientKeyStore clientKeyStore = new ClientKeyStore(settings); + for (final PrnfbNotification notification : settingsService.getNotifications()) { + PrnfbPullRequestAction action = fromPullRequestEvent(pullRequestEvent, notification); + Map> variables = populateVariables(pullRequestEvent); + PrnfbRenderer renderer = + prnfbRendererFactory.create( + pullRequestEvent.getPullRequest(), + action, + notification, + variables, + pullRequestEvent.getUser()); + notify( + notification, + action, + pullRequestEvent.getPullRequest(), + renderer, + clientKeyStore, + settings.isShouldAcceptAnyCertificate()); + } + } + + @VisibleForTesting + public void handleEventAsync(final PullRequestEvent pullRequestEvent) { + executorService.execute( + new Runnable() { + @Override + public void run() { + handleEvent(pullRequestEvent); + } + }); + } + + @VisibleForTesting + boolean ignoreBecauseOfConflicting(TRIGGER_IF_MERGE triggerIfCanMerge, boolean isConflicted) { + return triggerIfCanMerge == NOT_CONFLICTING && isConflicted + || // + triggerIfCanMerge == CONFLICTING && !isConflicted; + } + + public boolean isNotificationTriggeredByAction( + PrnfbNotification notification, + PrnfbPullRequestAction pullRequestAction, + PrnfbRenderer renderer, + PullRequest pullRequest, + ClientKeyStore clientKeyStore, + Boolean shouldAcceptAnyCertificate) { + if (!notification.getTriggers().contains(pullRequestAction)) { + return FALSE; + } + + if (notification.getProjectKey().isPresent()) { + if (!notification + .getProjectKey() + .get() + .equals(pullRequest.getToRef().getRepository().getProject().getKey())) { + return FALSE; + } + } - private final ExecutorService executorService; - private final PrnfbRendererFactory prnfbRendererFactory; - private final PullRequestService pullRequestService; + if (notification.getRepositorySlug().isPresent()) { + if (!notification + .getRepositorySlug() + .get() + .equals(pullRequest.getToRef().getRepository().getSlug())) { + return FALSE; + } + } - private final SettingsService settingsService; + if (notification.getFilterRegexp().isPresent() + && notification.getFilterString().isPresent() + && !compile(notification.getFilterRegexp().get()) + .matcher( + renderer.render( + notification.getFilterString().get(), + ENCODE_FOR.NONE, + clientKeyStore, + shouldAcceptAnyCertificate)) + .find()) { + return FALSE; + } - public PrnfbPullRequestEventListener(PrnfbRendererFactory prnfbRendererFactory, PullRequestService pullRequestService, - ExecutorService executorService, SettingsService settingsService) { - this.prnfbRendererFactory = prnfbRendererFactory; - this.pullRequestService = pullRequestService; - this.executorService = executorService; - this.settingsService = settingsService; - } + if (notification.getTriggerIgnoreStateList().contains(pullRequest.getState())) { + return FALSE; + } + + if (notification.getTriggerIfCanMerge() != ALWAYS && pullRequest.isOpen()) { + // Cannot perform canMerge unless PR is open + boolean isConflicted = + pullRequestService + .canMerge(pullRequest.getToRef().getRepository().getId(), pullRequest.getId()) + .isConflicted(); + if (ignoreBecauseOfConflicting(notification.getTriggerIfCanMerge(), isConflicted)) { + return FALSE; + } + } + + return TRUE; + } + + public NotificationResponse notify( + final PrnfbNotification notification, + PrnfbPullRequestAction pullRequestAction, + PullRequest pullRequest, + PrnfbRenderer renderer, + ClientKeyStore clientKeyStore, + Boolean shouldAcceptAnyCertificate) { + if (!isNotificationTriggeredByAction( + notification, + pullRequestAction, + renderer, + pullRequest, + clientKeyStore, + shouldAcceptAnyCertificate)) { + return null; + } - private Invoker createInvoker() { - if (mockedInvoker != null) { - return mockedInvoker; + Optional postContent = absent(); + if (notification.getPostContent().isPresent()) { + postContent = + of( + renderer.render( + notification.getPostContent().get(), + ENCODE_FOR.NONE, + clientKeyStore, + shouldAcceptAnyCertificate)); + } + String renderedUrl = + renderer.render( + notification.getUrl(), ENCODE_FOR.URL, clientKeyStore, shouldAcceptAnyCertificate); + LOG.info( + notification.getName() + + " > " // + + pullRequest.getFromRef().getId() + + "(" + + pullRequest.getFromRef().getLatestCommit() + + ") -> " // + + pullRequest.getToRef().getId() + + "(" + + pullRequest.getToRef().getLatestCommit() + + ")" + + " " // + + renderedUrl); + UrlInvoker urlInvoker = + urlInvoker() // + .withClientKeyStore(clientKeyStore) // + .withUrlParam(renderedUrl) // + .withMethod(notification.getMethod()) // + .withPostContent(postContent) // + .appendBasicAuth(notification); + for (PrnfbHeader header : notification.getHeaders()) { + urlInvoker // + .withHeader( + header.getName(), + renderer.render( + header.getValue(), ENCODE_FOR.NONE, clientKeyStore, shouldAcceptAnyCertificate)); + } + HttpResponse httpResponse = + createInvoker() + .invoke( + urlInvoker // + .withProxyServer(notification.getProxyServer()) // + .withProxyPort(notification.getProxyPort()) // + .withProxyUser(notification.getProxyUser()) // + .withProxyPassword(notification.getProxyPassword()) // + .shouldAcceptAnyCertificate(shouldAcceptAnyCertificate)); + + return new NotificationResponse(notification.getUuid(), notification.getName(), httpResponse); } - return new Invoker() { - @Override - public HttpResponse invoke(UrlInvoker urlInvoker) { - return urlInvoker.invoke(); - } - }; - } - - private void handleEvent(final PullRequestEvent pullRequestEvent) { - if (pullRequestEvent.getPullRequest().isClosed() && pullRequestEvent instanceof PullRequestCommentEvent) { - return; + + @EventListener + public void onEvent(@SuppressWarnings("deprecation") PullRequestApprovedEvent e) { + handleEventAsync(e); } - final PrnfbSettingsData settings = settingsService.getPrnfbSettingsData(); - ClientKeyStore clientKeyStore = new ClientKeyStore(settings); - for (final PrnfbNotification notification : settingsService.getNotifications()) { - PrnfbPullRequestAction action = fromPullRequestEvent(pullRequestEvent, notification); - Map> variables = populateVariables(pullRequestEvent); - PrnfbRenderer renderer = prnfbRendererFactory.create(pullRequestEvent.getPullRequest(), action, notification, - variables, pullRequestEvent.getUser()); - notify(notification, action, pullRequestEvent.getPullRequest(), renderer, clientKeyStore, - settings.isShouldAcceptAnyCertificate()); + + @EventListener + public void onEvent(PullRequestCommentAddedEvent e) { + handleEventAsync(e); } - } - - @VisibleForTesting - public void handleEventAsync(final PullRequestEvent pullRequestEvent) { - executorService.execute(new Runnable() { - @Override - public void run() { - handleEvent(pullRequestEvent); - } - }); - } - - @VisibleForTesting - boolean ignoreBecauseOfConflicting(TRIGGER_IF_MERGE triggerIfCanMerge, boolean isConflicted) { - return triggerIfCanMerge == NOT_CONFLICTING && isConflicted || // - triggerIfCanMerge == CONFLICTING && !isConflicted; - } - - public boolean isNotificationTriggeredByAction(PrnfbNotification notification, - PrnfbPullRequestAction pullRequestAction, PrnfbRenderer renderer, PullRequest pullRequest, - ClientKeyStore clientKeyStore, Boolean shouldAcceptAnyCertificate) { - if (!notification.getTriggers().contains(pullRequestAction)) { - return FALSE; + + @EventListener + public void onEvent(PullRequestCommentDeletedEvent e) { + handleEventAsync(e); } - if (notification.getProjectKey().isPresent()) { - if (!notification.getProjectKey().get().equals(pullRequest.getToRef().getRepository().getProject().getKey())) { - return FALSE; - } + @EventListener + public void onEvent(PullRequestCommentEditedEvent e) { + handleEventAsync(e); } - if (notification.getRepositorySlug().isPresent()) { - if (!notification.getRepositorySlug().get().equals(pullRequest.getToRef().getRepository().getSlug())) { - return FALSE; - } + @EventListener + public void onEvent(PullRequestCommentRepliedEvent e) { + handleEventAsync(e); } - if (notification.getFilterRegexp().isPresent() && notification.getFilterString().isPresent() - && !compile(notification.getFilterRegexp().get()) - .matcher(renderer.render(notification.getFilterString().get(), FALSE, FALSE, clientKeyStore, shouldAcceptAnyCertificate)) - .find()) { - return FALSE; + @EventListener + public void onEvent(PullRequestDeclinedEvent e) { + handleEventAsync(e); } - if (notification.getTriggerIgnoreStateList().contains(pullRequest.getState())) { - return FALSE; + @EventListener + public void onEvent(PullRequestMergedEvent e) { + handleEventAsync(e); } - if (notification.getTriggerIfCanMerge() != ALWAYS && pullRequest.isOpen()) { - // Cannot perform canMerge unless PR is open - boolean isConflicted = pullRequestService - .canMerge(pullRequest.getToRef().getRepository().getId(), pullRequest.getId()).isConflicted(); - if (ignoreBecauseOfConflicting(notification.getTriggerIfCanMerge(), isConflicted)) { - return FALSE; - } + @EventListener + public void onEvent(PullRequestOpenedEvent e) { + handleEventAsync(e); } - return TRUE; - } + @EventListener + public void onEvent(PullRequestReopenedEvent e) { + handleEventAsync(e); + } - public NotificationResponse notify(final PrnfbNotification notification, PrnfbPullRequestAction pullRequestAction, - PullRequest pullRequest, PrnfbRenderer renderer, ClientKeyStore clientKeyStore, Boolean shouldAcceptAnyCertificate) { - if (!isNotificationTriggeredByAction(notification, pullRequestAction, renderer, pullRequest, clientKeyStore, - shouldAcceptAnyCertificate)) { - return null; + @EventListener + public void onEvent(final PullRequestRescopedEvent e) { + handleEventAsync(e); } - Optional postContent = absent(); - if (notification.getPostContent().isPresent()) { - postContent = of( - renderer.render(notification.getPostContent().get(), FALSE, FALSE, clientKeyStore, shouldAcceptAnyCertificate)); + @EventListener + public void onEvent(@SuppressWarnings("deprecation") PullRequestUnapprovedEvent e) { + handleEventAsync(e); } - String renderedUrl = renderer.render(notification.getUrl(), TRUE, FALSE, clientKeyStore, shouldAcceptAnyCertificate); - LOG.info(notification.getName() + " > " // - + pullRequest.getFromRef().getId() + "(" + pullRequest.getFromRef().getLatestCommit() + ") -> " // - + pullRequest.getToRef().getId() + "(" + pullRequest.getToRef().getLatestCommit() + ")" + " " // - + renderedUrl); - UrlInvoker urlInvoker = urlInvoker()// - .withClientKeyStore(clientKeyStore)// - .withUrlParam(renderedUrl)// - .withMethod(notification.getMethod())// - .withPostContent(postContent)// - .appendBasicAuth(notification); - for (PrnfbHeader header : notification.getHeaders()) { - urlInvoker// - .withHeader(header.getName(), - renderer.render(header.getValue(), FALSE, FALSE, clientKeyStore, shouldAcceptAnyCertificate)); + + @EventListener + public void onEvent(PullRequestUpdatedEvent e) { + handleEventAsync(e); } - HttpResponse httpResponse = createInvoker().invoke(urlInvoker// - .withProxyServer(notification.getProxyServer()) // - .withProxyPort(notification.getProxyPort())// - .withProxyUser(notification.getProxyUser())// - .withProxyPassword(notification.getProxyPassword())// - .shouldAcceptAnyCertificate(shouldAcceptAnyCertificate)); - - return new NotificationResponse(notification.getUuid(), notification.getName(), httpResponse); - } - - @EventListener - public void onEvent(@SuppressWarnings("deprecation") PullRequestApprovedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestCommentAddedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestCommentDeletedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestCommentEditedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestCommentRepliedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestDeclinedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestMergedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestOpenedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestReopenedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(final PullRequestRescopedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(@SuppressWarnings("deprecation") PullRequestUnapprovedEvent e) { - handleEventAsync(e); - } - - @EventListener - public void onEvent(PullRequestUpdatedEvent e) { - handleEventAsync(e); - } - - @VisibleForTesting - Map> populateVariables(final PullRequestEvent pullRequestEvent) { - Map> variables = newHashMap(); - if (pullRequestEvent instanceof PullRequestCommentEvent) { - PullRequestCommentEvent pullRequestCommentEvent = (PullRequestCommentEvent) pullRequestEvent; - variables.put(PULL_REQUEST_COMMENT_TEXT, () -> { - return pullRequestCommentEvent.getComment().getText(); - }); - variables.put(PULL_REQUEST_COMMENT_ACTION, () -> { - return pullRequestCommentEvent.getCommentAction().name(); - }); - } else if (pullRequestEvent instanceof PullRequestMergedEvent) { - variables.put(PULL_REQUEST_MERGE_COMMIT, new Supplier() { - @Override - public String get() { - return ((PullRequestMergedEvent) pullRequestEvent).getCommit().getId(); + + @VisibleForTesting + Map> populateVariables(final PullRequestEvent pullRequestEvent) { + Map> variables = newHashMap(); + if (pullRequestEvent instanceof PullRequestCommentEvent) { + PullRequestCommentEvent pullRequestCommentEvent = (PullRequestCommentEvent) pullRequestEvent; + variables.put( + PULL_REQUEST_COMMENT_TEXT, + () -> { + return pullRequestCommentEvent.getComment().getText(); + }); + variables.put( + PULL_REQUEST_COMMENT_ACTION, + () -> { + return pullRequestCommentEvent.getCommentAction().name(); + }); + } else if (pullRequestEvent instanceof PullRequestMergedEvent) { + variables.put( + PULL_REQUEST_MERGE_COMMIT, + new Supplier() { + @Override + public String get() { + return ((PullRequestMergedEvent) pullRequestEvent).getCommit().getId(); + } + }); } - }); + return variables; } - return variables; - } - -} \ No newline at end of file +} diff --git a/src/main/java/se/bjurr/prnfb/presentation/ButtonServlet.java b/src/main/java/se/bjurr/prnfb/presentation/ButtonServlet.java index d194dac7..f04c45d9 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/ButtonServlet.java +++ b/src/main/java/se/bjurr/prnfb/presentation/ButtonServlet.java @@ -25,6 +25,9 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import com.atlassian.annotations.security.XsrfProtectionExcluded; +import com.google.gson.Gson; + import se.bjurr.prnfb.http.NotificationResponse; import se.bjurr.prnfb.presentation.dto.ButtonDTO; import se.bjurr.prnfb.presentation.dto.ButtonPressDTO; @@ -33,154 +36,166 @@ import se.bjurr.prnfb.service.UserCheckService; import se.bjurr.prnfb.settings.PrnfbButton; -import com.atlassian.annotations.security.XsrfProtectionExcluded; -import com.google.gson.Gson; - @Path("/settings/buttons") public class ButtonServlet { - private final ButtonsService buttonsService; - private final SettingsService settingsService; - private final UserCheckService userCheckService; - private static final Gson gson = new Gson(); - - public ButtonServlet(ButtonsService buttonsService, SettingsService settingsService, - UserCheckService userCheckService) { - this.buttonsService = buttonsService; - this.settingsService = settingsService; - this.userCheckService = userCheckService; - } - - @POST - @XsrfProtectionExcluded - @Consumes(APPLICATION_JSON) - @Produces(APPLICATION_JSON) - public Response create(ButtonDTO buttonDto) { - if (!this.userCheckService.isAdminAllowed(// - buttonDto.getProjectKey().orNull()// - , buttonDto.getRepositorySlug().orNull())) { - return status(UNAUTHORIZED)// - .build(); - } - - if (buttonDto.getButtonForm() != null && !buttonDto.getButtonForm().isEmpty()) { - try { - gson.fromJson(buttonDto.getButtonForm(), Object.class); - } catch(com.google.gson.JsonSyntaxException ex) { - throw new Error("The form specification for the button must be a valid JSON string"); - } - } - - PrnfbButton prnfbButton = toPrnfbButton(buttonDto); - PrnfbButton created = this.settingsService.addOrUpdateButton(prnfbButton); - ButtonDTO createdDto = toButtonDto(created); - - return status(OK)// - .entity(createdDto)// - .build(); - } - - @DELETE - @Path("{uuid}") - @XsrfProtectionExcluded - @Produces(APPLICATION_JSON) - public Response delete(@PathParam("uuid") UUID prnfbButtonUuid) { - PrnfbButton prnfbButton = this.settingsService.getButton(prnfbButtonUuid); - if (!this.userCheckService.isAdminAllowed(// - prnfbButton.getProjectKey().orNull()// - , prnfbButton.getRepositorySlug().orNull())) { - return status(UNAUTHORIZED)// - .build(); + private static final Gson gson = new Gson(); + private final ButtonsService buttonsService; + private final SettingsService settingsService; + private final UserCheckService userCheckService; + + public ButtonServlet( + ButtonsService buttonsService, + SettingsService settingsService, + UserCheckService userCheckService) { + this.buttonsService = buttonsService; + this.settingsService = settingsService; + this.userCheckService = userCheckService; } - this.settingsService.deleteButton(prnfbButtonUuid); - return status(OK).build(); - } - - @GET - @Produces(APPLICATION_JSON) - public Response get() { - List buttons = this.settingsService.getButtons(); - Iterable allowedButtons = this.userCheckService.filterAllowed(buttons); - List dtos = toButtonDtoList(allowedButtons); - Collections.sort(dtos); - return ok(dtos, APPLICATION_JSON).build(); - } - - @GET - @Path("/repository/{repositoryId}/pullrequest/{pullRequestId}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("repositoryId") Integer repositoryId, @PathParam("pullRequestId") Long pullRequestId) { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + + @POST + @XsrfProtectionExcluded + @Consumes(APPLICATION_JSON) + @Produces(APPLICATION_JSON) + public Response create(ButtonDTO buttonDto) { + if (!userCheckService.isAdminAllowed( // + buttonDto.getProjectKey().orNull() // + , + buttonDto.getRepositorySlug().orNull())) { + return status(UNAUTHORIZED) // + .build(); + } + + if (buttonDto.getButtonForm() != null && !buttonDto.getButtonForm().isEmpty()) { + try { + gson.fromJson(buttonDto.getButtonForm(), Object.class); + // TODO: Replace string with a DTO + } catch (com.google.gson.JsonSyntaxException ex) { + throw new Error("The form specification for the button must be a valid JSON string"); + } + } + + PrnfbButton prnfbButton = toPrnfbButton(buttonDto); + PrnfbButton created = settingsService.addOrUpdateButton(prnfbButton); + ButtonDTO createdDto = toButtonDto(created); + + return status(OK) // + .entity(createdDto) // + .build(); } - List buttons = this.buttonsService.getButtons(repositoryId, pullRequestId); - Iterable allowedButtons = this.userCheckService.filterAllowed(buttons); - List dtos = toButtonDtoList(allowedButtons); - Collections.sort(dtos); - - for(ButtonDTO dto : dtos) { - if (dto.getButtonForm() != null) { - dto.setButtonForm(this.buttonsService.getRenderedButtonFormData(repositoryId, pullRequestId, dto.getUuid(), dto.getButtonForm())); - } + + @DELETE + @Path("{uuid}") + @XsrfProtectionExcluded + @Produces(APPLICATION_JSON) + public Response delete(@PathParam("uuid") UUID prnfbButtonUuid) { + PrnfbButton prnfbButton = settingsService.getButton(prnfbButtonUuid); + if (!userCheckService.isAdminAllowed( // + prnfbButton.getProjectKey().orNull() // + , + prnfbButton.getRepositorySlug().orNull())) { + return status(UNAUTHORIZED) // + .build(); + } + settingsService.deleteButton(prnfbButtonUuid); + return status(OK).build(); } - - return ok(dtos, APPLICATION_JSON).build(); - } - - @GET - @Path("/projectKey/{projectKey}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("projectKey") String projectKey) { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + + @GET + @Produces(APPLICATION_JSON) + public Response get() { + List buttons = settingsService.getButtons(); + Iterable allowedButtons = userCheckService.filterAllowed(buttons); + List dtos = toButtonDtoList(allowedButtons); + Collections.sort(dtos); + return ok(dtos, APPLICATION_JSON).build(); } - List buttons = this.settingsService.getButtons(projectKey); - Iterable allowedButtons = this.userCheckService.filterAllowed(buttons); - List dtos = toButtonDtoList(allowedButtons); - Collections.sort(dtos); - return ok(dtos, APPLICATION_JSON).build(); - } - - @GET - @Path("/projectKey/{projectKey}/repositorySlug/{repositorySlug}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("projectKey") String projectKey, @PathParam("repositorySlug") String repositorySlug) { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + + @GET + @Path("/repository/{repositoryId}/pullrequest/{pullRequestId}") + @Produces(APPLICATION_JSON) + public Response get( + @PathParam("repositoryId") Integer repositoryId, + @PathParam("pullRequestId") Long pullRequestId) { + if (!userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + List buttons = buttonsService.getButtons(repositoryId, pullRequestId); + Iterable allowedButtons = userCheckService.filterAllowed(buttons); + List dtos = toButtonDtoList(allowedButtons); + Collections.sort(dtos); + + for (ButtonDTO dto : dtos) { + if (dto.getButtonForm() != null) { + // TODO: After replace string with a DTO, only render the defaultType string + dto.setButtonForm( + buttonsService.getRenderedButtonFormData( + repositoryId, pullRequestId, dto.getUuid(), dto.getButtonForm())); + } + } + + return ok(dtos, APPLICATION_JSON).build(); } - List buttons = this.settingsService.getButtons(projectKey, repositorySlug); - Iterable allowedButtons = this.userCheckService.filterAllowed(buttons); - List dtos = toButtonDtoList(allowedButtons); - Collections.sort(dtos); - return ok(dtos, APPLICATION_JSON).build(); - } - - @GET - @Path("{uuid}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("uuid") UUID uuid) { - PrnfbButton button = this.settingsService.getButton(uuid); - if (!this.userCheckService.isAllowedUseButton(button)) { - return status(UNAUTHORIZED).build(); + + @GET + @Path("/projectKey/{projectKey}") + @Produces(APPLICATION_JSON) + public Response get(@PathParam("projectKey") String projectKey) { + if (!userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + List buttons = settingsService.getButtons(projectKey); + Iterable allowedButtons = userCheckService.filterAllowed(buttons); + List dtos = toButtonDtoList(allowedButtons); + Collections.sort(dtos); + return ok(dtos, APPLICATION_JSON).build(); } - ButtonDTO dto = toButtonDto(button); - return ok(dto, APPLICATION_JSON).build(); - } - - @POST - @Path("{uuid}/press/repository/{repositoryId}/pullrequest/{pullRequestId}") - @XsrfProtectionExcluded - @Produces(APPLICATION_JSON) - public Response press(@Context HttpServletRequest request, @PathParam("repositoryId") Integer repositoryId, @PathParam("pullRequestId") Long pullRequestId, - @PathParam("uuid") final UUID buttionUuid) { - String formData = request.getParameter("form"); - PrnfbButton button = this.settingsService.getButton(buttionUuid); - if (!this.userCheckService.isAllowedUseButton(button)) { - return status(UNAUTHORIZED).build(); + + @GET + @Path("/projectKey/{projectKey}/repositorySlug/{repositorySlug}") + @Produces(APPLICATION_JSON) + public Response get( + @PathParam("projectKey") String projectKey, + @PathParam("repositorySlug") String repositorySlug) { + if (!userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + List buttons = settingsService.getButtons(projectKey, repositorySlug); + Iterable allowedButtons = userCheckService.filterAllowed(buttons); + List dtos = toButtonDtoList(allowedButtons); + Collections.sort(dtos); + return ok(dtos, APPLICATION_JSON).build(); } - List results = this.buttonsService.handlePressed(repositoryId, pullRequestId, buttionUuid, formData); - ButtonPressDTO dto = toTriggerResultDto(button, results); - return ok(dto, APPLICATION_JSON).build(); - } + @GET + @Path("{uuid}") + @Produces(APPLICATION_JSON) + public Response get(@PathParam("uuid") UUID uuid) { + PrnfbButton button = settingsService.getButton(uuid); + if (!userCheckService.isAllowedUseButton(button)) { + return status(UNAUTHORIZED).build(); + } + ButtonDTO dto = toButtonDto(button); + return ok(dto, APPLICATION_JSON).build(); + } + @POST + @Path("{uuid}/press/repository/{repositoryId}/pullrequest/{pullRequestId}") + @XsrfProtectionExcluded + @Produces(APPLICATION_JSON) + public Response press( + @Context HttpServletRequest request, + @PathParam("repositoryId") Integer repositoryId, + @PathParam("pullRequestId") Long pullRequestId, + @PathParam("uuid") final UUID buttionUuid) { + PrnfbButton button = settingsService.getButton(buttionUuid); + if (!userCheckService.isAllowedUseButton(button)) { + return status(UNAUTHORIZED).build(); + } + String formData = request.getParameter("form"); + List results = + buttonsService.handlePressed(repositoryId, pullRequestId, buttionUuid, formData); + + ButtonPressDTO dto = toTriggerResultDto(button, results); + return ok(dto, APPLICATION_JSON).build(); + } } diff --git a/src/main/java/se/bjurr/prnfb/presentation/GlobalAdminServlet.java b/src/main/java/se/bjurr/prnfb/presentation/GlobalAdminServlet.java index 1ae3d2e1..7ef35849 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/GlobalAdminServlet.java +++ b/src/main/java/se/bjurr/prnfb/presentation/GlobalAdminServlet.java @@ -25,86 +25,97 @@ import com.google.common.base.Optional; public class GlobalAdminServlet extends HttpServlet { - private static final long serialVersionUID = 3846987953228399693L; - private final LoginUriProvider loginUriProvider; - private final TemplateRenderer renderer; - private final RepositoryService repositoryService; - private final UserCheckService userCheckService; - private final UserManager userManager; + private static final long serialVersionUID = 3846987953228399693L; + private final LoginUriProvider loginUriProvider; + private final TemplateRenderer renderer; + private final RepositoryService repositoryService; + private final UserCheckService userCheckService; + private final UserManager userManager; - public GlobalAdminServlet(UserManager userManager, LoginUriProvider loginUriProvider, TemplateRenderer renderer, - RepositoryService repositoryService, UserCheckService userCheckService) { - this.userManager = userManager; - this.loginUriProvider = loginUriProvider; - this.renderer = renderer; - this.repositoryService = repositoryService; - this.userCheckService = userCheckService; - } + public GlobalAdminServlet( + UserManager userManager, + LoginUriProvider loginUriProvider, + TemplateRenderer renderer, + RepositoryService repositoryService, + UserCheckService userCheckService) { + this.userManager = userManager; + this.loginUriProvider = loginUriProvider; + this.renderer = renderer; + this.repositoryService = repositoryService; + this.userCheckService = userCheckService; + } - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - UserProfile user = this.userManager.getRemoteUser(request); - if (user == null) { - response.sendRedirect(this.loginUriProvider.getLoginUri(getUri(request)).toASCIIString()); - return; - } + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) { + try { + UserProfile user = this.userManager.getRemoteUser(request); + if (user == null) { + response.sendRedirect(this.loginUriProvider.getLoginUri(getUri(request)).toASCIIString()); + return; + } - final Optional repository = getRepository(request.getPathInfo()); - boolean isSystemAdmin = this.userCheckService.isSystemAdmin(user.getUserKey()); - String projectKey = null; - String repositorySlug = null; - if (repository.isPresent()) { - projectKey = repository.get().getProject().getKey(); - repositorySlug = repository.get().getSlug(); - } - boolean isAdmin = this.userCheckService.isAdmin(user.getUserKey(), projectKey, repositorySlug); + final Optional repository = getRepository(request.getPathInfo()); + boolean isSystemAdmin = this.userCheckService.isSystemAdmin(user.getUserKey()); + String projectKey = null; + String repositorySlug = null; + if (repository.isPresent()) { + projectKey = repository.get().getProject().getKey(); + repositorySlug = repository.get().getSlug(); + } + boolean isAdmin = + this.userCheckService.isAdmin(user.getUserKey(), projectKey, repositorySlug); - Map context = newHashMap(); - if (repository.isPresent()) { - context = of( // - "repository", repository.orNull(), // - "isAdmin", isAdmin, // - "isSystemAdmin", isSystemAdmin); - } else { - context = of( // - "isAdmin", isAdmin, // - "isSystemAdmin", isSystemAdmin); - } + Map context = newHashMap(); + if (repository.isPresent()) { + context = + of( // + "repository", repository.orNull(), // + "isAdmin", isAdmin, // + "isSystemAdmin", isSystemAdmin); + } else { + context = + of( // + "isAdmin", isAdmin, // + "isSystemAdmin", isSystemAdmin); + } - response.setContentType("text/html;charset=UTF-8"); - this.renderer.render( // - "admin.vm", // - context, // - response.getWriter()); - } catch (Exception e) { - propagate(e); + response.setContentType("text/html;charset=UTF-8"); + this.renderer.render( // + "admin.vm", // + context, // + response.getWriter()); + } catch (Exception e) { + propagate(e); + } } - } - private URI getUri(HttpServletRequest request) { - StringBuffer builder = request.getRequestURL(); - if (request.getQueryString() != null) { - builder.append("?"); - builder.append(request.getQueryString()); + private URI getUri(HttpServletRequest request) { + StringBuffer builder = request.getRequestURL(); + if (request.getQueryString() != null) { + builder.append("?"); + builder.append(request.getQueryString()); + } + return URI.create(builder.toString()); } - return URI.create(builder.toString()); - } - @VisibleForTesting - Optional getRepository(String pathInfo) { - if (pathInfo == null || !pathInfo.contains("/") || pathInfo.endsWith("prnfb/admin") - || pathInfo.endsWith("prnfb/admin/")) { - return absent(); - } - String[] components = pathInfo.split("/"); - if (components.length == 0) { - return absent(); + @VisibleForTesting + Optional getRepository(String pathInfo) { + if (pathInfo == null + || !pathInfo.contains("/") + || pathInfo.endsWith("prnfb/admin") + || pathInfo.endsWith("prnfb/admin/")) { + return absent(); + } + String[] components = pathInfo.split("/"); + if (components.length == 0) { + return absent(); + } + String project = components[components.length - 2]; + String repoSlug = components[components.length - 1]; + final Repository repository = + checkNotNull( + this.repositoryService.getBySlug(project, repoSlug), // + "Did not find " + project + " " + repoSlug); + return Optional.of(repository); } - String project = components[components.length - 2]; - String repoSlug = components[components.length - 1]; - final Repository repository = checkNotNull(this.repositoryService.getBySlug(project, repoSlug), // - "Did not find " + project + " " + repoSlug); - return Optional.of(repository); - } -} \ No newline at end of file +} diff --git a/src/main/java/se/bjurr/prnfb/presentation/NotificationServlet.java b/src/main/java/se/bjurr/prnfb/presentation/NotificationServlet.java index e30fd3cf..7a774cc7 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/NotificationServlet.java +++ b/src/main/java/se/bjurr/prnfb/presentation/NotificationServlet.java @@ -32,97 +32,100 @@ @Path("/settings/notifications") public class NotificationServlet { - private final SettingsService settingsService; - private final UserCheckService userCheckService; + private final SettingsService settingsService; + private final UserCheckService userCheckService; - public NotificationServlet(SettingsService settingsService, UserCheckService userCheckService) { - this.settingsService = settingsService; - this.userCheckService = userCheckService; - } - - @POST - @XsrfProtectionExcluded - @Consumes(APPLICATION_JSON) - @Produces(APPLICATION_JSON) - public Response create(NotificationDTO notificationDto) { - if (!this.userCheckService.isAdminAllowed(notificationDto.getProjectKey(), notificationDto.getRepositorySlug())) { - return status(UNAUTHORIZED).build(); - } - try { - PrnfbNotification prnfbNotification = toPrnfbNotification(notificationDto); - PrnfbNotification created = this.settingsService.addOrUpdateNotification(prnfbNotification); - NotificationDTO createdDto = toNotificationDto(created); - return status(OK)// - .entity(createdDto)// - .build(); - } catch (Exception e) { - throw propagate(e); + public NotificationServlet(SettingsService settingsService, UserCheckService userCheckService) { + this.settingsService = settingsService; + this.userCheckService = userCheckService; } - } - @DELETE - @Path("{uuid}") - @XsrfProtectionExcluded - @Produces(APPLICATION_JSON) - public Response delete(@PathParam("uuid") UUID notification) { - PrnfbNotification notificationDto = this.settingsService.getNotification(notification); - if (!this.userCheckService.isAdminAllowed(// - notificationDto.getProjectKey().orNull(), // - notificationDto.getRepositorySlug().orNull())) { - return status(UNAUTHORIZED).build(); + @POST + @XsrfProtectionExcluded + @Consumes(APPLICATION_JSON) + @Produces(APPLICATION_JSON) + public Response create(NotificationDTO notificationDto) { + if (!this.userCheckService.isAdminAllowed( + notificationDto.getProjectKey(), notificationDto.getRepositorySlug())) { + return status(UNAUTHORIZED).build(); + } + try { + PrnfbNotification prnfbNotification = toPrnfbNotification(notificationDto); + PrnfbNotification created = this.settingsService.addOrUpdateNotification(prnfbNotification); + NotificationDTO createdDto = toNotificationDto(created); + return status(OK) // + .entity(createdDto) // + .build(); + } catch (Exception e) { + throw propagate(e); + } } - this.settingsService.deleteNotification(notification); - return status(OK).build(); - } - @GET - @Produces(APPLICATION_JSON) - public Response get() { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + @DELETE + @Path("{uuid}") + @XsrfProtectionExcluded + @Produces(APPLICATION_JSON) + public Response delete(@PathParam("uuid") UUID notification) { + PrnfbNotification notificationDto = this.settingsService.getNotification(notification); + if (!this.userCheckService.isAdminAllowed( // + notificationDto.getProjectKey().orNull(), // + notificationDto.getRepositorySlug().orNull())) { + return status(UNAUTHORIZED).build(); + } + this.settingsService.deleteNotification(notification); + return status(OK).build(); } - List notifications = this.settingsService.getNotifications(); - List dtos = toNotificationDtoList(notifications); - Collections.sort(dtos); - return ok(dtos).build(); - } - @GET - @Path("/projectKey/{projectKey}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("projectKey") String projectKey) { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + @GET + @Produces(APPLICATION_JSON) + public Response get() { + if (!this.userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + List notifications = this.settingsService.getNotifications(); + List dtos = toNotificationDtoList(notifications); + Collections.sort(dtos); + return ok(dtos).build(); } - List notifications = this.settingsService.getNotifications(projectKey); - List dtos = toNotificationDtoList(notifications); - Collections.sort(dtos); - return ok(dtos).build(); - } - @GET - @Path("/projectKey/{projectKey}/repositorySlug/{repositorySlug}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("projectKey") String projectKey, @PathParam("repositorySlug") String repositorySlug) { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + @GET + @Path("/projectKey/{projectKey}") + @Produces(APPLICATION_JSON) + public Response get(@PathParam("projectKey") String projectKey) { + if (!this.userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + List notifications = this.settingsService.getNotifications(projectKey); + List dtos = toNotificationDtoList(notifications); + Collections.sort(dtos); + return ok(dtos).build(); } - List notifications = this.settingsService.getNotifications(projectKey, repositorySlug); - List dtos = toNotificationDtoList(notifications); - Collections.sort(dtos); - return ok(dtos).build(); - } - @GET - @Path("{uuid}") - @Produces(APPLICATION_JSON) - public Response get(@PathParam("uuid") UUID notificationUuid) { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + @GET + @Path("/projectKey/{projectKey}/repositorySlug/{repositorySlug}") + @Produces(APPLICATION_JSON) + public Response get( + @PathParam("projectKey") String projectKey, + @PathParam("repositorySlug") String repositorySlug) { + if (!this.userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + List notifications = + this.settingsService.getNotifications(projectKey, repositorySlug); + List dtos = toNotificationDtoList(notifications); + Collections.sort(dtos); + return ok(dtos).build(); } - PrnfbNotification notification = this.settingsService.getNotification(notificationUuid); - NotificationDTO dto = toNotificationDto(notification); - return ok(dto).build(); - } -} \ No newline at end of file + @GET + @Path("{uuid}") + @Produces(APPLICATION_JSON) + public Response get(@PathParam("uuid") UUID notificationUuid) { + if (!this.userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } + PrnfbNotification notification = this.settingsService.getNotification(notificationUuid); + NotificationDTO dto = toNotificationDto(notification); + return ok(dto).build(); + } +} diff --git a/src/main/java/se/bjurr/prnfb/presentation/SettingsDataServlet.java b/src/main/java/se/bjurr/prnfb/presentation/SettingsDataServlet.java index 88c1b91f..b3ae43b7 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/SettingsDataServlet.java +++ b/src/main/java/se/bjurr/prnfb/presentation/SettingsDataServlet.java @@ -24,39 +24,39 @@ @Path("/settings") public class SettingsDataServlet { - private final SettingsService settingsService; - private final UserCheckService userCheckService; - - public SettingsDataServlet(UserCheckService userCheckService, SettingsService settingsService) { - this.userCheckService = userCheckService; - this.settingsService = settingsService; - } - - @GET - @Produces(APPLICATION_JSON) - public Response get() { - if (!this.userCheckService.isViewAllowed()) { - return status(UNAUTHORIZED).build(); + private final SettingsService settingsService; + private final UserCheckService userCheckService; + + public SettingsDataServlet(UserCheckService userCheckService, SettingsService settingsService) { + this.userCheckService = userCheckService; + this.settingsService = settingsService; } - PrnfbSettingsData settingsData = this.settingsService.getPrnfbSettingsData(); - SettingsDataDTO settingsDataDto = toDto(settingsData); + @GET + @Produces(APPLICATION_JSON) + public Response get() { + if (!this.userCheckService.isViewAllowed()) { + return status(UNAUTHORIZED).build(); + } - return ok(settingsDataDto).build(); - } + PrnfbSettingsData settingsData = this.settingsService.getPrnfbSettingsData(); + SettingsDataDTO settingsDataDto = toDto(settingsData); - @POST - @XsrfProtectionExcluded - @Consumes(APPLICATION_JSON) - @Produces(APPLICATION_JSON) - public Response post(SettingsDataDTO settingsDataDto) { - if (!this.userCheckService.isAdminAllowed(null, null)) { - return status(UNAUTHORIZED).build(); + return ok(settingsDataDto).build(); } - PrnfbSettingsData prnfbSettingsData = toPrnfbSettingsData(settingsDataDto); - this.settingsService.setPrnfbSettingsData(prnfbSettingsData); + @POST + @XsrfProtectionExcluded + @Consumes(APPLICATION_JSON) + @Produces(APPLICATION_JSON) + public Response post(SettingsDataDTO settingsDataDto) { + if (!this.userCheckService.isAdminAllowed(null, null)) { + return status(UNAUTHORIZED).build(); + } + + PrnfbSettingsData prnfbSettingsData = toPrnfbSettingsData(settingsDataDto); + this.settingsService.setPrnfbSettingsData(prnfbSettingsData); - return noContent().build(); - } -} \ No newline at end of file + return noContent().build(); + } +} diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonDTO.java b/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonDTO.java index c74bbcd0..017bdead 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonDTO.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonDTO.java @@ -15,157 +15,169 @@ @XmlAccessorType(FIELD) public class ButtonDTO implements Comparable { - private ON_OR_OFF confirmation; - private String name; - private String projectKey; - private String repositorySlug; - private USER_LEVEL userLevel; - private UUID uuid; - private String buttonForm; - - @Override - public int compareTo(ButtonDTO o) { - return this.name.compareTo(o.name); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ButtonDTO other = (ButtonDTO) obj; - if (this.projectKey == null) { - if (other.projectKey != null) { - return false; - } - } else if (!this.projectKey.equals(other.projectKey)) { - return false; - } - if (this.repositorySlug == null) { - if (other.repositorySlug != null) { - return false; - } - } else if (!this.repositorySlug.equals(other.repositorySlug)) { - return false; - } - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - if (this.userLevel != other.userLevel) { - return false; - } - if (this.confirmation == null) { - if (other.confirmation != null) { - return false; - } - } else if (!this.confirmation.equals(other.confirmation)) { - return false; - } - if (this.buttonForm == null) { - if (other.buttonForm != null) { - return false; - } - } else if (!this.buttonForm.equals(other.buttonForm)) { - return false; - } - if (this.uuid == null) { - if (other.uuid != null) { - return false; - } - } else if (!this.uuid.equals(other.uuid)) { - return false; - } - return true; - } - - public ON_OR_OFF getConfirmation() { - return this.confirmation; - } - - public String getName() { - return this.name; - } - - public String getButtonForm() { - return this.buttonForm; - } - - public Optional getProjectKey() { - return Optional.fromNullable(this.projectKey); - } - - public Optional getRepositorySlug() { - return Optional.fromNullable(this.repositorySlug); - } - - public USER_LEVEL getUserLevel() { - return this.userLevel; - } - - public UUID getUuid() { - return this.uuid; - } - - public UUID getUUID() { - return this.uuid; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); - result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.userLevel == null) ? 0 : this.userLevel.hashCode()); - result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); - result = prime * result + ((this.confirmation == null) ? 0 : this.confirmation.hashCode()); - result = prime * result + ((this.buttonForm == null) ? 0 : this.buttonForm.hashCode()); - return result; - } - - public void setConfirmation(ON_OR_OFF confirmation) { - this.confirmation = confirmation; - } - - public void setName(String name) { - this.name = name; - } - - public void setButtonForm(String buttonForm) { - this.buttonForm = buttonForm; - } - - public void setProjectKey(String projectKey) { - this.projectKey = projectKey; - } - - public void setRepositorySlug(String repositorySlug) { - this.repositorySlug = repositorySlug; - } - - public void setUserLevel(USER_LEVEL userLevel) { - this.userLevel = userLevel; - } - - public void setUuid(UUID uuid) { - this.uuid = uuid; - } - - @Override - public String toString() { - return "ButtonDTO [name=" + this.name + ", userLevel=" + this.userLevel + ", uuid=" + this.uuid + ", repositorySlug=" - + this.repositorySlug + ", projectKey=" + this.projectKey + ", buttonForm=" + this.buttonForm + ", confirmation=" + this.confirmation + "]"; - } + private ON_OR_OFF confirmation; + private String name; + private String projectKey; + private String repositorySlug; + private USER_LEVEL userLevel; + private UUID uuid; + private String buttonForm; + + @Override + public int compareTo(ButtonDTO o) { + return this.name.compareTo(o.name); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ButtonDTO other = (ButtonDTO) obj; + if (this.projectKey == null) { + if (other.projectKey != null) { + return false; + } + } else if (!this.projectKey.equals(other.projectKey)) { + return false; + } + if (this.repositorySlug == null) { + if (other.repositorySlug != null) { + return false; + } + } else if (!this.repositorySlug.equals(other.repositorySlug)) { + return false; + } + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.userLevel != other.userLevel) { + return false; + } + if (this.confirmation == null) { + if (other.confirmation != null) { + return false; + } + } else if (!this.confirmation.equals(other.confirmation)) { + return false; + } + if (this.buttonForm == null) { + if (other.buttonForm != null) { + return false; + } + } else if (!this.buttonForm.equals(other.buttonForm)) { + return false; + } + if (this.uuid == null) { + if (other.uuid != null) { + return false; + } + } else if (!this.uuid.equals(other.uuid)) { + return false; + } + return true; + } + + public ON_OR_OFF getConfirmation() { + return this.confirmation; + } + + public String getName() { + return this.name; + } + + public String getButtonForm() { + return this.buttonForm; + } + + public Optional getProjectKey() { + return Optional.fromNullable(this.projectKey); + } + + public Optional getRepositorySlug() { + return Optional.fromNullable(this.repositorySlug); + } + + public USER_LEVEL getUserLevel() { + return this.userLevel; + } + + public UUID getUuid() { + return this.uuid; + } + + public UUID getUUID() { + return this.uuid; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); + result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.userLevel == null) ? 0 : this.userLevel.hashCode()); + result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); + result = prime * result + ((this.confirmation == null) ? 0 : this.confirmation.hashCode()); + result = prime * result + ((this.buttonForm == null) ? 0 : this.buttonForm.hashCode()); + return result; + } + + public void setConfirmation(ON_OR_OFF confirmation) { + this.confirmation = confirmation; + } + + public void setName(String name) { + this.name = name; + } + + public void setButtonForm(String buttonForm) { + this.buttonForm = buttonForm; + } + public void setProjectKey(String projectKey) { + this.projectKey = projectKey; + } + + public void setRepositorySlug(String repositorySlug) { + this.repositorySlug = repositorySlug; + } + + public void setUserLevel(USER_LEVEL userLevel) { + this.userLevel = userLevel; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + @Override + public String toString() { + return "ButtonDTO [name=" + + this.name + + ", userLevel=" + + this.userLevel + + ", uuid=" + + this.uuid + + ", repositorySlug=" + + this.repositorySlug + + ", projectKey=" + + this.projectKey + + ", buttonForm=" + + this.buttonForm + + ", confirmation=" + + this.confirmation + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonPressDTO.java b/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonPressDTO.java index 1a932556..613bc6a7 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonPressDTO.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/ButtonPressDTO.java @@ -10,59 +10,65 @@ @XmlRootElement @XmlAccessorType(FIELD) public class ButtonPressDTO { - private final ON_OR_OFF confirmation; - private final List notificationResponses; + private final ON_OR_OFF confirmation; + private final List notificationResponses; - public ButtonPressDTO(ON_OR_OFF confirmation, List notificationResponses) { - this.confirmation = confirmation; - this.notificationResponses = notificationResponses; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; + public ButtonPressDTO( + ON_OR_OFF confirmation, List notificationResponses) { + this.confirmation = confirmation; + this.notificationResponses = notificationResponses; } - ButtonPressDTO other = (ButtonPressDTO) obj; - if (this.confirmation != other.confirmation) { - return false; - } - if (this.notificationResponses == null) { - if (other.notificationResponses != null) { - return false; - } - } else if (!this.notificationResponses.equals(other.notificationResponses)) { - return false; + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ButtonPressDTO other = (ButtonPressDTO) obj; + if (this.confirmation != other.confirmation) { + return false; + } + if (this.notificationResponses == null) { + if (other.notificationResponses != null) { + return false; + } + } else if (!this.notificationResponses.equals(other.notificationResponses)) { + return false; + } + return true; } - return true; - } - public ON_OR_OFF getConfirmation() { - return this.confirmation; - } + public ON_OR_OFF getConfirmation() { + return this.confirmation; + } - public List getNotificationResponses() { - return this.notificationResponses; - } + public List getNotificationResponses() { + return this.notificationResponses; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.confirmation == null) ? 0 : this.confirmation.hashCode()); - result = prime * result + ((this.notificationResponses == null) ? 0 : this.notificationResponses.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.confirmation == null) ? 0 : this.confirmation.hashCode()); + result = + prime * result + + ((this.notificationResponses == null) ? 0 : this.notificationResponses.hashCode()); + return result; + } - @Override - public String toString() { - return "ButtonPressDTO [confirmation=" + this.confirmation + ", notificationResponses=" + this.notificationResponses - + "]"; - } + @Override + public String toString() { + return "ButtonPressDTO [confirmation=" + + this.confirmation + + ", notificationResponses=" + + this.notificationResponses + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/HeaderDTO.java b/src/main/java/se/bjurr/prnfb/presentation/dto/HeaderDTO.java index 041d6214..425e38e6 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/HeaderDTO.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/HeaderDTO.java @@ -9,66 +9,65 @@ @XmlAccessorType(FIELD) public class HeaderDTO { - private String name; - private String value; + private String name; + private String value; - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + HeaderDTO other = (HeaderDTO) obj; + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.value == null) { + if (other.value != null) { + return false; + } + } else if (!this.value.equals(other.value)) { + return false; + } + return true; } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - HeaderDTO other = (HeaderDTO) obj; - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - if (this.value == null) { - if (other.value != null) { - return false; - } - } else if (!this.value.equals(other.value)) { - return false; - } - return true; - } - - public String getName() { - return this.name; - } - public String getValue() { - return this.value; - } + public String getName() { + return this.name; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.value == null) ? 0 : this.value.hashCode()); - return result; - } + public String getValue() { + return this.value; + } - public void setName(String name) { - this.name = name; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.value == null) ? 0 : this.value.hashCode()); + return result; + } - public void setValue(String value) { - this.value = value; - } + public void setName(String name) { + this.name = name; + } - @Override - public String toString() { - return "HeaderDTO [name=" + this.name + ", value=" + this.value + "]"; - } + public void setValue(String value) { + this.value = value; + } + @Override + public String toString() { + return "HeaderDTO [name=" + this.name + ", value=" + this.value + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationDTO.java b/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationDTO.java index df038b42..14297c80 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationDTO.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationDTO.java @@ -14,381 +14,385 @@ @XmlRootElement @XmlAccessorType(FIELD) public class NotificationDTO implements Comparable { - private String filterRegexp; - private String filterString; - private List headers; - private String injectionUrl; - private String injectionUrlRegexp; - private HTTP_METHOD method; - private String name; - private String password; - private String postContent; - private String projectKey; - private String proxyPassword; - private Integer proxyPort; - private String proxyServer; - private String proxyUser; - private String repositorySlug; - private TRIGGER_IF_MERGE triggerIfCanMerge; - private List triggerIgnoreStateList; - private List triggers; - private String url; - private String user; - private UUID uuid; - - @Override - public int compareTo(NotificationDTO o) { - return this.name.compareTo(o.name); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - NotificationDTO other = (NotificationDTO) obj; - if (this.filterRegexp == null) { - if (other.filterRegexp != null) { - return false; - } - } else if (!this.filterRegexp.equals(other.filterRegexp)) { - return false; - } - if (this.filterString == null) { - if (other.filterString != null) { - return false; - } - } else if (!this.filterString.equals(other.filterString)) { - return false; - } - if (this.headers == null) { - if (other.headers != null) { - return false; - } - } else if (!this.headers.equals(other.headers)) { - return false; - } - if (this.injectionUrl == null) { - if (other.injectionUrl != null) { - return false; - } - } else if (!this.injectionUrl.equals(other.injectionUrl)) { - return false; - } - if (this.injectionUrlRegexp == null) { - if (other.injectionUrlRegexp != null) { - return false; - } - } else if (!this.injectionUrlRegexp.equals(other.injectionUrlRegexp)) { - return false; - } - if (this.method != other.method) { - return false; - } - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - if (this.password == null) { - if (other.password != null) { - return false; - } - } else if (!this.password.equals(other.password)) { - return false; - } - if (this.postContent == null) { - if (other.postContent != null) { - return false; - } - } else if (!this.postContent.equals(other.postContent)) { - return false; - } - if (this.projectKey == null) { - if (other.projectKey != null) { - return false; - } - } else if (!this.projectKey.equals(other.projectKey)) { - return false; - } - if (this.proxyPassword == null) { - if (other.proxyPassword != null) { - return false; - } - } else if (!this.proxyPassword.equals(other.proxyPassword)) { - return false; - } - if (this.proxyPort == null) { - if (other.proxyPort != null) { - return false; - } - } else if (!this.proxyPort.equals(other.proxyPort)) { - return false; - } - if (this.proxyServer == null) { - if (other.proxyServer != null) { - return false; - } - } else if (!this.proxyServer.equals(other.proxyServer)) { - return false; - } - if (this.proxyUser == null) { - if (other.proxyUser != null) { - return false; - } - } else if (!this.proxyUser.equals(other.proxyUser)) { - return false; - } - if (this.repositorySlug == null) { - if (other.repositorySlug != null) { - return false; - } - } else if (!this.repositorySlug.equals(other.repositorySlug)) { - return false; - } - if (this.triggerIfCanMerge != other.triggerIfCanMerge) { - return false; - } - if (this.triggerIgnoreStateList == null) { - if (other.triggerIgnoreStateList != null) { - return false; - } - } else if (!this.triggerIgnoreStateList.equals(other.triggerIgnoreStateList)) { - return false; - } - if (this.triggers == null) { - if (other.triggers != null) { - return false; - } - } else if (!this.triggers.equals(other.triggers)) { - return false; - } - if (this.url == null) { - if (other.url != null) { - return false; - } - } else if (!this.url.equals(other.url)) { - return false; - } - if (this.user == null) { - if (other.user != null) { - return false; - } - } else if (!this.user.equals(other.user)) { - return false; - } - if (this.uuid == null) { - if (other.uuid != null) { - return false; - } - } else if (!this.uuid.equals(other.uuid)) { - return false; - } - return true; - } - - public String getFilterRegexp() { - return this.filterRegexp; - } - - public String getFilterString() { - return this.filterString; - } - - public List getHeaders() { - return this.headers; - } - - public String getInjectionUrl() { - return this.injectionUrl; - } - - public String getInjectionUrlRegexp() { - return this.injectionUrlRegexp; - } - - public HTTP_METHOD getMethod() { - return this.method; - } - - public String getName() { - return this.name; - } - - public String getPassword() { - return this.password; - } - - public String getPostContent() { - return this.postContent; - } - - public String getProjectKey() { - return this.projectKey; - } - - public String getProxyPassword() { - return this.proxyPassword; - } - - public Integer getProxyPort() { - return this.proxyPort; - } - - public String getProxyServer() { - return this.proxyServer; - } - - public String getProxyUser() { - return this.proxyUser; - } - - public String getRepositorySlug() { - return this.repositorySlug; - } - - public TRIGGER_IF_MERGE getTriggerIfCanMerge() { - return this.triggerIfCanMerge; - } - - public List getTriggerIgnoreStateList() { - return this.triggerIgnoreStateList; - } - - public List getTriggers() { - return this.triggers; - } - - public String getUrl() { - return this.url; - } - - public String getUser() { - return this.user; - } - - public UUID getUuid() { - return this.uuid; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.filterRegexp == null) ? 0 : this.filterRegexp.hashCode()); - result = prime * result + ((this.filterString == null) ? 0 : this.filterString.hashCode()); - result = prime * result + ((this.headers == null) ? 0 : this.headers.hashCode()); - result = prime * result + ((this.injectionUrl == null) ? 0 : this.injectionUrl.hashCode()); - result = prime * result + ((this.injectionUrlRegexp == null) ? 0 : this.injectionUrlRegexp.hashCode()); - result = prime * result + ((this.method == null) ? 0 : this.method.hashCode()); - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.password == null) ? 0 : this.password.hashCode()); - result = prime * result + ((this.postContent == null) ? 0 : this.postContent.hashCode()); - result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); - result = prime * result + ((this.proxyPassword == null) ? 0 : this.proxyPassword.hashCode()); - result = prime * result + ((this.proxyPort == null) ? 0 : this.proxyPort.hashCode()); - result = prime * result + ((this.proxyServer == null) ? 0 : this.proxyServer.hashCode()); - result = prime * result + ((this.proxyUser == null) ? 0 : this.proxyUser.hashCode()); - result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); - result = prime * result + ((this.triggerIfCanMerge == null) ? 0 : this.triggerIfCanMerge.hashCode()); - result = prime * result + ((this.triggerIgnoreStateList == null) ? 0 : this.triggerIgnoreStateList.hashCode()); - result = prime * result + ((this.triggers == null) ? 0 : this.triggers.hashCode()); - result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); - result = prime * result + ((this.user == null) ? 0 : this.user.hashCode()); - result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); - return result; - } - - public void setFilterRegexp(String filterRegexp) { - this.filterRegexp = filterRegexp; - } - - public void setFilterString(String filterString) { - this.filterString = filterString; - } - - public void setHeaders(List headers) { - this.headers = headers; - } - - public void setInjectionUrl(String injectionUrl) { - this.injectionUrl = injectionUrl; - } - - public void setInjectionUrlRegexp(String injectionUrlRegexp) { - this.injectionUrlRegexp = injectionUrlRegexp; - } - - public void setMethod(HTTP_METHOD method) { - this.method = method; - } - - public void setName(String name) { - this.name = name; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setPostContent(String postContent) { - this.postContent = postContent; - } - - public void setProjectKey(String projectKey) { - this.projectKey = projectKey; - } - - public void setProxyPassword(String proxyPassword) { - this.proxyPassword = proxyPassword; - } - - public void setProxyPort(Integer proxyPort) { - this.proxyPort = proxyPort; - } - - public void setProxyServer(String proxyServer) { - this.proxyServer = proxyServer; - } - - public void setProxyUser(String proxyUser) { - this.proxyUser = proxyUser; - } - - public void setRepositorySlug(String repositorySlug) { - this.repositorySlug = repositorySlug; - } - - public void setTriggerIfCanMerge(TRIGGER_IF_MERGE triggerIfCanMerge) { - this.triggerIfCanMerge = triggerIfCanMerge; - } - - public void setTriggerIgnoreStateList(List triggerIgnoreStateList) { - this.triggerIgnoreStateList = triggerIgnoreStateList; - } - - public void setTriggers(List triggers) { - this.triggers = triggers; - } - - public void setUrl(String url) { - this.url = url; - } - - public void setUser(String user) { - this.user = user; - } - - public void setUuid(UUID uuid) { - this.uuid = uuid; - } + private String filterRegexp; + private String filterString; + private List headers; + private String injectionUrl; + private String injectionUrlRegexp; + private HTTP_METHOD method; + private String name; + private String password; + private String postContent; + private String projectKey; + private String proxyPassword; + private Integer proxyPort; + private String proxyServer; + private String proxyUser; + private String repositorySlug; + private TRIGGER_IF_MERGE triggerIfCanMerge; + private List triggerIgnoreStateList; + private List triggers; + private String url; + private String user; + private UUID uuid; + + @Override + public int compareTo(NotificationDTO o) { + return this.name.compareTo(o.name); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NotificationDTO other = (NotificationDTO) obj; + if (this.filterRegexp == null) { + if (other.filterRegexp != null) { + return false; + } + } else if (!this.filterRegexp.equals(other.filterRegexp)) { + return false; + } + if (this.filterString == null) { + if (other.filterString != null) { + return false; + } + } else if (!this.filterString.equals(other.filterString)) { + return false; + } + if (this.headers == null) { + if (other.headers != null) { + return false; + } + } else if (!this.headers.equals(other.headers)) { + return false; + } + if (this.injectionUrl == null) { + if (other.injectionUrl != null) { + return false; + } + } else if (!this.injectionUrl.equals(other.injectionUrl)) { + return false; + } + if (this.injectionUrlRegexp == null) { + if (other.injectionUrlRegexp != null) { + return false; + } + } else if (!this.injectionUrlRegexp.equals(other.injectionUrlRegexp)) { + return false; + } + if (this.method != other.method) { + return false; + } + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.password == null) { + if (other.password != null) { + return false; + } + } else if (!this.password.equals(other.password)) { + return false; + } + if (this.postContent == null) { + if (other.postContent != null) { + return false; + } + } else if (!this.postContent.equals(other.postContent)) { + return false; + } + if (this.projectKey == null) { + if (other.projectKey != null) { + return false; + } + } else if (!this.projectKey.equals(other.projectKey)) { + return false; + } + if (this.proxyPassword == null) { + if (other.proxyPassword != null) { + return false; + } + } else if (!this.proxyPassword.equals(other.proxyPassword)) { + return false; + } + if (this.proxyPort == null) { + if (other.proxyPort != null) { + return false; + } + } else if (!this.proxyPort.equals(other.proxyPort)) { + return false; + } + if (this.proxyServer == null) { + if (other.proxyServer != null) { + return false; + } + } else if (!this.proxyServer.equals(other.proxyServer)) { + return false; + } + if (this.proxyUser == null) { + if (other.proxyUser != null) { + return false; + } + } else if (!this.proxyUser.equals(other.proxyUser)) { + return false; + } + if (this.repositorySlug == null) { + if (other.repositorySlug != null) { + return false; + } + } else if (!this.repositorySlug.equals(other.repositorySlug)) { + return false; + } + if (this.triggerIfCanMerge != other.triggerIfCanMerge) { + return false; + } + if (this.triggerIgnoreStateList == null) { + if (other.triggerIgnoreStateList != null) { + return false; + } + } else if (!this.triggerIgnoreStateList.equals(other.triggerIgnoreStateList)) { + return false; + } + if (this.triggers == null) { + if (other.triggers != null) { + return false; + } + } else if (!this.triggers.equals(other.triggers)) { + return false; + } + if (this.url == null) { + if (other.url != null) { + return false; + } + } else if (!this.url.equals(other.url)) { + return false; + } + if (this.user == null) { + if (other.user != null) { + return false; + } + } else if (!this.user.equals(other.user)) { + return false; + } + if (this.uuid == null) { + if (other.uuid != null) { + return false; + } + } else if (!this.uuid.equals(other.uuid)) { + return false; + } + return true; + } + + public String getFilterRegexp() { + return this.filterRegexp; + } + + public String getFilterString() { + return this.filterString; + } + + public List getHeaders() { + return this.headers; + } + + public String getInjectionUrl() { + return this.injectionUrl; + } + + public String getInjectionUrlRegexp() { + return this.injectionUrlRegexp; + } + + public HTTP_METHOD getMethod() { + return this.method; + } + + public String getName() { + return this.name; + } + + public String getPassword() { + return this.password; + } + + public String getPostContent() { + return this.postContent; + } + + public String getProjectKey() { + return this.projectKey; + } + + public String getProxyPassword() { + return this.proxyPassword; + } + + public Integer getProxyPort() { + return this.proxyPort; + } + + public String getProxyServer() { + return this.proxyServer; + } + + public String getProxyUser() { + return this.proxyUser; + } + + public String getRepositorySlug() { + return this.repositorySlug; + } + + public TRIGGER_IF_MERGE getTriggerIfCanMerge() { + return this.triggerIfCanMerge; + } + + public List getTriggerIgnoreStateList() { + return this.triggerIgnoreStateList; + } + + public List getTriggers() { + return this.triggers; + } + + public String getUrl() { + return this.url; + } + + public String getUser() { + return this.user; + } + + public UUID getUuid() { + return this.uuid; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.filterRegexp == null) ? 0 : this.filterRegexp.hashCode()); + result = prime * result + ((this.filterString == null) ? 0 : this.filterString.hashCode()); + result = prime * result + ((this.headers == null) ? 0 : this.headers.hashCode()); + result = prime * result + ((this.injectionUrl == null) ? 0 : this.injectionUrl.hashCode()); + result = + prime * result + + ((this.injectionUrlRegexp == null) ? 0 : this.injectionUrlRegexp.hashCode()); + result = prime * result + ((this.method == null) ? 0 : this.method.hashCode()); + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.password == null) ? 0 : this.password.hashCode()); + result = prime * result + ((this.postContent == null) ? 0 : this.postContent.hashCode()); + result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); + result = prime * result + ((this.proxyPassword == null) ? 0 : this.proxyPassword.hashCode()); + result = prime * result + ((this.proxyPort == null) ? 0 : this.proxyPort.hashCode()); + result = prime * result + ((this.proxyServer == null) ? 0 : this.proxyServer.hashCode()); + result = prime * result + ((this.proxyUser == null) ? 0 : this.proxyUser.hashCode()); + result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); + result = + prime * result + ((this.triggerIfCanMerge == null) ? 0 : this.triggerIfCanMerge.hashCode()); + result = + prime * result + + ((this.triggerIgnoreStateList == null) ? 0 : this.triggerIgnoreStateList.hashCode()); + result = prime * result + ((this.triggers == null) ? 0 : this.triggers.hashCode()); + result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); + result = prime * result + ((this.user == null) ? 0 : this.user.hashCode()); + result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); + return result; + } + + public void setFilterRegexp(String filterRegexp) { + this.filterRegexp = filterRegexp; + } + + public void setFilterString(String filterString) { + this.filterString = filterString; + } + + public void setHeaders(List headers) { + this.headers = headers; + } + + public void setInjectionUrl(String injectionUrl) { + this.injectionUrl = injectionUrl; + } + + public void setInjectionUrlRegexp(String injectionUrlRegexp) { + this.injectionUrlRegexp = injectionUrlRegexp; + } + + public void setMethod(HTTP_METHOD method) { + this.method = method; + } + + public void setName(String name) { + this.name = name; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setPostContent(String postContent) { + this.postContent = postContent; + } + + public void setProjectKey(String projectKey) { + this.projectKey = projectKey; + } + + public void setProxyPassword(String proxyPassword) { + this.proxyPassword = proxyPassword; + } + + public void setProxyPort(Integer proxyPort) { + this.proxyPort = proxyPort; + } + + public void setProxyServer(String proxyServer) { + this.proxyServer = proxyServer; + } + + public void setProxyUser(String proxyUser) { + this.proxyUser = proxyUser; + } + + public void setRepositorySlug(String repositorySlug) { + this.repositorySlug = repositorySlug; + } + public void setTriggerIfCanMerge(TRIGGER_IF_MERGE triggerIfCanMerge) { + this.triggerIfCanMerge = triggerIfCanMerge; + } + + public void setTriggerIgnoreStateList(List triggerIgnoreStateList) { + this.triggerIgnoreStateList = triggerIgnoreStateList; + } + + public void setTriggers(List triggers) { + this.triggers = triggers; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setUser(String user) { + this.user = user; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } } diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationResponseDTO.java b/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationResponseDTO.java index b26ee6e0..767fda44 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationResponseDTO.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/NotificationResponseDTO.java @@ -11,91 +11,101 @@ @XmlRootElement @XmlAccessorType(FIELD) public class NotificationResponseDTO implements Comparable { - private final String content; - private final UUID notification; - private final String notificationName; - private final int status; - private final URI uri; + private final String content; + private final UUID notification; + private final String notificationName; + private final int status; + private final URI uri; - public NotificationResponseDTO(URI uri, String content, int status, UUID notification, String notificationName) { - this.content = content; - this.status = status; - this.notification = notification; - this.notificationName = notificationName; - this.uri = uri; - } - - @Override - public int compareTo(NotificationResponseDTO o) { - return this.notificationName.compareTo(o.notificationName); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - NotificationResponseDTO other = (NotificationResponseDTO) obj; - if (this.content == null) { - if (other.content != null) { - return false; - } - } else if (!this.content.equals(other.content)) { - return false; - } - if (this.notification == null) { - if (other.notification != null) { - return false; - } - } else if (!this.notification.equals(other.notification)) { - return false; - } - if (this.notificationName == null) { - if (other.notificationName != null) { - return false; - } - } else if (!this.notificationName.equals(other.notificationName)) { - return false; + public NotificationResponseDTO( + URI uri, String content, int status, UUID notification, String notificationName) { + this.content = content; + this.status = status; + this.notification = notification; + this.notificationName = notificationName; + this.uri = uri; } - if (this.status != other.status) { - return false; - } - if (this.uri == null) { - if (other.uri != null) { - return false; - } - } else if (!this.uri.equals(other.uri)) { - return false; + + @Override + public int compareTo(NotificationResponseDTO o) { + return this.notificationName.compareTo(o.notificationName); } - return true; - } - public URI getUri() { - return this.uri; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NotificationResponseDTO other = (NotificationResponseDTO) obj; + if (this.content == null) { + if (other.content != null) { + return false; + } + } else if (!this.content.equals(other.content)) { + return false; + } + if (this.notification == null) { + if (other.notification != null) { + return false; + } + } else if (!this.notification.equals(other.notification)) { + return false; + } + if (this.notificationName == null) { + if (other.notificationName != null) { + return false; + } + } else if (!this.notificationName.equals(other.notificationName)) { + return false; + } + if (this.status != other.status) { + return false; + } + if (this.uri == null) { + if (other.uri != null) { + return false; + } + } else if (!this.uri.equals(other.uri)) { + return false; + } + return true; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.content == null) ? 0 : this.content.hashCode()); - result = prime * result + ((this.notification == null) ? 0 : this.notification.hashCode()); - result = prime * result + ((this.notificationName == null) ? 0 : this.notificationName.hashCode()); - result = prime * result + this.status; - result = prime * result + ((this.uri == null) ? 0 : this.uri.hashCode()); - return result; - } + public URI getUri() { + return this.uri; + } - @Override - public String toString() { - return "NotificationResponseDTO [content=" + this.content + ", notification=" + this.notification - + ", notificationName=" + this.notificationName + ", status=" + this.status + ", uri=" + this.uri + "]"; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.content == null) ? 0 : this.content.hashCode()); + result = prime * result + ((this.notification == null) ? 0 : this.notification.hashCode()); + result = + prime * result + ((this.notificationName == null) ? 0 : this.notificationName.hashCode()); + result = prime * result + this.status; + result = prime * result + ((this.uri == null) ? 0 : this.uri.hashCode()); + return result; + } + @Override + public String toString() { + return "NotificationResponseDTO [content=" + + this.content + + ", notification=" + + this.notification + + ", notificationName=" + + this.notificationName + + ", status=" + + this.status + + ", uri=" + + this.uri + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/ON_OR_OFF.java b/src/main/java/se/bjurr/prnfb/presentation/dto/ON_OR_OFF.java index 48bde8ee..f0b24e30 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/ON_OR_OFF.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/ON_OR_OFF.java @@ -1,5 +1,6 @@ package se.bjurr.prnfb.presentation.dto; public enum ON_OR_OFF { - on, off + on, + off } diff --git a/src/main/java/se/bjurr/prnfb/presentation/dto/SettingsDataDTO.java b/src/main/java/se/bjurr/prnfb/presentation/dto/SettingsDataDTO.java index bc87b913..244e3f16 100644 --- a/src/main/java/se/bjurr/prnfb/presentation/dto/SettingsDataDTO.java +++ b/src/main/java/se/bjurr/prnfb/presentation/dto/SettingsDataDTO.java @@ -11,111 +11,120 @@ @XmlAccessorType(FIELD) public class SettingsDataDTO { - private USER_LEVEL adminRestriction; - private String keyStore; - private String keyStorePassword; - private String keyStoreType; - private boolean shouldAcceptAnyCertificate; - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + private USER_LEVEL adminRestriction; + private String keyStore; + private String keyStorePassword; + private String keyStoreType; + private boolean shouldAcceptAnyCertificate; + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + SettingsDataDTO other = (SettingsDataDTO) obj; + if (this.adminRestriction != other.adminRestriction) { + return false; + } + if (this.keyStore == null) { + if (other.keyStore != null) { + return false; + } + } else if (!this.keyStore.equals(other.keyStore)) { + return false; + } + if (this.keyStorePassword == null) { + if (other.keyStorePassword != null) { + return false; + } + } else if (!this.keyStorePassword.equals(other.keyStorePassword)) { + return false; + } + if (this.keyStoreType == null) { + if (other.keyStoreType != null) { + return false; + } + } else if (!this.keyStoreType.equals(other.keyStoreType)) { + return false; + } + if (this.shouldAcceptAnyCertificate != other.shouldAcceptAnyCertificate) { + return false; + } + return true; } - if (obj == null) { - return false; + + public USER_LEVEL getAdminRestriction() { + return this.adminRestriction; + } + + public String getKeyStore() { + return this.keyStore; + } + + public String getKeyStorePassword() { + return this.keyStorePassword; + } + + public String getKeyStoreType() { + return this.keyStoreType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = + prime * result + ((this.adminRestriction == null) ? 0 : this.adminRestriction.hashCode()); + result = prime * result + ((this.keyStore == null) ? 0 : this.keyStore.hashCode()); + result = + prime * result + ((this.keyStorePassword == null) ? 0 : this.keyStorePassword.hashCode()); + result = prime * result + ((this.keyStoreType == null) ? 0 : this.keyStoreType.hashCode()); + result = prime * result + (this.shouldAcceptAnyCertificate ? 1231 : 1237); + return result; } - if (getClass() != obj.getClass()) { - return false; + + public boolean isShouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; } - SettingsDataDTO other = (SettingsDataDTO) obj; - if (this.adminRestriction != other.adminRestriction) { - return false; + + public void setAdminRestriction(USER_LEVEL adminRestriction) { + this.adminRestriction = adminRestriction; } - if (this.keyStore == null) { - if (other.keyStore != null) { - return false; - } - } else if (!this.keyStore.equals(other.keyStore)) { - return false; + + public void setKeyStore(String keyStore) { + this.keyStore = keyStore; } - if (this.keyStorePassword == null) { - if (other.keyStorePassword != null) { - return false; - } - } else if (!this.keyStorePassword.equals(other.keyStorePassword)) { - return false; + + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; } - if (this.keyStoreType == null) { - if (other.keyStoreType != null) { - return false; - } - } else if (!this.keyStoreType.equals(other.keyStoreType)) { - return false; + + public void setKeyStoreType(String keyStoreType) { + this.keyStoreType = keyStoreType; } - if (this.shouldAcceptAnyCertificate != other.shouldAcceptAnyCertificate) { - return false; + + public void setShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { + this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; } - return true; - } - - public USER_LEVEL getAdminRestriction() { - return this.adminRestriction; - } - - public String getKeyStore() { - return this.keyStore; - } - - public String getKeyStorePassword() { - return this.keyStorePassword; - } - - public String getKeyStoreType() { - return this.keyStoreType; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.adminRestriction == null) ? 0 : this.adminRestriction.hashCode()); - result = prime * result + ((this.keyStore == null) ? 0 : this.keyStore.hashCode()); - result = prime * result + ((this.keyStorePassword == null) ? 0 : this.keyStorePassword.hashCode()); - result = prime * result + ((this.keyStoreType == null) ? 0 : this.keyStoreType.hashCode()); - result = prime * result + (this.shouldAcceptAnyCertificate ? 1231 : 1237); - return result; - } - - public boolean isShouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } - - public void setAdminRestriction(USER_LEVEL adminRestriction) { - this.adminRestriction = adminRestriction; - } - - public void setKeyStore(String keyStore) { - this.keyStore = keyStore; - } - - public void setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - } - - public void setKeyStoreType(String keyStoreType) { - this.keyStoreType = keyStoreType; - } - - public void setShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { - this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; - } - - @Override - public String toString() { - return "SettingsDataDTO [adminRestriction=" + this.adminRestriction + ", keyStore=" + this.keyStore - + ", keyStorePassword=" + this.keyStorePassword + ", keyStoreType=" + this.keyStoreType - + ", shouldAcceptAnyCertificate=" + this.shouldAcceptAnyCertificate + "]"; - } + @Override + public String toString() { + return "SettingsDataDTO [adminRestriction=" + + this.adminRestriction + + ", keyStore=" + + this.keyStore + + ", keyStorePassword=" + + this.keyStorePassword + + ", keyStoreType=" + + this.keyStoreType + + ", shouldAcceptAnyCertificate=" + + this.shouldAcceptAnyCertificate + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/service/ButtonsService.java b/src/main/java/se/bjurr/prnfb/service/ButtonsService.java index 7b035d40..7096757a 100644 --- a/src/main/java/se/bjurr/prnfb/service/ButtonsService.java +++ b/src/main/java/se/bjurr/prnfb/service/ButtonsService.java @@ -5,178 +5,215 @@ import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static se.bjurr.prnfb.listener.PrnfbPullRequestAction.BUTTON_TRIGGER; -import static se.bjurr.prnfb.service.PrnfbVariable.BUTTON_TRIGGER_TITLE; import static se.bjurr.prnfb.service.PrnfbVariable.BUTTON_FORM_DATA; +import static se.bjurr.prnfb.service.PrnfbVariable.BUTTON_TRIGGER_TITLE; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import com.atlassian.bitbucket.pull.PullRequest; +import com.atlassian.bitbucket.pull.PullRequestService; +import com.atlassian.bitbucket.repository.Repository; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; + import se.bjurr.prnfb.http.ClientKeyStore; import se.bjurr.prnfb.http.NotificationResponse; import se.bjurr.prnfb.listener.PrnfbPullRequestAction; import se.bjurr.prnfb.listener.PrnfbPullRequestEventListener; +import se.bjurr.prnfb.service.PrnfbRenderer.ENCODE_FOR; import se.bjurr.prnfb.settings.PrnfbButton; import se.bjurr.prnfb.settings.PrnfbNotification; import se.bjurr.prnfb.settings.PrnfbSettingsData; -import com.atlassian.bitbucket.pull.PullRequest; -import com.atlassian.bitbucket.pull.PullRequestService; -import com.atlassian.bitbucket.repository.Repository; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; - public class ButtonsService { - private final PrnfbPullRequestEventListener prnfbPullRequestEventListener; - private final PrnfbRendererFactory prnfbRendererFactory; - private final PullRequestService pullRequestService; - private final SettingsService settingsService; - private final UserCheckService userCheckService; - - public ButtonsService(PullRequestService pullRequestService, - PrnfbPullRequestEventListener prnfbPullRequestEventListener, PrnfbRendererFactory prnfbRendererFactory, - SettingsService settingsService, UserCheckService userCheckService) { - this.pullRequestService = pullRequestService; - this.prnfbPullRequestEventListener = prnfbPullRequestEventListener; - this.prnfbRendererFactory = prnfbRendererFactory; - this.settingsService = settingsService; - this.userCheckService = userCheckService; - } - - public List getButtons(Integer repositoryId, Long pullRequestId) { - final PrnfbSettingsData settings = this.settingsService.getPrnfbSettingsData(); - List notifications = this.settingsService.getNotifications(); - ClientKeyStore clientKeyStore = new ClientKeyStore(settings); - final PullRequest pullRequest = this.pullRequestService.getById(repositoryId, pullRequestId); - boolean shouldAcceptAnyCertificate = settings.isShouldAcceptAnyCertificate(); - return doGetButtons(notifications, clientKeyStore, pullRequest, shouldAcceptAnyCertificate); - } - - public String getRenderedButtonFormData(Integer repositoryId, Long pullRequestId, UUID buttonUuid, String formData) { - final PrnfbSettingsData settings = this.settingsService.getPrnfbSettingsData(); - ClientKeyStore clientKeyStore = new ClientKeyStore(settings); - final PullRequest pullRequest = this.pullRequestService.getById(repositoryId, pullRequestId); - boolean shouldAcceptAnyCertificate = settings.isShouldAcceptAnyCertificate(); - - Map> variables = getVariables(buttonUuid, formData); - PrnfbPullRequestAction pullRequestAction = BUTTON_TRIGGER; - - PrnfbRenderer renderer = this.prnfbRendererFactory.create(pullRequest, pullRequestAction, null, variables); - return renderer.render(formData, false, true, clientKeyStore, shouldAcceptAnyCertificate); -} - - public List handlePressed(Integer repositoryId, Long pullRequestId, UUID buttonUuid, String formData) { - final PrnfbSettingsData prnfbSettingsData = this.settingsService.getPrnfbSettingsData(); - ClientKeyStore clientKeyStore = new ClientKeyStore(prnfbSettingsData); - boolean shouldAcceptAnyCertificate = prnfbSettingsData.isShouldAcceptAnyCertificate(); - final PullRequest pullRequest = this.pullRequestService.getById(repositoryId, pullRequestId); - return doHandlePressed(buttonUuid, clientKeyStore, shouldAcceptAnyCertificate, pullRequest, formData); - } - - private boolean isTriggeredByAction(ClientKeyStore clientKeyStore, List notifications, - boolean shouldAcceptAnyCertificate, PrnfbPullRequestAction pullRequestAction, PullRequest pullRequest, - Map> variables) { - for (PrnfbNotification prnfbNotification : notifications) { - PrnfbRenderer renderer = this.prnfbRendererFactory.create(pullRequest, pullRequestAction, prnfbNotification, - variables); - if (this.prnfbPullRequestEventListener.isNotificationTriggeredByAction(prnfbNotification, pullRequestAction, - renderer, pullRequest, clientKeyStore, shouldAcceptAnyCertificate)) { - return TRUE; - } + private final PrnfbPullRequestEventListener prnfbPullRequestEventListener; + private final PrnfbRendererFactory prnfbRendererFactory; + private final PullRequestService pullRequestService; + private final SettingsService settingsService; + private final UserCheckService userCheckService; + + public ButtonsService( + PullRequestService pullRequestService, + PrnfbPullRequestEventListener prnfbPullRequestEventListener, + PrnfbRendererFactory prnfbRendererFactory, + SettingsService settingsService, + UserCheckService userCheckService) { + this.pullRequestService = pullRequestService; + this.prnfbPullRequestEventListener = prnfbPullRequestEventListener; + this.prnfbRendererFactory = prnfbRendererFactory; + this.settingsService = settingsService; + this.userCheckService = userCheckService; + } + + @VisibleForTesting + List doGetButtons( + List notifications, + ClientKeyStore clientKeyStore, + final PullRequest pullRequest, + boolean shouldAcceptAnyCertificate) { + List allFoundButtons = newArrayList(); + for (PrnfbButton candidate : settingsService.getButtons()) { + Map> variables = getVariables(candidate.getUuid(), null); + PrnfbPullRequestAction pullRequestAction = BUTTON_TRIGGER; + if (userCheckService.isAllowedUseButton(candidate) // + && isTriggeredByAction( + clientKeyStore, + notifications, + shouldAcceptAnyCertificate, + pullRequestAction, + pullRequest, + variables) // + && isVisibleOnPullRequest(candidate, pullRequest)) { + allFoundButtons.add(candidate); + } + } + allFoundButtons = usingToString().sortedCopy(allFoundButtons); + return allFoundButtons; + } + + @VisibleForTesting + List doHandlePressed( + UUID buttonUuid, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + final PullRequest pullRequest, + final String formData) { + Map> variables = getVariables(buttonUuid, formData); + List successes = newArrayList(); + for (PrnfbNotification prnfbNotification : settingsService.getNotifications()) { + PrnfbPullRequestAction pullRequestAction = BUTTON_TRIGGER; + PrnfbRenderer renderer = + prnfbRendererFactory.create(pullRequest, pullRequestAction, prnfbNotification, variables); + if (prnfbPullRequestEventListener.isNotificationTriggeredByAction( + prnfbNotification, + pullRequestAction, + renderer, + pullRequest, + clientKeyStore, + shouldAcceptAnyCertificate)) { + NotificationResponse response = + prnfbPullRequestEventListener.notify( + prnfbNotification, + pullRequestAction, + pullRequest, + renderer, + clientKeyStore, + shouldAcceptAnyCertificate); + if (response != null) { + successes.add(response); + } + } + } + + return successes; + } + + public List getButtons(Integer repositoryId, Long pullRequestId) { + final PrnfbSettingsData settings = settingsService.getPrnfbSettingsData(); + List notifications = settingsService.getNotifications(); + ClientKeyStore clientKeyStore = new ClientKeyStore(settings); + final PullRequest pullRequest = pullRequestService.getById(repositoryId, pullRequestId); + boolean shouldAcceptAnyCertificate = settings.isShouldAcceptAnyCertificate(); + return doGetButtons(notifications, clientKeyStore, pullRequest, shouldAcceptAnyCertificate); + } + + public String getRenderedButtonFormData( + Integer repositoryId, Long pullRequestId, UUID buttonUuid, String formData) { + final PrnfbSettingsData settings = settingsService.getPrnfbSettingsData(); + ClientKeyStore clientKeyStore = new ClientKeyStore(settings); + final PullRequest pullRequest = pullRequestService.getById(repositoryId, pullRequestId); + boolean shouldAcceptAnyCertificate = settings.isShouldAcceptAnyCertificate(); + + Map> variables = getVariables(buttonUuid, formData); + PrnfbPullRequestAction pullRequestAction = BUTTON_TRIGGER; + + PrnfbRenderer renderer = + prnfbRendererFactory.create(pullRequest, pullRequestAction, null, variables); + return renderer.render(formData, ENCODE_FOR.JSON, clientKeyStore, shouldAcceptAnyCertificate); } - return FALSE; - } - - /** - * Checks if the given button is visible on the pull request by either the from - * or to repository. - */ - private boolean isVisibleOnPullRequest(PrnfbButton button, PullRequest pullRequest) { - return (pullRequest.getFromRef() != null && isVisibleOnRepository(button, pullRequest.getFromRef().getRepository())) - || (pullRequest.getToRef() != null && isVisibleOnRepository(button, pullRequest.getToRef().getRepository())); - } - - @VisibleForTesting - List doGetButtons(List notifications, ClientKeyStore clientKeyStore, - final PullRequest pullRequest, boolean shouldAcceptAnyCertificate) { - List allFoundButtons = newArrayList(); - for (PrnfbButton candidate : this.settingsService.getButtons()) { - Map> variables = getVariables(candidate.getUuid(), null); - PrnfbPullRequestAction pullRequestAction = BUTTON_TRIGGER; - if (this.userCheckService.isAllowedUseButton(candidate)// - && isTriggeredByAction(clientKeyStore, notifications, shouldAcceptAnyCertificate, pullRequestAction, pullRequest, - variables) // - && (isVisibleOnPullRequest(candidate, pullRequest))) { - allFoundButtons.add(candidate); - } + + @VisibleForTesting + Map> getVariables(final UUID uuid, final String formData) { + Map> variables = new HashMap<>(); + PrnfbButton button = settingsService.getButton(uuid); + variables.put(BUTTON_TRIGGER_TITLE, Suppliers.ofInstance(button.getName())); + variables.put(BUTTON_FORM_DATA, Suppliers.ofInstance(formData)); + return variables; } - allFoundButtons = usingToString().sortedCopy(allFoundButtons); - return allFoundButtons; - } - - @VisibleForTesting - List doHandlePressed(UUID buttonUuid, ClientKeyStore clientKeyStore, - boolean shouldAcceptAnyCertificate, final PullRequest pullRequest, final String formData) { - Map> variables = getVariables(buttonUuid, formData); - List successes = newArrayList(); - for (PrnfbNotification prnfbNotification : this.settingsService.getNotifications()) { - PrnfbPullRequestAction pullRequestAction = BUTTON_TRIGGER; - PrnfbRenderer renderer = this.prnfbRendererFactory.create(pullRequest, pullRequestAction, prnfbNotification, - variables); - if (this.prnfbPullRequestEventListener.isNotificationTriggeredByAction(prnfbNotification, pullRequestAction, - renderer, pullRequest, clientKeyStore, shouldAcceptAnyCertificate)) { - NotificationResponse response = this.prnfbPullRequestEventListener.notify(prnfbNotification, pullRequestAction, - pullRequest, renderer, clientKeyStore, shouldAcceptAnyCertificate); - if (response != null) { - successes.add(response); + + public List handlePressed( + Integer repositoryId, Long pullRequestId, UUID buttonUuid, String formData) { + final PrnfbSettingsData prnfbSettingsData = settingsService.getPrnfbSettingsData(); + ClientKeyStore clientKeyStore = new ClientKeyStore(prnfbSettingsData); + boolean shouldAcceptAnyCertificate = prnfbSettingsData.isShouldAcceptAnyCertificate(); + final PullRequest pullRequest = pullRequestService.getById(repositoryId, pullRequestId); + return doHandlePressed( + buttonUuid, clientKeyStore, shouldAcceptAnyCertificate, pullRequest, formData); + } + + private boolean isTriggeredByAction( + ClientKeyStore clientKeyStore, + List notifications, + boolean shouldAcceptAnyCertificate, + PrnfbPullRequestAction pullRequestAction, + PullRequest pullRequest, + Map> variables) { + for (PrnfbNotification prnfbNotification : notifications) { + PrnfbRenderer renderer = + prnfbRendererFactory.create(pullRequest, pullRequestAction, prnfbNotification, variables); + if (prnfbPullRequestEventListener.isNotificationTriggeredByAction( + prnfbNotification, + pullRequestAction, + renderer, + pullRequest, + clientKeyStore, + shouldAcceptAnyCertificate)) { + return TRUE; + } } - } + return FALSE; } - return successes; - } - - @VisibleForTesting - Map> getVariables(final UUID uuid, final String formData) { - Map> variables = new HashMap>(); - PrnfbButton button = this.settingsService.getButton(uuid); - variables.put(BUTTON_TRIGGER_TITLE, Suppliers.ofInstance(button.getName())); - variables.put(BUTTON_FORM_DATA, Suppliers.ofInstance(formData)); - return variables; - } - - /** - * Checks if the given button is visible in the given repository. - * - * @param button - * Button under test - * @param repository - * Repository to check for - * @return True if the button is either globally visible or matches with the - * given repository - */ - @VisibleForTesting - boolean isVisibleOnRepository(PrnfbButton button, Repository repository) { - boolean projectOk = false; - boolean repoOk = false; - - do { - if (button.getProjectKey().isPresent()) { - projectOk |= button.getProjectKey().get().equals(repository.getProject().getKey()); - } else { - projectOk = true; - } - if (button.getRepositorySlug().isPresent()) { - repoOk |= button.getRepositorySlug().get().equals(repository.getSlug()); - } else { - repoOk = true; - } - } while (!(projectOk && repoOk) && (repository = repository.getOrigin()) != null); - - return projectOk && repoOk; - } + /** + * Checks if the given button is visible on the pull request by either the from or to repository. + */ + private boolean isVisibleOnPullRequest(PrnfbButton button, PullRequest pullRequest) { + return pullRequest.getFromRef() != null + && isVisibleOnRepository(button, pullRequest.getFromRef().getRepository()) + || pullRequest.getToRef() != null + && isVisibleOnRepository(button, pullRequest.getToRef().getRepository()); + } + /** + * Checks if the given button is visible in the given repository. + * + * @param button Button under test + * @param repository Repository to check for + * @return True if the button is either globally visible or matches with the given repository + */ + @VisibleForTesting + boolean isVisibleOnRepository(PrnfbButton button, Repository repository) { + boolean projectOk = false; + boolean repoOk = false; + + do { + if (button.getProjectKey().isPresent()) { + projectOk |= button.getProjectKey().get().equals(repository.getProject().getKey()); + } else { + projectOk = true; + } + if (button.getRepositorySlug().isPresent()) { + repoOk |= button.getRepositorySlug().get().equals(repository.getSlug()); + } else { + repoOk = true; + } + } while (!(projectOk && repoOk) && (repository = repository.getOrigin()) != null); + + return projectOk && repoOk; + } } diff --git a/src/main/java/se/bjurr/prnfb/service/PrnfbRenderer.java b/src/main/java/se/bjurr/prnfb/service/PrnfbRenderer.java index 400766a0..1576a02b 100644 --- a/src/main/java/se/bjurr/prnfb/service/PrnfbRenderer.java +++ b/src/main/java/se/bjurr/prnfb/service/PrnfbRenderer.java @@ -4,6 +4,8 @@ import static com.google.common.base.Throwables.propagate; import static java.net.URLEncoder.encode; import static org.slf4j.LoggerFactory.getLogger; +import static se.bjurr.prnfb.service.PrnfbRenderer.ENCODE_FOR.JSON; +import static se.bjurr.prnfb.service.PrnfbRenderer.ENCODE_FOR.URL; import static se.bjurr.prnfb.service.PrnfbVariable.EVERYTHING_URL; import java.io.UnsupportedEncodingException; @@ -24,96 +26,128 @@ import se.bjurr.prnfb.settings.PrnfbNotification; public class PrnfbRenderer { - private static final Logger LOG = getLogger(PrnfbRenderer.class); - - private final ApplicationUser applicationUser; - private final PrnfbNotification prnfbNotification; - private final ApplicationPropertiesService propertiesService; - private final PullRequest pullRequest; - private final PrnfbPullRequestAction pullRequestAction; - private final RepositoryService repositoryService; - private final SecurityService securityService; - /** - * Contains special variables that are only available for specific events like - * {@link PrnfbVariable#BUTTON_TRIGGER_TITLE} and - * {@link PrnfbVariable#PULL_REQUEST_COMMENT_TEXT}. - */ - private final Map> variables; + public enum ENCODE_FOR { + JSON, + NONE, + URL + } - PrnfbRenderer(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, ApplicationUser applicationUser, - RepositoryService repositoryService, ApplicationPropertiesService propertiesService, - PrnfbNotification prnfbNotification, Map> variables, - SecurityService securityService) { - this.pullRequest = pullRequest; - this.pullRequestAction = pullRequestAction; - this.applicationUser = applicationUser; - this.repositoryService = repositoryService; - this.prnfbNotification = prnfbNotification; - this.propertiesService = propertiesService; - this.variables = variables; - this.securityService = securityService; - } + private static final Logger LOG = getLogger(PrnfbRenderer.class); + private final ApplicationUser applicationUser; + private final PrnfbNotification prnfbNotification; + private final ApplicationPropertiesService propertiesService; + private final PullRequest pullRequest; + private final PrnfbPullRequestAction pullRequestAction; + private final RepositoryService repositoryService; + private final SecurityService securityService; - private boolean containsVariable(String string, final String regExpStr) { - return string.contains(regExpStr.replaceAll("\\\\", "")); - } + /** + * Contains special variables that are only available for specific events like {@link + * PrnfbVariable#BUTTON_TRIGGER_TITLE} and {@link PrnfbVariable#PULL_REQUEST_COMMENT_TEXT}. + */ + private final Map> variables; - @VisibleForTesting - String getRenderedStringResolved(String string, Boolean forUrl, Boolean forJson, final String regExpStr, String resolved) { - String replaceWith = null; - try { - if (forUrl) { - replaceWith = forUrl ? encode(resolved, UTF_8.name()) : resolved; - } else if (forJson) { - // The string we're replacing as JSON is already within a string-encoded JSON blob, so we - // just need to replace any quotes with \\", which will have the behavior we want. - replaceWith = resolved.replace("\"", "\\\\\""); - } - else { + PrnfbRenderer( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + SecurityService securityService) { + this.pullRequest = pullRequest; + this.pullRequestAction = pullRequestAction; + this.applicationUser = applicationUser; + this.repositoryService = repositoryService; + this.prnfbNotification = prnfbNotification; + this.propertiesService = propertiesService; + this.variables = variables; + this.securityService = securityService; + } + + private boolean containsVariable(String string, final String regExpStr) { + return string.contains(regExpStr.replaceAll("\\\\", "")); + } + + @VisibleForTesting + String getRenderedStringResolved( + String string, ENCODE_FOR encodeFor, final String regExpStr, String resolved) { + String replaceWith = null; + if (encodeFor == URL) { + try { + replaceWith = encode(resolved, UTF_8.name()); + } catch (UnsupportedEncodingException e) { + propagate(e); + } + } else if (encodeFor == JSON) { + // The string we're replacing as JSON is already within a string-encoded + // JSON blob, so we + // just need to replace any quotes with \\", which will have the behavior we + // want. + replaceWith = resolved.replace("\"", "\\\\\""); + } else { replaceWith = resolved; } - } catch (UnsupportedEncodingException e) { - propagate(e); - } - try { - string = string.replaceAll(regExpStr, replaceWith); - } catch (IllegalArgumentException e) { - throw new RuntimeException("Tried to replace " + regExpStr + " with " + replaceWith, e); + try { + string = string.replaceAll(regExpStr, replaceWith); + } catch (IllegalArgumentException e) { + throw new RuntimeException("Tried to replace " + regExpStr + " with " + replaceWith, e); + } + return string; } - return string; - } - @VisibleForTesting - String regexp(PrnfbVariable variable) { - return "\\$\\{" + variable.name() + "\\}"; - } + @VisibleForTesting + String regexp(PrnfbVariable variable) { + return "\\$\\{" + variable.name() + "\\}"; + } - public String render(String string, Boolean forUrl, Boolean forJson, ClientKeyStore clientKeyStore, - Boolean shouldAcceptAnyCertificate) { - string = renderVariable(string, false, forJson, clientKeyStore, shouldAcceptAnyCertificate, EVERYTHING_URL); + public String render( + String string, + ENCODE_FOR encodeFor, + ClientKeyStore clientKeyStore, + Boolean shouldAcceptAnyCertificate) { + string = + renderVariable( + string, ENCODE_FOR.NONE, clientKeyStore, shouldAcceptAnyCertificate, EVERYTHING_URL); - for (final PrnfbVariable variable : PrnfbVariable.values()) { - string = renderVariable(string, forUrl, forJson, clientKeyStore, shouldAcceptAnyCertificate, variable); + for (final PrnfbVariable variable : PrnfbVariable.values()) { + string = + renderVariable(string, encodeFor, clientKeyStore, shouldAcceptAnyCertificate, variable); + } + return string; } - return string; - } - private String renderVariable(String string, Boolean forUrl, Boolean forJson, ClientKeyStore clientKeyStore, - Boolean shouldAcceptAnyCertificate, final PrnfbVariable variable) { - final String regExpStr = regexp(variable); - if (containsVariable(string, regExpStr)) { - String resolved = ""; - try { - resolved = variable.resolve(pullRequest, pullRequestAction, applicationUser, repositoryService, propertiesService, - prnfbNotification, variables, clientKeyStore, shouldAcceptAnyCertificate, securityService); - if (resolved == null) { - resolved = ""; + private String renderVariable( + String string, + ENCODE_FOR encodeFor, + ClientKeyStore clientKeyStore, + Boolean shouldAcceptAnyCertificate, + final PrnfbVariable variable) { + final String regExpStr = regexp(variable); + if (containsVariable(string, regExpStr)) { + String resolved = ""; + try { + resolved = + variable.resolve( + pullRequest, + pullRequestAction, + applicationUser, + repositoryService, + propertiesService, + prnfbNotification, + variables, + clientKeyStore, + shouldAcceptAnyCertificate, + securityService); + if (resolved == null) { + resolved = ""; + } + } catch (Exception e) { + LOG.error("Error when resolving " + variable, e); + } + return getRenderedStringResolved(string, encodeFor, regExpStr, resolved); } - } catch (Exception e) { - LOG.error("Error when resolving " + variable, e); - } - return getRenderedStringResolved(string, forUrl, forJson, regExpStr, resolved); + return string; } - return string; - } } diff --git a/src/main/java/se/bjurr/prnfb/service/PrnfbRendererFactory.java b/src/main/java/se/bjurr/prnfb/service/PrnfbRendererFactory.java index 331e796c..3a43b3a2 100644 --- a/src/main/java/se/bjurr/prnfb/service/PrnfbRendererFactory.java +++ b/src/main/java/se/bjurr/prnfb/service/PrnfbRendererFactory.java @@ -15,28 +15,49 @@ public class PrnfbRendererFactory { - private final AuthenticationContext authenticationContext; - private final ApplicationPropertiesService propertiesService; - private final RepositoryService repositoryService; - private final SecurityService securityService; - - public PrnfbRendererFactory(RepositoryService repositoryService, ApplicationPropertiesService propertiesService, - AuthenticationContext authenticationContext, SecurityService securityService) { - this.repositoryService = repositoryService; - this.propertiesService = propertiesService; - this.authenticationContext = authenticationContext; - this.securityService = securityService; - } - - public PrnfbRenderer create(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - PrnfbNotification prnfbNotification, Map> variables) { - return create(pullRequest, pullRequestAction, prnfbNotification, variables, - this.authenticationContext.getCurrentUser()); - } - - public PrnfbRenderer create(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - PrnfbNotification prnfbNotification, Map> variables, ApplicationUser currentUser) { - return new PrnfbRenderer(pullRequest, pullRequestAction, currentUser, this.repositoryService, this.propertiesService, - prnfbNotification, variables, this.securityService); - } + private final AuthenticationContext authenticationContext; + private final ApplicationPropertiesService propertiesService; + private final RepositoryService repositoryService; + private final SecurityService securityService; + + public PrnfbRendererFactory( + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + AuthenticationContext authenticationContext, + SecurityService securityService) { + this.repositoryService = repositoryService; + this.propertiesService = propertiesService; + this.authenticationContext = authenticationContext; + this.securityService = securityService; + } + + public PrnfbRenderer create( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + PrnfbNotification prnfbNotification, + Map> variables) { + return create( + pullRequest, + pullRequestAction, + prnfbNotification, + variables, + this.authenticationContext.getCurrentUser()); + } + + public PrnfbRenderer create( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + PrnfbNotification prnfbNotification, + Map> variables, + ApplicationUser currentUser) { + return new PrnfbRenderer( + pullRequest, + pullRequestAction, + currentUser, + this.repositoryService, + this.propertiesService, + prnfbNotification, + variables, + this.securityService); + } } diff --git a/src/main/java/se/bjurr/prnfb/service/PrnfbVariable.java b/src/main/java/se/bjurr/prnfb/service/PrnfbVariable.java index 02d05fbe..4b6c6ec1 100644 --- a/src/main/java/se/bjurr/prnfb/service/PrnfbVariable.java +++ b/src/main/java/se/bjurr/prnfb/service/PrnfbVariable.java @@ -42,587 +42,1036 @@ import se.bjurr.prnfb.settings.PrnfbNotification; public enum PrnfbVariable { + BUTTON_TRIGGER_TITLE( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return getOrEmpty(variables, BUTTON_TRIGGER_TITLE); + } + }), + EVERYTHING_URL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + List parts = newArrayList(); + for (PrnfbVariable v : PrnfbVariable.values()) { + if (v != EVERYTHING_URL // + && v != PULL_REQUEST_DESCRIPTION) { + parts.add(v.name() + "=\\${" + v.name() + "}"); + } + } + Collections.sort(parts); + return on('&').join(parts); + } + }), + INJECTION_URL_VALUE( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + if (prnfbNotification == null || !prnfbNotification.getInjectionUrl().isPresent()) { + return ""; + } + UrlInvoker urlInvoker = + urlInvoker() // + .withUrlParam(prnfbNotification.getInjectionUrl().get()) // + .withMethod(GET) // + .withProxyServer(prnfbNotification.getProxyServer()) // + .withProxyPort(prnfbNotification.getProxyPort()) // + .withProxyUser(prnfbNotification.getProxyUser()) // + .withProxyPassword(prnfbNotification.getProxyPassword()) // + .appendBasicAuth(prnfbNotification) // + .withClientKeyStore(clientKeyStore) // + .shouldAcceptAnyCertificate(shouldAcceptAnyCertificate); + createInvoker() // + .invoke(urlInvoker); + String rawResponse = urlInvoker.getResponse().getContent().trim(); + if (prnfbNotification.getInjectionUrlRegexp().isPresent()) { + Matcher m = + compile(prnfbNotification.getInjectionUrlRegexp().get()).matcher(rawResponse); + if (!m.find()) { + return ""; + } + if (m.groupCount() == 0) { + return m.group(); + } + return m.group(1); + } else { + return rawResponse; + } + } + }), + PULL_REQUEST_ACTION( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return prnfbPullRequestAction.name(); + } + }), + PULL_REQUEST_AUTHOR_DISPLAY_NAME( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getAuthor().getUser().getDisplayName(); + } + }), + PULL_REQUEST_AUTHOR_EMAIL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getAuthor().getUser().getEmailAddress(); + } + }), + PULL_REQUEST_AUTHOR_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getAuthor().getUser().getId() + ""; + } + }), + PULL_REQUEST_AUTHOR_NAME( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getAuthor().getUser().getName(); + } + }), + PULL_REQUEST_AUTHOR_SLUG( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getAuthor().getUser().getSlug(); + } + }), + PULL_REQUEST_COMMENT_ACTION( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return getOrEmpty(variables, PULL_REQUEST_COMMENT_ACTION); + } + }), + PULL_REQUEST_COMMENT_TEXT( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return getOrEmpty(variables, PULL_REQUEST_COMMENT_TEXT); + } + }), + PULL_REQUEST_DESCRIPTION( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getDescription(); + } + }), + PULL_REQUEST_FROM_BRANCH( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getDisplayId(); + } + }), + PULL_REQUEST_FROM_HASH( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getLatestCommit(); + } + }), + PULL_REQUEST_FROM_HTTP_CLONE_URL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return cloneUrlFromRepository( + http, pullRequest.getFromRef().getRepository(), repositoryService, securityService); + } + }), + PULL_REQUEST_FROM_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getId(); + } + }), + PULL_REQUEST_FROM_REPO_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getRepository().getId() + ""; + } + }), + PULL_REQUEST_FROM_REPO_NAME( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getRepository().getName() + ""; + } + }), + PULL_REQUEST_FROM_REPO_PROJECT_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getRepository().getProject().getId() + ""; + } + }), + PULL_REQUEST_FROM_REPO_PROJECT_KEY( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getRepository().getProject().getKey(); + } + }), + PULL_REQUEST_FROM_REPO_SLUG( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getFromRef().getRepository().getSlug() + ""; + } + }), + PULL_REQUEST_FROM_SSH_CLONE_URL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return cloneUrlFromRepository( + ssh, pullRequest.getFromRef().getRepository(), repositoryService, securityService); + } + }), + PULL_REQUEST_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getId() + ""; + } + }), + PULL_REQUEST_MERGE_COMMIT( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfsPullRequestAction, + ApplicationUser stashUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfsNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return getOrEmpty(variables, PULL_REQUEST_MERGE_COMMIT); + } + }), + PULL_REQUEST_PARTICIPANTS_APPROVED_COUNT( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return Integer.toString( + newArrayList(filter(pullRequest.getParticipants(), isApproved)).size()); + } + }), + PULL_REQUEST_PARTICIPANTS_EMAIL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return iterableToString( + transform(pullRequest.getParticipants(), (p) -> p.getUser().getEmailAddress())); + } + }), + PULL_REQUEST_REVIEWERS( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return iterableToString( + transform(pullRequest.getReviewers(), (p) -> p.getUser().getDisplayName())); + } + }), + PULL_REQUEST_REVIEWERS_APPROVED_COUNT( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return Integer.toString( + newArrayList(filter(pullRequest.getReviewers(), isApproved)).size()); + } + }), + PULL_REQUEST_REVIEWERS_EMAIL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return iterableToString( + transform(pullRequest.getReviewers(), (p) -> p.getUser().getEmailAddress())); + } + }), + PULL_REQUEST_REVIEWERS_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return iterableToString( + transform(pullRequest.getReviewers(), (p) -> Integer.toString(p.getUser().getId()))); + } + }), + PULL_REQUEST_REVIEWERS_SLUG( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return iterableToString( + transform(pullRequest.getReviewers(), (p) -> p.getUser().getSlug())); + } + }), + PULL_REQUEST_STATE( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getState().name(); + } + }), + PULL_REQUEST_TITLE( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getTitle(); + } + }), + PULL_REQUEST_TO_BRANCH( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getDisplayId(); + } + }), + PULL_REQUEST_TO_HASH( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getLatestCommit(); + } + }), + PULL_REQUEST_TO_HTTP_CLONE_URL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return cloneUrlFromRepository( + http, pullRequest.getToRef().getRepository(), repositoryService, securityService); + } + }), + PULL_REQUEST_TO_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getId(); + } + }), + PULL_REQUEST_TO_REPO_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getRepository().getId() + ""; + } + }), + PULL_REQUEST_TO_REPO_NAME( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getRepository().getName() + ""; + } + }), + PULL_REQUEST_TO_REPO_PROJECT_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getRepository().getProject().getId() + ""; + } + }), + PULL_REQUEST_TO_REPO_PROJECT_KEY( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getRepository().getProject().getKey(); + } + }), + PULL_REQUEST_TO_REPO_SLUG( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getToRef().getRepository().getSlug() + ""; + } + }), + PULL_REQUEST_TO_SSH_CLONE_URL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return cloneUrlFromRepository( + ssh, pullRequest.getToRef().getRepository(), repositoryService, securityService); + } + }), + PULL_REQUEST_URL( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return getPullRequestUrl(propertiesService, pullRequest); + } + }), + PULL_REQUEST_USER_DISPLAY_NAME( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return applicationUser.getDisplayName(); + } + }), + PULL_REQUEST_USER_EMAIL_ADDRESS( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return applicationUser.getEmailAddress(); + } + }), + PULL_REQUEST_USER_ID( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return applicationUser.getId() + ""; + } + }), + PULL_REQUEST_USER_NAME( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return applicationUser.getName(); + } + }), + PULL_REQUEST_USER_SLUG( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return applicationUser.getSlug(); + } + }), + PULL_REQUEST_VERSION( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction prnfbPullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return pullRequest.getVersion() + ""; + } + }), + BUTTON_FORM_DATA( + new PrnfbVariableResolver() { + @Override + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return getOrEmpty(variables, BUTTON_FORM_DATA); + } + }); - BUTTON_TRIGGER_TITLE(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return getOrEmpty(variables, BUTTON_TRIGGER_TITLE); + private static final Predicate isApproved = + new Predicate() { + @Override + public boolean apply(PullRequestParticipant input) { + return input.isApproved(); + } + }; + + private static Invoker mockedInvoker = + new Invoker() { + @Override + public HttpResponse invoke(UrlInvoker urlInvoker) { + return urlInvoker.invoke(); + } + }; + + private static String cloneUrlFromRepository( + RepoProtocol protocol, + Repository repository, + RepositoryService repositoryService, + SecurityService securityService) { + return securityService // + .withPermission(Permission.ADMIN, "cloneUrls") // + .call( + new Operation() { + @Override + public String perform() throws RuntimeException { + RepositoryCloneLinksRequest request = + new RepositoryCloneLinksRequest.Builder() // + .protocol(protocol.name()) // + .repository(repository) // + .build(); + final Set cloneLinks = repositoryService.getCloneLinks(request); + Set allUrls = newTreeSet(); + Iterator itr = cloneLinks.iterator(); + while (itr.hasNext()) { + allUrls.add(itr.next().getHref()); + } + if (allUrls.isEmpty()) { + return ""; + } + return allUrls.iterator().next(); + } + }); } - }), EVERYTHING_URL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - List parts = newArrayList(); - for (PrnfbVariable v : PrnfbVariable.values()) { - if (v != EVERYTHING_URL // - && v != PULL_REQUEST_DESCRIPTION) { - parts.add(v.name() + "=\\${" + v.name() + "}"); + + private static Invoker createInvoker() { + if (mockedInvoker != null) { + return mockedInvoker; } - } - Collections.sort(parts); - return on('&').join(parts); + return new Invoker() { + @Override + public HttpResponse invoke(UrlInvoker urlInvoker) { + return urlInvoker.invoke(); + } + }; } - }), INJECTION_URL_VALUE(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - if (prnfbNotification == null || !prnfbNotification.getInjectionUrl().isPresent()) { - return ""; - } - UrlInvoker urlInvoker = urlInvoker() // - .withUrlParam(prnfbNotification.getInjectionUrl().get()) // - .withMethod(GET)// - .withProxyServer(prnfbNotification.getProxyServer()) // - .withProxyPort(prnfbNotification.getProxyPort()) // - .withProxyUser(prnfbNotification.getProxyUser()) // - .withProxyPassword(prnfbNotification.getProxyPassword())// - .appendBasicAuth(prnfbNotification)// - .withClientKeyStore(clientKeyStore)// - .shouldAcceptAnyCertificate(shouldAcceptAnyCertificate); - createInvoker()// - .invoke(urlInvoker); - String rawResponse = urlInvoker.getResponse().getContent().trim(); - if (prnfbNotification.getInjectionUrlRegexp().isPresent()) { - Matcher m = compile(prnfbNotification.getInjectionUrlRegexp().get()).matcher(rawResponse); - if (!m.find()) { - return ""; - } - if (m.groupCount() == 0) { - return m.group(); + + private static String getOrEmpty( + Map> variables, PrnfbVariable variable) { + if (variables.get(variable) == null) { + return ""; } - return m.group(1); - } else { - return rawResponse; - } - } - }), PULL_REQUEST_ACTION(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return prnfbPullRequestAction.name(); - } - }), PULL_REQUEST_AUTHOR_DISPLAY_NAME(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getAuthor().getUser().getDisplayName(); - } - }), PULL_REQUEST_AUTHOR_EMAIL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getAuthor().getUser().getEmailAddress(); - } - }), PULL_REQUEST_AUTHOR_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getAuthor().getUser().getId() + ""; - } - }), PULL_REQUEST_AUTHOR_NAME(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getAuthor().getUser().getName(); - } - }), PULL_REQUEST_AUTHOR_SLUG(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getAuthor().getUser().getSlug(); - } - }), PULL_REQUEST_COMMENT_ACTION(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return getOrEmpty(variables, PULL_REQUEST_COMMENT_ACTION); - } - }), PULL_REQUEST_COMMENT_TEXT(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return getOrEmpty(variables, PULL_REQUEST_COMMENT_TEXT); - } - }), PULL_REQUEST_DESCRIPTION(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getDescription(); - } - }), PULL_REQUEST_FROM_BRANCH(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getDisplayId(); - } - }), PULL_REQUEST_FROM_HASH(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getLatestCommit(); - } - }), PULL_REQUEST_FROM_HTTP_CLONE_URL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return cloneUrlFromRepository(http, pullRequest.getFromRef().getRepository(), repositoryService, securityService); - } - }), PULL_REQUEST_FROM_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getId(); - } - }), PULL_REQUEST_FROM_REPO_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getRepository().getId() + ""; - } - }), PULL_REQUEST_FROM_REPO_NAME(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getRepository().getName() + ""; - } - }), PULL_REQUEST_FROM_REPO_PROJECT_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getRepository().getProject().getId() + ""; - } - }), PULL_REQUEST_FROM_REPO_PROJECT_KEY(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getRepository().getProject().getKey(); - } - }), PULL_REQUEST_FROM_REPO_SLUG(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getFromRef().getRepository().getSlug() + ""; - } - }), PULL_REQUEST_FROM_SSH_CLONE_URL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return cloneUrlFromRepository(ssh, pullRequest.getFromRef().getRepository(), repositoryService, securityService); - } - }), PULL_REQUEST_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getId() + ""; - } - }), PULL_REQUEST_MERGE_COMMIT(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfsPullRequestAction, - ApplicationUser stashUser, RepositoryService repositoryService, ApplicationPropertiesService propertiesService, - PrnfbNotification prnfsNotification, Map> variables, ClientKeyStore clientKeyStore, - boolean shouldAcceptAnyCertificate, SecurityService securityService) { - return getOrEmpty(variables, PULL_REQUEST_MERGE_COMMIT); - } - }), PULL_REQUEST_PARTICIPANTS_APPROVED_COUNT(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return Integer.toString(newArrayList(filter(pullRequest.getParticipants(), isApproved)).size()); - } - }), PULL_REQUEST_PARTICIPANTS_EMAIL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return iterableToString(transform(pullRequest.getParticipants(), (p) -> p.getUser().getEmailAddress())); - } - }), PULL_REQUEST_REVIEWERS(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return iterableToString(transform(pullRequest.getReviewers(), (p) -> p.getUser().getDisplayName())); - } - }), PULL_REQUEST_REVIEWERS_APPROVED_COUNT(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return Integer.toString(newArrayList(filter(pullRequest.getReviewers(), isApproved)).size()); - } - }), PULL_REQUEST_REVIEWERS_EMAIL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return iterableToString(transform(pullRequest.getReviewers(), (p) -> p.getUser().getEmailAddress())); - } - }), PULL_REQUEST_REVIEWERS_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return iterableToString(transform(pullRequest.getReviewers(), (p) -> Integer.toString(p.getUser().getId()))); - } - }), PULL_REQUEST_REVIEWERS_SLUG(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return iterableToString(transform(pullRequest.getReviewers(), (p) -> p.getUser().getSlug())); + return variables.get(variable).get(); } - }), PULL_REQUEST_STATE(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getState().name(); - } - }), PULL_REQUEST_TITLE(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getTitle(); - } - }), PULL_REQUEST_TO_BRANCH(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getDisplayId(); - } - }), PULL_REQUEST_TO_HASH(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getLatestCommit(); - } - }), PULL_REQUEST_TO_HTTP_CLONE_URL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return cloneUrlFromRepository(http, pullRequest.getToRef().getRepository(), repositoryService, securityService); - } - }), PULL_REQUEST_TO_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getId(); - } - }), PULL_REQUEST_TO_REPO_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getRepository().getId() + ""; - } - }), PULL_REQUEST_TO_REPO_NAME(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getRepository().getName() + ""; - } - }), PULL_REQUEST_TO_REPO_PROJECT_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getRepository().getProject().getId() + ""; - } - }), PULL_REQUEST_TO_REPO_PROJECT_KEY(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getRepository().getProject().getKey(); - } - }), PULL_REQUEST_TO_REPO_SLUG(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getToRef().getRepository().getSlug() + ""; - } - }), PULL_REQUEST_TO_SSH_CLONE_URL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return cloneUrlFromRepository(ssh, pullRequest.getToRef().getRepository(), repositoryService, securityService); - } - }), PULL_REQUEST_URL(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return getPullRequestUrl(propertiesService, pullRequest); + private static String getPullRequestUrl( + ApplicationPropertiesService propertiesService, PullRequest pullRequest) { + return propertiesService.getBaseUrl() + + "/projects/" + + pullRequest.getToRef().getRepository().getProject().getKey() + + "/repos/" + + pullRequest.getToRef().getRepository().getSlug() + + "/pull-requests/" + + pullRequest.getId(); } - }), PULL_REQUEST_USER_DISPLAY_NAME(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return applicationUser.getDisplayName(); - } - }), PULL_REQUEST_USER_EMAIL_ADDRESS(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return applicationUser.getEmailAddress(); - } - }), PULL_REQUEST_USER_ID(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return applicationUser.getId() + ""; - } - }), PULL_REQUEST_USER_NAME(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return applicationUser.getName(); - } - }), PULL_REQUEST_USER_SLUG(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return applicationUser.getSlug(); - } - }), PULL_REQUEST_VERSION(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction prnfbPullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return pullRequest.getVersion() + ""; - } - }), BUTTON_FORM_DATA(new PrnfbVariableResolver() { - @Override - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, - ApplicationPropertiesService propertiesService, PrnfbNotification prnfbNotification, - Map> variables, ClientKeyStore clientKeyStore, boolean shouldAcceptAnyCertificate, - SecurityService securityService) { - return getOrEmpty(variables, BUTTON_FORM_DATA); - } - }); - private static final Predicate isApproved = new Predicate() { - @Override - public boolean apply(PullRequestParticipant input) { - return input.isApproved(); + private static String iterableToString(Iterable slist) { + List sorted = usingToString().sortedCopy(slist); + return on(',').join(sorted); } - }; - private static Invoker mockedInvoker = new Invoker() { - @Override - public HttpResponse invoke(UrlInvoker urlInvoker) { - return urlInvoker.invoke(); + @VisibleForTesting + public static void setInvoker(Invoker invoker) { + PrnfbVariable.mockedInvoker = invoker; } - }; - private static String cloneUrlFromRepository(RepoProtocol protocol, Repository repository, - RepositoryService repositoryService, SecurityService securityService) { - return securityService// - .withPermission(Permission.ADMIN, "cloneUrls")// - .call(new Operation() { - @Override - public String perform() throws RuntimeException { - RepositoryCloneLinksRequest request = new RepositoryCloneLinksRequest.Builder()// - .protocol(protocol.name())// - .repository(repository)// - .build(); - final Set cloneLinks = repositoryService.getCloneLinks(request); - Set allUrls = newTreeSet(); - Iterator itr = cloneLinks.iterator(); - while (itr.hasNext()) { - allUrls.add(itr.next().getHref()); - } - if (allUrls.isEmpty()) { - return ""; - } - return allUrls.iterator().next(); - } - }); - } + private PrnfbVariableResolver resolver; - private static Invoker createInvoker() { - if (mockedInvoker != null) { - return mockedInvoker; + PrnfbVariable(PrnfbVariableResolver resolver) { + this.resolver = resolver; } - return new Invoker() { - @Override - public HttpResponse invoke(UrlInvoker urlInvoker) { - return urlInvoker.invoke(); - } - }; - } - private static String getOrEmpty(Map> variables, PrnfbVariable variable) { - if (variables.get(variable) == null) { - return ""; + public String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService) { + return resolver.resolve( + pullRequest, + pullRequestAction, + applicationUser, + repositoryService, + propertiesService, + prnfbNotification, + variables, + clientKeyStore, + shouldAcceptAnyCertificate, + securityService); } - return variables.get(variable).get(); - } - - private static String getPullRequestUrl(ApplicationPropertiesService propertiesService, PullRequest pullRequest) { - return propertiesService.getBaseUrl() + "/projects/" + pullRequest.getToRef().getRepository().getProject().getKey() - + "/repos/" + pullRequest.getToRef().getRepository().getSlug() + "/pull-requests/" + pullRequest.getId(); - } - - private static String iterableToString(Iterable slist) { - List sorted = usingToString().sortedCopy(slist); - return on(',').join(sorted); - } - - @VisibleForTesting - public static void setInvoker(Invoker invoker) { - PrnfbVariable.mockedInvoker = invoker; - } - - private PrnfbVariableResolver resolver; - - PrnfbVariable(PrnfbVariableResolver resolver) { - this.resolver = resolver; - } - - public String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, - ApplicationUser applicationUser, RepositoryService repositoryService, ApplicationPropertiesService propertiesService, - PrnfbNotification prnfbNotification, Map> variables, ClientKeyStore clientKeyStore, - boolean shouldAcceptAnyCertificate, SecurityService securityService) { - return resolver.resolve(pullRequest, pullRequestAction, applicationUser, repositoryService, propertiesService, - prnfbNotification, variables, clientKeyStore, shouldAcceptAnyCertificate, securityService); - } } diff --git a/src/main/java/se/bjurr/prnfb/service/PrnfbVariableResolver.java b/src/main/java/se/bjurr/prnfb/service/PrnfbVariableResolver.java index b28770fc..f1aed034 100644 --- a/src/main/java/se/bjurr/prnfb/service/PrnfbVariableResolver.java +++ b/src/main/java/se/bjurr/prnfb/service/PrnfbVariableResolver.java @@ -15,8 +15,15 @@ public interface PrnfbVariableResolver { - String resolve(PullRequest pullRequest, PrnfbPullRequestAction pullRequestAction, ApplicationUser applicationUser, - RepositoryService repositoryService, ApplicationPropertiesService propertiesService, - PrnfbNotification prnfbNotification, Map> variables, ClientKeyStore clientKeyStore, - boolean shouldAcceptAnyCertificate, SecurityService securityService); + String resolve( + PullRequest pullRequest, + PrnfbPullRequestAction pullRequestAction, + ApplicationUser applicationUser, + RepositoryService repositoryService, + ApplicationPropertiesService propertiesService, + PrnfbNotification prnfbNotification, + Map> variables, + ClientKeyStore clientKeyStore, + boolean shouldAcceptAnyCertificate, + SecurityService securityService); } diff --git a/src/main/java/se/bjurr/prnfb/service/RepoProtocol.java b/src/main/java/se/bjurr/prnfb/service/RepoProtocol.java index 2bf9f070..72e684bb 100644 --- a/src/main/java/se/bjurr/prnfb/service/RepoProtocol.java +++ b/src/main/java/se/bjurr/prnfb/service/RepoProtocol.java @@ -1,5 +1,6 @@ package se.bjurr.prnfb.service; public enum RepoProtocol { - http, ssh + http, + ssh } diff --git a/src/main/java/se/bjurr/prnfb/service/SettingsService.java b/src/main/java/se/bjurr/prnfb/service/SettingsService.java index 6cc7f62f..9e8b1fa1 100644 --- a/src/main/java/se/bjurr/prnfb/service/SettingsService.java +++ b/src/main/java/se/bjurr/prnfb/service/SettingsService.java @@ -47,337 +47,369 @@ public class SettingsService { - public static final String STORAGE_KEY = "se.bjurr.prnfb.pull-request-notifier-for-bitbucket-3"; - private static Gson gson = new Gson(); - private final Logger logger = LoggerFactory.getLogger(SettingsService.class); - private final PluginSettings pluginSettings; - private final SecurityService securityService; - private final TransactionTemplate transactionTemplate; - - public SettingsService(PluginSettingsFactory pluginSettingsFactory, TransactionTemplate transactionTemplate, - SecurityService securityService) { - this.pluginSettings = pluginSettingsFactory.createGlobalSettings(); - this.transactionTemplate = transactionTemplate; - this.securityService = securityService; - } - - public PrnfbButton addOrUpdateButton(PrnfbButton prnfbButton) { - return inSynchronizedTransaction(new TransactionCallback() { - @Override - public PrnfbButton doInTransaction() { - return doAddOrUpdateButton(prnfbButton); - } - }); - } - - public PrnfbNotification addOrUpdateNotification(PrnfbNotification prnfbNotification) throws ValidationException { - return inSynchronizedTransaction(new TransactionCallback() { - @Override - public PrnfbNotification doInTransaction() { - try { - return doAddOrUpdateNotification(prnfbNotification); - } catch (ValidationException e) { - propagate(e); - } - return null; - } - }); - } - - public void deleteButton(UUID uuid) { - inSynchronizedTransaction(new TransactionCallback() { - @Override - public Void doInTransaction() { - doDeleteButton(uuid); - return null; - } - }); - } - - public void deleteNotification(UUID uuid) { - inSynchronizedTransaction(new TransactionCallback() { - @Override - public Void doInTransaction() { - doDeleteNotification(uuid); - return null; - } - }); - } - - public Optional findButton(UUID uuid) { - return tryFind(getPrnfbSettings().getButtons(), withUuid(uuid)); - } - - public Optional findNotification(UUID notificationUuid) { - return tryFind(getPrnfbSettings().getNotifications(), withUuid(notificationUuid)); - } - - public PrnfbButton getButton(UUID buttionUuid) { - Optional foundOpt = findButton(buttionUuid); - if (!foundOpt.isPresent()) { - throw new RuntimeException(buttionUuid + " not fond in:\n" + on('\n').join(getButtons())); + public static final String STORAGE_KEY = "se.bjurr.prnfb.pull-request-notifier-for-bitbucket-3"; + private static Gson gson = new Gson(); + private final Logger logger = LoggerFactory.getLogger(SettingsService.class); + private final PluginSettings pluginSettings; + private final SecurityService securityService; + private final TransactionTemplate transactionTemplate; + + public SettingsService( + PluginSettingsFactory pluginSettingsFactory, + TransactionTemplate transactionTemplate, + SecurityService securityService) { + this.pluginSettings = pluginSettingsFactory.createGlobalSettings(); + this.transactionTemplate = transactionTemplate; + this.securityService = securityService; + } + + public PrnfbButton addOrUpdateButton(PrnfbButton prnfbButton) { + return inSynchronizedTransaction( + new TransactionCallback() { + @Override + public PrnfbButton doInTransaction() { + return doAddOrUpdateButton(prnfbButton); + } + }); } - return foundOpt.get(); - } - - public List getButtons() { - return getPrnfbSettings().getButtons(); - } - - public List getButtons(String projectKey) { - List found = newArrayList(); - for (PrnfbButton candidate : getPrnfbSettings().getButtons()) { - if (candidate.getProjectKey().isPresent() && candidate.getProjectKey().get().equals(projectKey)) { - found.add(candidate); - } + + public PrnfbNotification addOrUpdateNotification(PrnfbNotification prnfbNotification) + throws ValidationException { + return inSynchronizedTransaction( + new TransactionCallback() { + @Override + public PrnfbNotification doInTransaction() { + try { + return doAddOrUpdateNotification(prnfbNotification); + } catch (ValidationException e) { + propagate(e); + } + return null; + } + }); } - return found; - } - - public List getButtons(String projectKey, String repositorySlug) { - List found = newArrayList(); - for (PrnfbButton candidate : getPrnfbSettings().getButtons()) { - if (candidate.getProjectKey().isPresent() && candidate.getProjectKey().get().equals(projectKey)// - && candidate.getRepositorySlug().isPresent() && candidate.getRepositorySlug().get().equals(repositorySlug)) { - found.add(candidate); - } + + public void deleteButton(UUID uuid) { + inSynchronizedTransaction( + new TransactionCallback() { + @Override + public Void doInTransaction() { + doDeleteButton(uuid); + return null; + } + }); } - return found; - } - - public PrnfbNotification getNotification(UUID notificationUuid) { - return find(getPrnfbSettings().getNotifications(), withUuid(notificationUuid)); - } - - public List getNotifications() { - return getPrnfbSettings().getNotifications(); - } - - public List getNotifications(String projectKey) { - List found = newArrayList(); - for (PrnfbNotification candidate : getPrnfbSettings().getNotifications()) { - if (candidate.getProjectKey().isPresent() && candidate.getProjectKey().get().equals(projectKey)) { - found.add(candidate); - } + + public void deleteNotification(UUID uuid) { + inSynchronizedTransaction( + new TransactionCallback() { + @Override + public Void doInTransaction() { + doDeleteNotification(uuid); + return null; + } + }); } - return found; - } - - public List getNotifications(String projectKey, String repositorySlug) { - List found = newArrayList(); - for (PrnfbNotification candidate : getPrnfbSettings().getNotifications()) { - if (candidate.getProjectKey().isPresent() && candidate.getProjectKey().get().equals(projectKey)// - && candidate.getRepositorySlug().isPresent() && candidate.getRepositorySlug().get().equals(repositorySlug)) { - found.add(candidate); - } + + public Optional findButton(UUID uuid) { + return tryFind(getPrnfbSettings().getButtons(), withUuid(uuid)); } - return found; - } - - @VisibleForTesting - public PrnfbSettings getPrnfbSettings() { - return inSynchronizedTransaction(new TransactionCallback() { - @Override - public PrnfbSettings doInTransaction() { - return doGetPrnfbSettings(); - } - }); - } - - public PrnfbSettingsData getPrnfbSettingsData() { - return getPrnfbSettings().getPrnfbSettingsData(); - } - - public void setPrnfbSettingsData(PrnfbSettingsData prnfbSettingsData) { - inSynchronizedTransaction(new TransactionCallback() { - @Override - public Void doInTransaction() { - PrnfbSettings oldSettings = doGetPrnfbSettings(); - PrnfbSettings newPrnfbSettings = prnfbSettingsBuilder(oldSettings)// - .setPrnfbSettingsData(prnfbSettingsData)// - .build(); - doSetPrnfbSettings(newPrnfbSettings); - return null; - } - }); - } - - private PrnfbButton doAddOrUpdateButton(PrnfbButton prnfbButton) { - if (findButton(prnfbButton.getUuid()).isPresent()) { - doDeleteButton(prnfbButton.getUuid()); + + public Optional findNotification(UUID notificationUuid) { + return tryFind(getPrnfbSettings().getNotifications(), withUuid(notificationUuid)); } - PrnfbSettings originalSettings = doGetPrnfbSettings(); - PrnfbSettings updated = prnfbSettingsBuilder(originalSettings)// - .withButton(prnfbButton)// - .build(); + public PrnfbButton getButton(UUID buttionUuid) { + Optional foundOpt = findButton(buttionUuid); + if (!foundOpt.isPresent()) { + throw new RuntimeException(buttionUuid + " not fond in:\n" + on('\n').join(getButtons())); + } + return foundOpt.get(); + } - doSetPrnfbSettings(updated); - return prnfbButton; - } + public List getButtons() { + return getPrnfbSettings().getButtons(); + } - private PrnfbNotification doAddOrUpdateNotification(PrnfbNotification prnfbNotification) throws ValidationException { - if (findNotification(prnfbNotification.getUuid()).isPresent()) { - doDeleteNotification(prnfbNotification.getUuid()); + public List getButtons(String projectKey) { + List found = newArrayList(); + for (PrnfbButton candidate : getPrnfbSettings().getButtons()) { + if (candidate.getProjectKey().isPresent() + && candidate.getProjectKey().get().equals(projectKey)) { + found.add(candidate); + } + } + return found; } - PrnfbSettings originalSettings = doGetPrnfbSettings(); - PrnfbSettings updated = prnfbSettingsBuilder(originalSettings)// - .withNotification(prnfbNotification)// - .build(); - - doSetPrnfbSettings(updated); - return prnfbNotification; - } - - private void doDeleteButton(UUID uuid) { - PrnfbSettings originalSettings = doGetPrnfbSettings(); - List keep = newArrayList(filter(originalSettings.getButtons(), not(withUuid(uuid)))); - PrnfbSettings withoutDeleted = prnfbSettingsBuilder(originalSettings)// - .setButtons(keep)// - .build(); - doSetPrnfbSettings(withoutDeleted); - } - - private void doDeleteNotification(UUID uuid) { - PrnfbSettings originalSettings = doGetPrnfbSettings(); - List keep = newArrayList(filter(originalSettings.getNotifications(), not(withUuid(uuid)))); - PrnfbSettings withoutDeleted = prnfbSettingsBuilder(originalSettings)// - .setNotifications(keep)// - .build(); - doSetPrnfbSettings(withoutDeleted); - } - - private PrnfbSettings doGetPrnfbSettings() { - Object storedSettings = this.pluginSettings.get(STORAGE_KEY); - if (storedSettings == null) { - this.logger.info("No settings found for " + STORAGE_KEY + ", looking for legacy settings."); - if (this.pluginSettings.get(se.bjurr.prnfb.settings.legacy.SettingsStorage.STORAGE_KEY) != null - || this.pluginSettings.get(se.bjurr.prnfb.settings.legacy.SettingsStorage.STORAGE_KEY_PRNFS) != null) { - try { - this.logger.info("Using legacy settings."); - se.bjurr.prnfb.settings.legacy.PrnfbSettings legacySettings = SettingsStorage - .getPrnfbSettings(this.pluginSettings); - PrnfbSettings fromLegacy = settingsFromLegacy(legacySettings); - doSetPrnfbSettings(fromLegacy); - storedSettings = this.pluginSettings.get(STORAGE_KEY); - } catch (Exception e) { - this.logger.error("", e); + public List getButtons(String projectKey, String repositorySlug) { + List found = newArrayList(); + for (PrnfbButton candidate : getPrnfbSettings().getButtons()) { + if (candidate.getProjectKey().isPresent() + && candidate.getProjectKey().get().equals(projectKey) // + && candidate.getRepositorySlug().isPresent() + && candidate.getRepositorySlug().get().equals(repositorySlug)) { + found.add(candidate); + } } - } else { - this.logger.info("Creating new default settings."); - return prnfbSettingsBuilder()// - .setPrnfbSettingsData(// - prnfbSettingsDataBuilder()// - .setAdminRestriction(USER_LEVEL.ADMIN)// - .build())// - .build(); - } + return found; } - return gson.fromJson(storedSettings.toString(), PrnfbSettings.class); - } - - private void doSetPrnfbSettings(PrnfbSettings PrnfbSettings) { - String data = gson.toJson(PrnfbSettings); - this.pluginSettings.put(STORAGE_KEY, data); - } - - private synchronized T inSynchronizedTransaction(TransactionCallback transactionCallback) { - return this.securityService// - .withPermission(ADMIN, "Getting config")// - .call(new Operation() { - @Override - public T perform() throws RuntimeException { - return SettingsService.this.transactionTemplate.execute(transactionCallback); - } - }); - } - - private PrnfbSettings settingsFromLegacy(se.bjurr.prnfb.settings.legacy.PrnfbSettings oldSettings) { - String ks = oldSettings.getKeyStore().orNull(); - String ksp = oldSettings.getKeyStorePassword().orNull(); - String kst = oldSettings.getKeyStoreType(); - USER_LEVEL adminRestr = USER_LEVEL.SYSTEM_ADMIN; - if (oldSettings.isAdminsAllowed()) { - adminRestr = USER_LEVEL.ADMIN; + + public PrnfbNotification getNotification(UUID notificationUuid) { + return find(getPrnfbSettings().getNotifications(), withUuid(notificationUuid)); + } + + public List getNotifications() { + return getPrnfbSettings().getNotifications(); + } + + public List getNotifications(String projectKey) { + List found = newArrayList(); + for (PrnfbNotification candidate : getPrnfbSettings().getNotifications()) { + if (candidate.getProjectKey().isPresent() + && candidate.getProjectKey().get().equals(projectKey)) { + found.add(candidate); + } + } + return found; + } + + public List getNotifications(String projectKey, String repositorySlug) { + List found = newArrayList(); + for (PrnfbNotification candidate : getPrnfbSettings().getNotifications()) { + if (candidate.getProjectKey().isPresent() + && candidate.getProjectKey().get().equals(projectKey) // + && candidate.getRepositorySlug().isPresent() + && candidate.getRepositorySlug().get().equals(repositorySlug)) { + found.add(candidate); + } + } + return found; + } + + @VisibleForTesting + public PrnfbSettings getPrnfbSettings() { + return inSynchronizedTransaction( + new TransactionCallback() { + @Override + public PrnfbSettings doInTransaction() { + return doGetPrnfbSettings(); + } + }); } - if (oldSettings.isUsersAllowed()) { - adminRestr = USER_LEVEL.EVERYONE; + + public PrnfbSettingsData getPrnfbSettingsData() { + return getPrnfbSettings().getPrnfbSettingsData(); } - boolean shouldAcceptAnyCertificate = false; - - List newButtons = newArrayList(); - for (se.bjurr.prnfb.settings.legacy.PrnfbButton oldButton : oldSettings.getButtons()) { - USER_LEVEL userLevel = USER_LEVEL.SYSTEM_ADMIN; - if (oldButton.getVisibility() == BUTTON_VISIBILITY.ADMIN) { - userLevel = USER_LEVEL.ADMIN; - } - if (oldButton.getVisibility() == BUTTON_VISIBILITY.EVERYONE) { - userLevel = USER_LEVEL.EVERYONE; - } - newButtons.add(new PrnfbButton(UUID.randomUUID(), oldButton.getTitle(), userLevel, ON_OR_OFF.off, null, null, null)); + public void setPrnfbSettingsData(PrnfbSettingsData prnfbSettingsData) { + inSynchronizedTransaction( + new TransactionCallback() { + @Override + public Void doInTransaction() { + PrnfbSettings oldSettings = doGetPrnfbSettings(); + PrnfbSettings newPrnfbSettings = + prnfbSettingsBuilder(oldSettings) // + .setPrnfbSettingsData(prnfbSettingsData) // + .build(); + doSetPrnfbSettings(newPrnfbSettings); + return null; + } + }); } - List newNotifications = newArrayList(); - for (se.bjurr.prnfb.settings.legacy.PrnfbNotification oldNotification : oldSettings.getNotifications()) { - try { - PrnfbNotificationBuilder builder = prnfbNotificationBuilder()// - .withFilterRegexp(oldNotification.getFilterRegexp().orNull())// - .withFilterString(oldNotification.getFilterString().orNull())// - .withInjectionUrl(oldNotification.getInjectionUrl().orNull())// - .withInjectionUrlRegexp(oldNotification.getInjectionUrlRegexp().orNull())// - .withMethod(oldNotification.getMethod())// - .withName(oldNotification.getName())// - .withPassword(oldNotification.getPassword().orNull())// - .withPostContent(oldNotification.getPostContent().orNull())// - .withProxyPassword(oldNotification.getProxyPassword().orNull())// - .withProxyPort(oldNotification.getProxyPort())// - .withProxyServer(oldNotification.getProxyServer().orNull())// - .withProxyUser(oldNotification.getProxyUser().orNull())// - .withTriggerIfCanMerge(TRIGGER_IF_MERGE.valueOf(oldNotification.getTriggerIfCanMerge().name()))// - .withUrl(oldNotification.getUrl())// - .withUser(oldNotification.getUser().orNull()); - - for (Header h : oldNotification.getHeaders()) { - builder.withHeader(h.getName(), h.getValue()); + private PrnfbButton doAddOrUpdateButton(PrnfbButton prnfbButton) { + if (findButton(prnfbButton.getUuid()).isPresent()) { + doDeleteButton(prnfbButton.getUuid()); } - for (PullRequestState t : oldNotification.getTriggerIgnoreStateList()) { - builder.withTriggerIgnoreState(t); + PrnfbSettings originalSettings = doGetPrnfbSettings(); + PrnfbSettings updated = + prnfbSettingsBuilder(originalSettings) // + .withButton(prnfbButton) // + .build(); + + doSetPrnfbSettings(updated); + return prnfbButton; + } + + private PrnfbNotification doAddOrUpdateNotification(PrnfbNotification prnfbNotification) + throws ValidationException { + if (findNotification(prnfbNotification.getUuid()).isPresent()) { + doDeleteNotification(prnfbNotification.getUuid()); } - for (PrnfbPullRequestAction t : oldNotification.getTriggers()) { - builder.withTrigger(t); + PrnfbSettings originalSettings = doGetPrnfbSettings(); + PrnfbSettings updated = + prnfbSettingsBuilder(originalSettings) // + .withNotification(prnfbNotification) // + .build(); + + doSetPrnfbSettings(updated); + return prnfbNotification; + } + + private void doDeleteButton(UUID uuid) { + PrnfbSettings originalSettings = doGetPrnfbSettings(); + List keep = + newArrayList(filter(originalSettings.getButtons(), not(withUuid(uuid)))); + PrnfbSettings withoutDeleted = + prnfbSettingsBuilder(originalSettings) // + .setButtons(keep) // + .build(); + doSetPrnfbSettings(withoutDeleted); + } + + private void doDeleteNotification(UUID uuid) { + PrnfbSettings originalSettings = doGetPrnfbSettings(); + List keep = + newArrayList(filter(originalSettings.getNotifications(), not(withUuid(uuid)))); + PrnfbSettings withoutDeleted = + prnfbSettingsBuilder(originalSettings) // + .setNotifications(keep) // + .build(); + doSetPrnfbSettings(withoutDeleted); + } + + private PrnfbSettings doGetPrnfbSettings() { + Object storedSettings = this.pluginSettings.get(STORAGE_KEY); + if (storedSettings == null) { + this.logger.info("No settings found for " + STORAGE_KEY + ", looking for legacy settings."); + if (this.pluginSettings.get(se.bjurr.prnfb.settings.legacy.SettingsStorage.STORAGE_KEY) + != null + || this.pluginSettings.get( + se.bjurr.prnfb.settings.legacy.SettingsStorage.STORAGE_KEY_PRNFS) + != null) { + try { + this.logger.info("Using legacy settings."); + se.bjurr.prnfb.settings.legacy.PrnfbSettings legacySettings = + SettingsStorage.getPrnfbSettings(this.pluginSettings); + PrnfbSettings fromLegacy = settingsFromLegacy(legacySettings); + doSetPrnfbSettings(fromLegacy); + storedSettings = this.pluginSettings.get(STORAGE_KEY); + } catch (Exception e) { + this.logger.error("", e); + } + } else { + this.logger.info("Creating new default settings."); + return prnfbSettingsBuilder() // + .setPrnfbSettingsData( // + prnfbSettingsDataBuilder() // + .setAdminRestriction(USER_LEVEL.ADMIN) // + .build()) // + .build(); + } } + return gson.fromJson(storedSettings.toString(), PrnfbSettings.class); + } - newNotifications.add(builder.build()); - } catch (ValidationException e) { - this.logger.error("", e); - } + private void doSetPrnfbSettings(PrnfbSettings PrnfbSettings) { + String data = gson.toJson(PrnfbSettings); + this.pluginSettings.put(STORAGE_KEY, data); } - return prnfbSettingsBuilder()// - .setPrnfbSettingsData(// - prnfbSettingsDataBuilder()// - .setAdminRestriction(adminRestr)// - .setKeyStore(ks)// - .setKeyStorePassword(ksp)// - .setKeyStoreType(kst)// - .setShouldAcceptAnyCertificate(shouldAcceptAnyCertificate)// - .build())// - .setButtons(newButtons)// - .setNotifications(newNotifications)// - .build(); - } - - private Predicate withUuid(UUID uuid) { - return new Predicate() { - @Override - public boolean apply(HasUuid input) { - return input.getUuid().equals(uuid); - } - }; - } + private synchronized T inSynchronizedTransaction(TransactionCallback transactionCallback) { + return this.securityService // + .withPermission(ADMIN, "Getting config") // + .call( + new Operation() { + @Override + public T perform() throws RuntimeException { + return SettingsService.this.transactionTemplate.execute(transactionCallback); + } + }); + } + + private PrnfbSettings settingsFromLegacy( + se.bjurr.prnfb.settings.legacy.PrnfbSettings oldSettings) { + String ks = oldSettings.getKeyStore().orNull(); + String ksp = oldSettings.getKeyStorePassword().orNull(); + String kst = oldSettings.getKeyStoreType(); + USER_LEVEL adminRestr = USER_LEVEL.SYSTEM_ADMIN; + if (oldSettings.isAdminsAllowed()) { + adminRestr = USER_LEVEL.ADMIN; + } + if (oldSettings.isUsersAllowed()) { + adminRestr = USER_LEVEL.EVERYONE; + } + + boolean shouldAcceptAnyCertificate = false; + + List newButtons = newArrayList(); + for (se.bjurr.prnfb.settings.legacy.PrnfbButton oldButton : oldSettings.getButtons()) { + USER_LEVEL userLevel = USER_LEVEL.SYSTEM_ADMIN; + if (oldButton.getVisibility() == BUTTON_VISIBILITY.ADMIN) { + userLevel = USER_LEVEL.ADMIN; + } + if (oldButton.getVisibility() == BUTTON_VISIBILITY.EVERYONE) { + userLevel = USER_LEVEL.EVERYONE; + } + newButtons.add( + new PrnfbButton( + UUID.randomUUID(), oldButton.getTitle(), userLevel, ON_OR_OFF.off, null, null, null)); + } + List newNotifications = newArrayList(); + for (se.bjurr.prnfb.settings.legacy.PrnfbNotification oldNotification : + oldSettings.getNotifications()) { + try { + PrnfbNotificationBuilder builder = + prnfbNotificationBuilder() // + .withFilterRegexp(oldNotification.getFilterRegexp().orNull()) // + .withFilterString(oldNotification.getFilterString().orNull()) // + .withInjectionUrl(oldNotification.getInjectionUrl().orNull()) // + .withInjectionUrlRegexp(oldNotification.getInjectionUrlRegexp().orNull()) // + .withMethod(oldNotification.getMethod()) // + .withName(oldNotification.getName()) // + .withPassword(oldNotification.getPassword().orNull()) // + .withPostContent(oldNotification.getPostContent().orNull()) // + .withProxyPassword(oldNotification.getProxyPassword().orNull()) // + .withProxyPort(oldNotification.getProxyPort()) // + .withProxyServer(oldNotification.getProxyServer().orNull()) // + .withProxyUser(oldNotification.getProxyUser().orNull()) // + .withTriggerIfCanMerge( + TRIGGER_IF_MERGE.valueOf(oldNotification.getTriggerIfCanMerge().name())) // + .withUrl(oldNotification.getUrl()) // + .withUser(oldNotification.getUser().orNull()); + + for (Header h : oldNotification.getHeaders()) { + builder.withHeader(h.getName(), h.getValue()); + } + + for (PullRequestState t : oldNotification.getTriggerIgnoreStateList()) { + builder.withTriggerIgnoreState(t); + } + + for (PrnfbPullRequestAction t : oldNotification.getTriggers()) { + builder.withTrigger(t); + } + + newNotifications.add(builder.build()); + } catch (ValidationException e) { + this.logger.error("", e); + } + } + + return prnfbSettingsBuilder() // + .setPrnfbSettingsData( // + prnfbSettingsDataBuilder() // + .setAdminRestriction(adminRestr) // + .setKeyStore(ks) // + .setKeyStorePassword(ksp) // + .setKeyStoreType(kst) // + .setShouldAcceptAnyCertificate(shouldAcceptAnyCertificate) // + .build()) // + .setButtons(newButtons) // + .setNotifications(newNotifications) // + .build(); + } + + private Predicate withUuid(UUID uuid) { + return new Predicate() { + @Override + public boolean apply(HasUuid input) { + return input.getUuid().equals(uuid); + } + }; + } } diff --git a/src/main/java/se/bjurr/prnfb/service/UserCheckService.java b/src/main/java/se/bjurr/prnfb/service/UserCheckService.java index ff302e38..26d30180 100644 --- a/src/main/java/se/bjurr/prnfb/service/UserCheckService.java +++ b/src/main/java/se/bjurr/prnfb/service/UserCheckService.java @@ -33,142 +33,153 @@ import se.bjurr.prnfb.settings.USER_LEVEL; public class UserCheckService { - private static final Logger LOG = getLogger(UserCheckService.class); - private final PermissionService permissionService; - private final ProjectService projectService; - private final RepositoryService repositoryService; - private final SecurityService securityService; - private final SettingsService settingsService; - private final UserManager userManager; - - public UserCheckService(PermissionService permissionService, UserManager userManager, SettingsService settingsService, - RepositoryService repositoryService, ProjectService projectService, SecurityService securityService) { - this.userManager = userManager; - this.settingsService = settingsService; - this.permissionService = permissionService; - this.projectService = projectService; - this.repositoryService = repositoryService; - this.securityService = securityService; - } - - public Iterable filterAllowed(List buttons) { - Iterable allowedButtons = filter(buttons, new Predicate() { - @Override - public boolean apply(PrnfbButton input) { - return isAllowedUseButton(input); - } - }); - return allowedButtons; - } - - @VisibleForTesting - private Project getProject(String projectKey) { - try { - return securityService// - .withPermission(SYS_ADMIN, "Getting project")// - .call(new Operation() { - @Override - public Project perform() throws Exception { - return projectService.getByKey(projectKey); - } - }); - } catch (Exception e) { - throw propagate(e); + private static final Logger LOG = getLogger(UserCheckService.class); + private final PermissionService permissionService; + private final ProjectService projectService; + private final RepositoryService repositoryService; + private final SecurityService securityService; + private final SettingsService settingsService; + private final UserManager userManager; + + public UserCheckService( + PermissionService permissionService, + UserManager userManager, + SettingsService settingsService, + RepositoryService repositoryService, + ProjectService projectService, + SecurityService securityService) { + this.userManager = userManager; + this.settingsService = settingsService; + this.permissionService = permissionService; + this.projectService = projectService; + this.repositoryService = repositoryService; + this.securityService = securityService; } - } - - @VisibleForTesting - Repository getRepo(String projectKey, String repositorySlug) { - try { - return securityService// - .withPermission(SYS_ADMIN, "Getting repo")// - .call(new Operation() { - @Override - public Repository perform() throws Exception { - return repositoryService.getBySlug(projectKey, repositorySlug); - } - }); - } catch (Exception e) { - throw propagate(e); + + public Iterable filterAllowed(List buttons) { + Iterable allowedButtons = + filter( + buttons, + new Predicate() { + @Override + public boolean apply(PrnfbButton input) { + return isAllowedUseButton(input); + } + }); + return allowedButtons; + } + + @VisibleForTesting + private Project getProject(String projectKey) { + try { + return securityService // + .withPermission(SYS_ADMIN, "Getting project") // + .call( + new Operation() { + @Override + public Project perform() throws Exception { + return projectService.getByKey(projectKey); + } + }); + } catch (Exception e) { + throw propagate(e); + } } - } - public boolean isAdmin(UserKey userKey, String projectKey, String repositorySlug) { - boolean isAdmin = userManager.isAdmin(userKey); - if (isAdmin) { - return isAdmin; + @VisibleForTesting + Repository getRepo(String projectKey, String repositorySlug) { + try { + return securityService // + .withPermission(SYS_ADMIN, "Getting repo") // + .call( + new Operation() { + @Override + public Repository perform() throws Exception { + return repositoryService.getBySlug(projectKey, repositorySlug); + } + }); + } catch (Exception e) { + throw propagate(e); + } } - projectKey = emptyToNull(projectKey); - repositorySlug = emptyToNull(repositorySlug); + public boolean isAdmin(UserKey userKey, String projectKey, String repositorySlug) { + boolean isAdmin = userManager.isAdmin(userKey); + if (isAdmin) { + return isAdmin; + } - if (projectKey != null && repositorySlug == null) { - Project project = getProject(projectKey); - if (project == null) { - LOG.error("Button with project " + projectKey + " configured. But no such project exists!"); + projectKey = emptyToNull(projectKey); + repositorySlug = emptyToNull(repositorySlug); + + if (projectKey != null && repositorySlug == null) { + Project project = getProject(projectKey); + if (project == null) { + LOG.error("Button with project " + projectKey + " configured. But no such project exists!"); + return false; + } + boolean isAllowed = permissionService.hasProjectPermission(project, PROJECT_ADMIN); + if (isAllowed) { + return true; + } + } + + if (projectKey != null && repositorySlug != null) { + Repository repository = getRepo(projectKey, repositorySlug); + if (repository == null) { + LOG.error( + "Button with project " + + projectKey + + " and repo " + + repositorySlug + + " configured. But no such repo exists!"); + return false; + } + return permissionService.hasRepositoryPermission(repository, REPO_ADMIN); + } return false; - } - boolean isAllowed = permissionService.hasProjectPermission(project, PROJECT_ADMIN); - if (isAllowed) { - return true; - } } - if (projectKey != null && repositorySlug != null) { - Repository repository = getRepo(projectKey, repositorySlug); - if (repository == null) { - LOG.error( - "Button with project " + projectKey + " and repo " + repositorySlug + " configured. But no such repo exists!"); - return false; - } - return permissionService.hasRepositoryPermission(repository, REPO_ADMIN); + /** null if global. */ + public boolean isAdminAllowed(@Nullable String projectKey, @Nullable String repositorySlug) { + final UserProfile user = userManager.getRemoteUser(); + if (user == null) { + return false; + } + USER_LEVEL adminRestriction = settingsService.getPrnfbSettingsData().getAdminRestriction(); + return isAdminAllowed(adminRestriction, projectKey, repositorySlug); } - return false; - } - - /** - * null if global. - */ - public boolean isAdminAllowed(@Nullable String projectKey, @Nullable String repositorySlug) { - final UserProfile user = userManager.getRemoteUser(); - if (user == null) { - return false; + + private boolean isAdminAllowed( + USER_LEVEL adminRestriction, @Nullable String projectKey, @Nullable String repositorySlug) { + UserKey userKey = userManager.getRemoteUser().getUserKey(); + boolean isAdmin = isAdmin(userKey, projectKey, repositorySlug); + boolean isSystemAdmin = isSystemAdmin(userKey); + return isAdminAllowedCheck(adminRestriction, isAdmin, isSystemAdmin); } - USER_LEVEL adminRestriction = settingsService.getPrnfbSettingsData().getAdminRestriction(); - return isAdminAllowed(adminRestriction, projectKey, repositorySlug); - } - - private boolean isAdminAllowed(USER_LEVEL adminRestriction, @Nullable String projectKey, - @Nullable String repositorySlug) { - UserKey userKey = userManager.getRemoteUser().getUserKey(); - boolean isAdmin = isAdmin(userKey, projectKey, repositorySlug); - boolean isSystemAdmin = isSystemAdmin(userKey); - return isAdminAllowedCheck(adminRestriction, isAdmin, isSystemAdmin); - } - - boolean isAdminAllowedCheck(USER_LEVEL userLevel, boolean isAdmin, boolean isSystemAdmin) { - return userLevel == EVERYONE // - || isSystemAdmin // - || isAdmin && userLevel == ADMIN; - } - - public boolean isAllowedUseButton(PrnfbButton candidate) { - return isAdminAllowed(// - candidate.getUserLevel(), // - candidate.getProjectKey().orNull(), // - candidate.getRepositorySlug().orNull()); - } - - public boolean isSystemAdmin(UserKey userKey) { - return userManager.isSystemAdmin(userKey); - } - - public boolean isViewAllowed() { - UserProfile user = userManager.getRemoteUser(); - if (user == null) { - return false; + + boolean isAdminAllowedCheck(USER_LEVEL userLevel, boolean isAdmin, boolean isSystemAdmin) { + return userLevel == EVERYONE // + || isSystemAdmin // + || isAdmin && userLevel == ADMIN; + } + + public boolean isAllowedUseButton(PrnfbButton candidate) { + return isAdminAllowed( // + candidate.getUserLevel(), // + candidate.getProjectKey().orNull(), // + candidate.getRepositorySlug().orNull()); } - return true; - } + public boolean isSystemAdmin(UserKey userKey) { + return userManager.isSystemAdmin(userKey); + } + + public boolean isViewAllowed() { + UserProfile user = userManager.getRemoteUser(); + if (user == null) { + return false; + } + return true; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/HasUuid.java b/src/main/java/se/bjurr/prnfb/settings/HasUuid.java index 8f20cdf5..4298d6e9 100644 --- a/src/main/java/se/bjurr/prnfb/settings/HasUuid.java +++ b/src/main/java/se/bjurr/prnfb/settings/HasUuid.java @@ -4,6 +4,5 @@ public interface HasUuid { - UUID getUuid(); - + UUID getUuid(); } diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbButton.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbButton.java index f1429083..35d7f713 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbButton.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbButton.java @@ -13,132 +13,150 @@ public class PrnfbButton implements HasUuid { - private final ON_OR_OFF confirmation; - private final String name; - private final String projectKey; - private final String repositorySlug; - private final String buttonForm; - private final USER_LEVEL userLevel; - private final UUID uuid; - - public PrnfbButton(UUID uuid, String name, USER_LEVEL userLevel, ON_OR_OFF confirmation, String projectKey, - String repositorySlug, String buttonForm) { - this.uuid = firstNonNull(uuid, randomUUID()); - this.name = name; - this.userLevel = userLevel; - this.confirmation = confirmation; - this.repositorySlug = emptyToNull(repositorySlug); - this.projectKey = emptyToNull(projectKey); - this.buttonForm = emptyToNull(buttonForm); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + private final ON_OR_OFF confirmation; + private final String name; + private final String projectKey; + private final String repositorySlug; + private final String buttonForm; + private final USER_LEVEL userLevel; + private final UUID uuid; + + public PrnfbButton( + UUID uuid, + String name, + USER_LEVEL userLevel, + ON_OR_OFF confirmation, + String projectKey, + String repositorySlug, + String buttonForm) { + this.uuid = firstNonNull(uuid, randomUUID()); + this.name = name; + this.userLevel = userLevel; + this.confirmation = confirmation; + this.repositorySlug = emptyToNull(repositorySlug); + this.projectKey = emptyToNull(projectKey); + this.buttonForm = emptyToNull(buttonForm); } - if (obj == null) { - return false; + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PrnfbButton other = (PrnfbButton) obj; + if (this.projectKey == null) { + if (other.projectKey != null) { + return false; + } + } else if (!this.projectKey.equals(other.projectKey)) { + return false; + } + if (this.repositorySlug == null) { + if (other.repositorySlug != null) { + return false; + } + } else if (!this.repositorySlug.equals(other.repositorySlug)) { + return false; + } + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.buttonForm == null) { + if (other.buttonForm != null) { + return false; + } + } else if (!this.buttonForm.equals(other.buttonForm)) { + return false; + } + if (this.userLevel != other.userLevel) { + return false; + } + if (this.uuid == null) { + if (other.uuid != null) { + return false; + } + } else if (!this.uuid.equals(other.uuid)) { + return false; + } + if (this.confirmation == null) { + if (other.confirmation != null) { + return false; + } + } else if (!this.confirmation.equals(other.confirmation)) { + return false; + } + return true; } - if (getClass() != obj.getClass()) { - return false; + + public ON_OR_OFF getConfirmation() { + return this.confirmation; } - PrnfbButton other = (PrnfbButton) obj; - if (this.projectKey == null) { - if (other.projectKey != null) { - return false; - } - } else if (!this.projectKey.equals(other.projectKey)) { - return false; + + public String getName() { + return this.name; } - if (this.repositorySlug == null) { - if (other.repositorySlug != null) { - return false; - } - } else if (!this.repositorySlug.equals(other.repositorySlug)) { - return false; + + public String getButtonForm() { + return this.buttonForm; } - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; + + public Optional getProjectKey() { + return fromNullable(this.projectKey); } - if (this.buttonForm == null) { - if (other.buttonForm != null) { - return false; - } - } else if (!this.buttonForm.equals(other.buttonForm)) { - return false; + + public Optional getRepositorySlug() { + return fromNullable(this.repositorySlug); } - if (this.userLevel != other.userLevel) { - return false; + + public USER_LEVEL getUserLevel() { + return this.userLevel; } - if (this.uuid == null) { - if (other.uuid != null) { - return false; - } - } else if (!this.uuid.equals(other.uuid)) { - return false; + + @Override + public UUID getUuid() { + return this.uuid; } - if (this.confirmation == null) { - if (other.confirmation != null) { - return false; - } - } else if (!this.confirmation.equals(other.confirmation)) { - return false; + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); + result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.userLevel == null) ? 0 : this.userLevel.hashCode()); + result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); + result = prime * result + ((this.confirmation == null) ? 0 : this.confirmation.hashCode()); + result = prime * result + ((this.buttonForm == null) ? 0 : this.buttonForm.hashCode()); + return result; } - return true; - } - - public ON_OR_OFF getConfirmation() { - return this.confirmation; - } - - public String getName() { - return this.name; - } - - public String getButtonForm() { - return this.buttonForm; - } - - public Optional getProjectKey() { - return fromNullable(this.projectKey); - } - - public Optional getRepositorySlug() { - return fromNullable(this.repositorySlug); - } - - public USER_LEVEL getUserLevel() { - return this.userLevel; - } - - @Override - public UUID getUuid() { - return this.uuid; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); - result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.userLevel == null) ? 0 : this.userLevel.hashCode()); - result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); - result = prime * result + ((this.confirmation == null) ? 0 : this.confirmation.hashCode()); - result = prime * result + ((this.buttonForm == null) ? 0 : this.buttonForm.hashCode()); - return result; - } - - @Override - public String toString() { - return "PrnfbButton [projectKey=" + this.projectKey + ", repositorySlug=" + this.repositorySlug + ", name=" - + this.name + ", userLevel=" + this.userLevel + ", uuid=" + this.uuid + ", buttonForm=" + this.buttonForm + ", confirmation=" + this.confirmation + "]"; - } + @Override + public String toString() { + return "PrnfbButton [projectKey=" + + this.projectKey + + ", repositorySlug=" + + this.repositorySlug + + ", name=" + + this.name + + ", userLevel=" + + this.userLevel + + ", uuid=" + + this.uuid + + ", buttonForm=" + + this.buttonForm + + ", confirmation=" + + this.confirmation + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbHeader.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbHeader.java index 42686489..ba941918 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbHeader.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbHeader.java @@ -6,63 +6,62 @@ public class PrnfbHeader { - private final String name; - private final String value; + private final String name; + private final String value; - public PrnfbHeader(String name, String value) { - this.name = checkNotNull(emptyToNull(nullToEmpty(name).trim())); - this.value = checkNotNull(emptyToNull(nullToEmpty(value).trim())); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PrnfbHeader other = (PrnfbHeader) obj; - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - if (this.value == null) { - if (other.value != null) { - return false; - } - } else if (!this.value.equals(other.value)) { - return false; + public PrnfbHeader(String name, String value) { + this.name = checkNotNull(emptyToNull(nullToEmpty(name).trim())); + this.value = checkNotNull(emptyToNull(nullToEmpty(value).trim())); } - return true; - } - public String getName() { - return this.name; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PrnfbHeader other = (PrnfbHeader) obj; + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.value == null) { + if (other.value != null) { + return false; + } + } else if (!this.value.equals(other.value)) { + return false; + } + return true; + } - public String getValue() { - return this.value; - } + public String getName() { + return this.name; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.value == null) ? 0 : this.value.hashCode()); - return result; - } + public String getValue() { + return this.value; + } - @Override - public String toString() { - return "PrnfbHeader [name=" + this.name + ", value=" + this.value + "]"; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.value == null) ? 0 : this.value.hashCode()); + return result; + } -} \ No newline at end of file + @Override + public String toString() { + return "PrnfbHeader [name=" + this.name + ", value=" + this.value + "]"; + } +} diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbNotification.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbNotification.java index ef389393..cb4305ef 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbNotification.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbNotification.java @@ -22,348 +22,389 @@ public class PrnfbNotification implements HasUuid { - private static final String DEFAULT_NAME = "Notification"; - private final String filterRegexp; - private final String filterString; - private final List headers; - private final String injectionUrl; - private final String injectionUrlRegexp; - private final HTTP_METHOD method; - private final String name; - private final String password; - private final String postContent; - private final String projectKey; - private final String proxyPassword; - private final Integer proxyPort; - private final String proxyServer; - private final String proxyUser; - private final String repositorySlug; - private final TRIGGER_IF_MERGE triggerIfCanMerge; - private final List triggerIgnoreStateList; - private final List triggers; - private final String url; - private final String user; - private final UUID uuid; - - public PrnfbNotification(PrnfbNotificationBuilder builder) throws ValidationException { - this.uuid = firstNonNull(builder.getUUID(), randomUUID()); - this.proxyUser = emptyToNull(nullToEmpty(builder.getProxyUser()).trim()); - this.proxyPassword = emptyToNull(nullToEmpty(builder.getProxyPassword()).trim()); - this.proxyServer = emptyToNull(nullToEmpty(builder.getProxyServer()).trim()); - this.proxyPort = builder.getProxyPort(); - this.headers = checkNotNull(builder.getHeaders()); - this.postContent = emptyToNull(nullToEmpty(builder.getPostContent()).trim()); - this.method = firstNonNull(builder.getMethod(), GET); - this.triggerIfCanMerge = firstNonNull(builder.getTriggerIfCanMerge(), ALWAYS); - this.repositorySlug = emptyToNull(builder.getRepositorySlug()); - this.projectKey = emptyToNull(builder.getProjectKey()); - try { - new URL(builder.getUrl()); - } catch (final Exception e) { - throw new ValidationException("url", "URL not valid!"); - } - if (!nullToEmpty(builder.getFilterRegexp()).trim().isEmpty()) { - try { - compile(builder.getFilterRegexp()); - } catch (final Exception e) { - throw new ValidationException("filter_regexp", "Filter regexp not valid! " + e.getMessage().replaceAll("\n", " ")); - } - if (nullToEmpty(builder.getFilterString()).trim().isEmpty()) { - throw new ValidationException("filter_string", "Filter string not set, nothing to match regexp against!"); - } + private static final String DEFAULT_NAME = "Notification"; + private final String filterRegexp; + private final String filterString; + private final List headers; + private final String injectionUrl; + private final String injectionUrlRegexp; + private final HTTP_METHOD method; + private final String name; + private final String password; + private final String postContent; + private final String projectKey; + private final String proxyPassword; + private final Integer proxyPort; + private final String proxyServer; + private final String proxyUser; + private final String repositorySlug; + private final TRIGGER_IF_MERGE triggerIfCanMerge; + private final List triggerIgnoreStateList; + private final List triggers; + private final String url; + private final String user; + private final UUID uuid; + + public PrnfbNotification(PrnfbNotificationBuilder builder) throws ValidationException { + this.uuid = firstNonNull(builder.getUUID(), randomUUID()); + this.proxyUser = emptyToNull(nullToEmpty(builder.getProxyUser()).trim()); + this.proxyPassword = emptyToNull(nullToEmpty(builder.getProxyPassword()).trim()); + this.proxyServer = emptyToNull(nullToEmpty(builder.getProxyServer()).trim()); + this.proxyPort = builder.getProxyPort(); + this.headers = checkNotNull(builder.getHeaders()); + this.postContent = emptyToNull(nullToEmpty(builder.getPostContent()).trim()); + this.method = firstNonNull(builder.getMethod(), GET); + this.triggerIfCanMerge = firstNonNull(builder.getTriggerIfCanMerge(), ALWAYS); + this.repositorySlug = emptyToNull(builder.getRepositorySlug()); + this.projectKey = emptyToNull(builder.getProjectKey()); + try { + new URL(builder.getUrl()); + } catch (final Exception e) { + throw new ValidationException("url", "URL not valid!"); + } + if (!nullToEmpty(builder.getFilterRegexp()).trim().isEmpty()) { + try { + compile(builder.getFilterRegexp()); + } catch (final Exception e) { + throw new ValidationException( + "filter_regexp", "Filter regexp not valid! " + e.getMessage().replaceAll("\n", " ")); + } + if (nullToEmpty(builder.getFilterString()).trim().isEmpty()) { + throw new ValidationException( + "filter_string", "Filter string not set, nothing to match regexp against!"); + } + } + this.url = builder.getUrl(); + this.user = emptyToNull(nullToEmpty(builder.getUser()).trim()); + this.password = emptyToNull(nullToEmpty(builder.getPassword()).trim()); + this.triggers = checkNotNull(builder.getTriggers(), "triggers"); + if (this.triggers.isEmpty()) { + throw new ValidationException("triggers", "At least one trigger must be selected."); + } + this.filterString = builder.getFilterString(); + this.filterRegexp = builder.getFilterRegexp(); + this.name = firstNonNull(emptyToNull(nullToEmpty(builder.getName()).trim()), DEFAULT_NAME); + this.injectionUrl = emptyToNull(nullToEmpty(builder.getInjectionUrl()).trim()); + this.injectionUrlRegexp = emptyToNull(nullToEmpty(builder.getInjectionUrlRegexp()).trim()); + this.triggerIgnoreStateList = builder.getTriggerIgnoreStateList(); } - this.url = builder.getUrl(); - this.user = emptyToNull(nullToEmpty(builder.getUser()).trim()); - this.password = emptyToNull(nullToEmpty(builder.getPassword()).trim()); - this.triggers = checkNotNull(builder.getTriggers(), "triggers"); - if (this.triggers.isEmpty()) { - throw new ValidationException("triggers", "At least one trigger must be selected."); - } - this.filterString = builder.getFilterString(); - this.filterRegexp = builder.getFilterRegexp(); - this.name = firstNonNull(emptyToNull(nullToEmpty(builder.getName()).trim()), DEFAULT_NAME); - this.injectionUrl = emptyToNull(nullToEmpty(builder.getInjectionUrl()).trim()); - this.injectionUrlRegexp = emptyToNull(nullToEmpty(builder.getInjectionUrlRegexp()).trim()); - this.triggerIgnoreStateList = builder.getTriggerIgnoreStateList(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PrnfbNotification other = (PrnfbNotification) obj; - if (this.filterRegexp == null) { - if (other.filterRegexp != null) { - return false; - } - } else if (!this.filterRegexp.equals(other.filterRegexp)) { - return false; - } - if (this.filterString == null) { - if (other.filterString != null) { - return false; - } - } else if (!this.filterString.equals(other.filterString)) { - return false; - } - if (this.headers == null) { - if (other.headers != null) { - return false; - } - } else if (!this.headers.equals(other.headers)) { - return false; - } - if (this.injectionUrl == null) { - if (other.injectionUrl != null) { - return false; - } - } else if (!this.injectionUrl.equals(other.injectionUrl)) { - return false; - } - if (this.injectionUrlRegexp == null) { - if (other.injectionUrlRegexp != null) { - return false; - } - } else if (!this.injectionUrlRegexp.equals(other.injectionUrlRegexp)) { - return false; - } - if (this.method != other.method) { - return false; - } - if (this.name == null) { - if (other.name != null) { - return false; - } - } else if (!this.name.equals(other.name)) { - return false; - } - if (this.password == null) { - if (other.password != null) { - return false; - } - } else if (!this.password.equals(other.password)) { - return false; - } - if (this.postContent == null) { - if (other.postContent != null) { - return false; - } - } else if (!this.postContent.equals(other.postContent)) { - return false; - } - if (this.projectKey == null) { - if (other.projectKey != null) { - return false; - } - } else if (!this.projectKey.equals(other.projectKey)) { - return false; - } - if (this.proxyPassword == null) { - if (other.proxyPassword != null) { - return false; - } - } else if (!this.proxyPassword.equals(other.proxyPassword)) { - return false; - } - if (this.proxyPort == null) { - if (other.proxyPort != null) { - return false; - } - } else if (!this.proxyPort.equals(other.proxyPort)) { - return false; - } - if (this.proxyServer == null) { - if (other.proxyServer != null) { - return false; - } - } else if (!this.proxyServer.equals(other.proxyServer)) { - return false; - } - if (this.proxyUser == null) { - if (other.proxyUser != null) { - return false; - } - } else if (!this.proxyUser.equals(other.proxyUser)) { - return false; - } - if (this.repositorySlug == null) { - if (other.repositorySlug != null) { - return false; - } - } else if (!this.repositorySlug.equals(other.repositorySlug)) { - return false; - } - if (this.triggerIfCanMerge != other.triggerIfCanMerge) { - return false; - } - if (this.triggerIgnoreStateList == null) { - if (other.triggerIgnoreStateList != null) { - return false; - } - } else if (!this.triggerIgnoreStateList.equals(other.triggerIgnoreStateList)) { - return false; - } - if (this.triggers == null) { - if (other.triggers != null) { - return false; - } - } else if (!this.triggers.equals(other.triggers)) { - return false; - } - if (this.url == null) { - if (other.url != null) { - return false; - } - } else if (!this.url.equals(other.url)) { - return false; - } - if (this.user == null) { - if (other.user != null) { - return false; - } - } else if (!this.user.equals(other.user)) { - return false; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PrnfbNotification other = (PrnfbNotification) obj; + if (this.filterRegexp == null) { + if (other.filterRegexp != null) { + return false; + } + } else if (!this.filterRegexp.equals(other.filterRegexp)) { + return false; + } + if (this.filterString == null) { + if (other.filterString != null) { + return false; + } + } else if (!this.filterString.equals(other.filterString)) { + return false; + } + if (this.headers == null) { + if (other.headers != null) { + return false; + } + } else if (!this.headers.equals(other.headers)) { + return false; + } + if (this.injectionUrl == null) { + if (other.injectionUrl != null) { + return false; + } + } else if (!this.injectionUrl.equals(other.injectionUrl)) { + return false; + } + if (this.injectionUrlRegexp == null) { + if (other.injectionUrlRegexp != null) { + return false; + } + } else if (!this.injectionUrlRegexp.equals(other.injectionUrlRegexp)) { + return false; + } + if (this.method != other.method) { + return false; + } + if (this.name == null) { + if (other.name != null) { + return false; + } + } else if (!this.name.equals(other.name)) { + return false; + } + if (this.password == null) { + if (other.password != null) { + return false; + } + } else if (!this.password.equals(other.password)) { + return false; + } + if (this.postContent == null) { + if (other.postContent != null) { + return false; + } + } else if (!this.postContent.equals(other.postContent)) { + return false; + } + if (this.projectKey == null) { + if (other.projectKey != null) { + return false; + } + } else if (!this.projectKey.equals(other.projectKey)) { + return false; + } + if (this.proxyPassword == null) { + if (other.proxyPassword != null) { + return false; + } + } else if (!this.proxyPassword.equals(other.proxyPassword)) { + return false; + } + if (this.proxyPort == null) { + if (other.proxyPort != null) { + return false; + } + } else if (!this.proxyPort.equals(other.proxyPort)) { + return false; + } + if (this.proxyServer == null) { + if (other.proxyServer != null) { + return false; + } + } else if (!this.proxyServer.equals(other.proxyServer)) { + return false; + } + if (this.proxyUser == null) { + if (other.proxyUser != null) { + return false; + } + } else if (!this.proxyUser.equals(other.proxyUser)) { + return false; + } + if (this.repositorySlug == null) { + if (other.repositorySlug != null) { + return false; + } + } else if (!this.repositorySlug.equals(other.repositorySlug)) { + return false; + } + if (this.triggerIfCanMerge != other.triggerIfCanMerge) { + return false; + } + if (this.triggerIgnoreStateList == null) { + if (other.triggerIgnoreStateList != null) { + return false; + } + } else if (!this.triggerIgnoreStateList.equals(other.triggerIgnoreStateList)) { + return false; + } + if (this.triggers == null) { + if (other.triggers != null) { + return false; + } + } else if (!this.triggers.equals(other.triggers)) { + return false; + } + if (this.url == null) { + if (other.url != null) { + return false; + } + } else if (!this.url.equals(other.url)) { + return false; + } + if (this.user == null) { + if (other.user != null) { + return false; + } + } else if (!this.user.equals(other.user)) { + return false; + } + if (this.uuid == null) { + if (other.uuid != null) { + return false; + } + } else if (!this.uuid.equals(other.uuid)) { + return false; + } + return true; } - if (this.uuid == null) { - if (other.uuid != null) { - return false; - } - } else if (!this.uuid.equals(other.uuid)) { - return false; - } - return true; - } - - public Optional getFilterRegexp() { - return fromNullable(this.filterRegexp); - } - public Optional getFilterString() { - return fromNullable(this.filterString); - } + public Optional getFilterRegexp() { + return fromNullable(this.filterRegexp); + } - public List getHeaders() { - return this.headers; - } + public Optional getFilterString() { + return fromNullable(this.filterString); + } - public Optional getInjectionUrl() { - return fromNullable(this.injectionUrl); - } + public List getHeaders() { + return this.headers; + } - public Optional getInjectionUrlRegexp() { - return fromNullable(this.injectionUrlRegexp); - } + public Optional getInjectionUrl() { + return fromNullable(this.injectionUrl); + } - public HTTP_METHOD getMethod() { - return this.method; - } + public Optional getInjectionUrlRegexp() { + return fromNullable(this.injectionUrlRegexp); + } - public String getName() { - return this.name; - } + public HTTP_METHOD getMethod() { + return this.method; + } - public Optional getPassword() { - return fromNullable(this.password); - } + public String getName() { + return this.name; + } - public Optional getPostContent() { - return fromNullable(this.postContent); - } + public Optional getPassword() { + return fromNullable(this.password); + } - public Optional getProjectKey() { - return fromNullable(this.projectKey); - } + public Optional getPostContent() { + return fromNullable(this.postContent); + } - public Optional getProxyPassword() { - return fromNullable(this.proxyPassword); - } + public Optional getProjectKey() { + return fromNullable(this.projectKey); + } - public Integer getProxyPort() { - return this.proxyPort; - } + public Optional getProxyPassword() { + return fromNullable(this.proxyPassword); + } - public Optional getProxyServer() { - return fromNullable(this.proxyServer); - } + public Integer getProxyPort() { + return this.proxyPort; + } - public Optional getProxyUser() { - return fromNullable(this.proxyUser); - } + public Optional getProxyServer() { + return fromNullable(this.proxyServer); + } - public Optional getRepositorySlug() { - return fromNullable(this.repositorySlug); - } + public Optional getProxyUser() { + return fromNullable(this.proxyUser); + } - public TRIGGER_IF_MERGE getTriggerIfCanMerge() { - return this.triggerIfCanMerge; - } + public Optional getRepositorySlug() { + return fromNullable(this.repositorySlug); + } - public List getTriggerIgnoreStateList() { - return this.triggerIgnoreStateList; - } + public TRIGGER_IF_MERGE getTriggerIfCanMerge() { + return this.triggerIfCanMerge; + } - public List getTriggers() { - return this.triggers; - } + public List getTriggerIgnoreStateList() { + return this.triggerIgnoreStateList; + } - public String getUrl() { - return this.url; - } + public List getTriggers() { + return this.triggers; + } - public Optional getUser() { - return fromNullable(this.user); - } + public String getUrl() { + return this.url; + } - @Override - public UUID getUuid() { - return this.uuid; - } + public Optional getUser() { + return fromNullable(this.user); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.filterRegexp == null) ? 0 : this.filterRegexp.hashCode()); - result = prime * result + ((this.filterString == null) ? 0 : this.filterString.hashCode()); - result = prime * result + ((this.headers == null) ? 0 : this.headers.hashCode()); - result = prime * result + ((this.injectionUrl == null) ? 0 : this.injectionUrl.hashCode()); - result = prime * result + ((this.injectionUrlRegexp == null) ? 0 : this.injectionUrlRegexp.hashCode()); - result = prime * result + ((this.method == null) ? 0 : this.method.hashCode()); - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.password == null) ? 0 : this.password.hashCode()); - result = prime * result + ((this.postContent == null) ? 0 : this.postContent.hashCode()); - result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); - result = prime * result + ((this.proxyPassword == null) ? 0 : this.proxyPassword.hashCode()); - result = prime * result + ((this.proxyPort == null) ? 0 : this.proxyPort.hashCode()); - result = prime * result + ((this.proxyServer == null) ? 0 : this.proxyServer.hashCode()); - result = prime * result + ((this.proxyUser == null) ? 0 : this.proxyUser.hashCode()); - result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); - result = prime * result + ((this.triggerIfCanMerge == null) ? 0 : this.triggerIfCanMerge.hashCode()); - result = prime * result + ((this.triggerIgnoreStateList == null) ? 0 : this.triggerIgnoreStateList.hashCode()); - result = prime * result + ((this.triggers == null) ? 0 : this.triggers.hashCode()); - result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); - result = prime * result + ((this.user == null) ? 0 : this.user.hashCode()); - result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); - return result; - } + @Override + public UUID getUuid() { + return this.uuid; + } - @Override - public String toString() { - return "PrnfbNotification [filterRegexp=" + this.filterRegexp + ", filterString=" + this.filterString + ", headers=" - + this.headers + ", injectionUrl=" + this.injectionUrl + ", injectionUrlRegexp=" + this.injectionUrlRegexp - + ", method=" + this.method + ", name=" + this.name + ", password=" + this.password + ", postContent=" - + this.postContent + ", projectKey=" + this.projectKey + ", proxyPassword=" + this.proxyPassword + ", proxyPort=" - + this.proxyPort + ", proxyServer=" + this.proxyServer + ", proxyUser=" + this.proxyUser + ", repositorySlug=" - + this.repositorySlug + ", triggerIfCanMerge=" + this.triggerIfCanMerge + ", triggerIgnoreStateList=" - + this.triggerIgnoreStateList + ", triggers=" + this.triggers + ", url=" + this.url + ", user=" + this.user - + ", uuid=" + this.uuid + "]"; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.filterRegexp == null) ? 0 : this.filterRegexp.hashCode()); + result = prime * result + ((this.filterString == null) ? 0 : this.filterString.hashCode()); + result = prime * result + ((this.headers == null) ? 0 : this.headers.hashCode()); + result = prime * result + ((this.injectionUrl == null) ? 0 : this.injectionUrl.hashCode()); + result = + prime * result + + ((this.injectionUrlRegexp == null) ? 0 : this.injectionUrlRegexp.hashCode()); + result = prime * result + ((this.method == null) ? 0 : this.method.hashCode()); + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.password == null) ? 0 : this.password.hashCode()); + result = prime * result + ((this.postContent == null) ? 0 : this.postContent.hashCode()); + result = prime * result + ((this.projectKey == null) ? 0 : this.projectKey.hashCode()); + result = prime * result + ((this.proxyPassword == null) ? 0 : this.proxyPassword.hashCode()); + result = prime * result + ((this.proxyPort == null) ? 0 : this.proxyPort.hashCode()); + result = prime * result + ((this.proxyServer == null) ? 0 : this.proxyServer.hashCode()); + result = prime * result + ((this.proxyUser == null) ? 0 : this.proxyUser.hashCode()); + result = prime * result + ((this.repositorySlug == null) ? 0 : this.repositorySlug.hashCode()); + result = + prime * result + ((this.triggerIfCanMerge == null) ? 0 : this.triggerIfCanMerge.hashCode()); + result = + prime * result + + ((this.triggerIgnoreStateList == null) ? 0 : this.triggerIgnoreStateList.hashCode()); + result = prime * result + ((this.triggers == null) ? 0 : this.triggers.hashCode()); + result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); + result = prime * result + ((this.user == null) ? 0 : this.user.hashCode()); + result = prime * result + ((this.uuid == null) ? 0 : this.uuid.hashCode()); + return result; + } + @Override + public String toString() { + return "PrnfbNotification [filterRegexp=" + + this.filterRegexp + + ", filterString=" + + this.filterString + + ", headers=" + + this.headers + + ", injectionUrl=" + + this.injectionUrl + + ", injectionUrlRegexp=" + + this.injectionUrlRegexp + + ", method=" + + this.method + + ", name=" + + this.name + + ", password=" + + this.password + + ", postContent=" + + this.postContent + + ", projectKey=" + + this.projectKey + + ", proxyPassword=" + + this.proxyPassword + + ", proxyPort=" + + this.proxyPort + + ", proxyServer=" + + this.proxyServer + + ", proxyUser=" + + this.proxyUser + + ", repositorySlug=" + + this.repositorySlug + + ", triggerIfCanMerge=" + + this.triggerIfCanMerge + + ", triggerIgnoreStateList=" + + this.triggerIgnoreStateList + + ", triggers=" + + this.triggers + + ", url=" + + this.url + + ", user=" + + this.user + + ", uuid=" + + this.uuid + + "]"; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbNotificationBuilder.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbNotificationBuilder.java index 52b66b78..f2ba0328 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbNotificationBuilder.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbNotificationBuilder.java @@ -15,270 +15,271 @@ import com.atlassian.bitbucket.pull.PullRequestState; public class PrnfbNotificationBuilder { - public static PrnfbNotificationBuilder prnfbNotificationBuilder() { - return new PrnfbNotificationBuilder(); - } - - public static PrnfbNotificationBuilder prnfbNotificationBuilder(PrnfbNotification from) { - PrnfbNotificationBuilder b = new PrnfbNotificationBuilder(); - - b.uuid = from.getUuid(); - b.password = from.getPassword().orNull(); - b.triggers = from.getTriggers(); - b.url = from.getUrl(); - b.user = from.getUser().orNull(); - b.filterRegexp = from.getFilterRegexp().orNull(); - b.filterString = from.getFilterString().orNull(); - b.method = from.getMethod(); - b.postContent = from.getPostContent().orNull(); - b.headers = from.getHeaders(); - b.triggerIgnoreStateList = from.getTriggerIgnoreStateList(); - b.proxyUser = from.getProxyUser().orNull(); - b.proxyPassword = from.getProxyPassword().orNull(); - b.proxyServer = from.getProxyServer().orNull(); - b.proxyPort = from.getProxyPort(); - b.name = from.getName(); - b.injectionUrl = from.getInjectionUrl().orNull(); - b.injectionUrlRegexp = from.getInjectionUrlRegexp().orNull(); - b.triggerIfCanMerge = from.getTriggerIfCanMerge(); - return b; - } - - private String filterRegexp; - private String filterString; - private List headers = newArrayList(); - private String injectionUrl; - private String injectionUrlRegexp; - private HTTP_METHOD method; - private String name; - private String password; - private String postContent; - private String projectKey; - private String proxyPassword; - private Integer proxyPort; - private String proxyServer; - private String proxyUser; - private String repositorySlug; - private TRIGGER_IF_MERGE triggerIfCanMerge; - private List triggerIgnoreStateList = newArrayList(); - private List triggers = newArrayList(); - private String url; - private String user; - private UUID uuid; - - private PrnfbNotificationBuilder() { - this.uuid = randomUUID(); - } - - public PrnfbNotification build() throws ValidationException { - return new PrnfbNotification(this); - } - - public String getFilterRegexp() { - return this.filterRegexp; - } - - public String getFilterString() { - return this.filterString; - } - - public List getHeaders() { - return this.headers; - } - - public String getInjectionUrl() { - return this.injectionUrl; - } - - public String getInjectionUrlRegexp() { - return this.injectionUrlRegexp; - } - - public HTTP_METHOD getMethod() { - return this.method; - } - - public String getName() { - return this.name; - } - - public String getPassword() { - return this.password; - } - - public String getPostContent() { - return this.postContent; - } - - public String getProjectKey() { - return this.projectKey; - } - - public String getProxyPassword() { - return this.proxyPassword; - } - - public Integer getProxyPort() { - return this.proxyPort; - } - - public String getProxyServer() { - return this.proxyServer; - } - - public String getProxyUser() { - return this.proxyUser; - } - - public String getRepositorySlug() { - return this.repositorySlug; - } - - public TRIGGER_IF_MERGE getTriggerIfCanMerge() { - return this.triggerIfCanMerge; - } - - public List getTriggerIgnoreStateList() { - return this.triggerIgnoreStateList; - } - - public List getTriggers() { - return this.triggers; - } - - public String getUrl() { - return this.url; - } - - public String getUser() { - return this.user; - } - - public UUID getUuid() { - return this.uuid; - } - - public UUID getUUID() { - return this.uuid; - } - - public PrnfbNotificationBuilder setHeaders(List headers) { - this.headers = headers; - return this; - } - - public PrnfbNotificationBuilder setTriggerIgnoreState(List triggerIgnoreStateList) { - this.triggerIgnoreStateList = triggerIgnoreStateList; - return this; - } - - public PrnfbNotificationBuilder setTriggers(List triggers) { - this.triggers = triggers; - return this; - } - - public PrnfbNotificationBuilder withFilterRegexp(String filterRegexp) { - this.filterRegexp = emptyToNull(filterRegexp); - return this; - } - - public PrnfbNotificationBuilder withFilterString(String filterString) { - this.filterString = emptyToNull(filterString); - return this; - } - - public PrnfbNotificationBuilder withHeader(String name, String value) { - this.headers.add(new PrnfbHeader(name, value)); - return this; - } - - public PrnfbNotificationBuilder withInjectionUrl(String injectionUrl) { - this.injectionUrl = emptyToNull(injectionUrl); - return this; - } - - public PrnfbNotificationBuilder withInjectionUrlRegexp(String injectionUrlRegexp) { - this.injectionUrlRegexp = emptyToNull(injectionUrlRegexp); - return this; - } - - public PrnfbNotificationBuilder withMethod(HTTP_METHOD method) { - this.method = firstNonNull(method, GET); - return this; - } - - public PrnfbNotificationBuilder withName(String name) { - this.name = name; - return this; - } - - public PrnfbNotificationBuilder withPassword(String password) { - this.password = emptyToNull(password); - return this; - } - - public PrnfbNotificationBuilder withPostContent(String postContent) { - this.postContent = emptyToNull(postContent); - return this; - } - - public PrnfbNotificationBuilder withProjectKey(String projectKey) { - this.projectKey = projectKey; - return this; - } - - public PrnfbNotificationBuilder withProxyPassword(String s) { - this.proxyPassword = emptyToNull(s); - return this; - } - - public PrnfbNotificationBuilder withProxyPort(Integer s) { - this.proxyPort = s; - return this; - } - - public PrnfbNotificationBuilder withProxyServer(String s) { - this.proxyServer = emptyToNull(s); - return this; - } - - public PrnfbNotificationBuilder withProxyUser(String s) { - this.proxyUser = emptyToNull(s); - return this; - } - - public PrnfbNotificationBuilder withRepositorySlug(String repositorySlug) { - this.repositorySlug = repositorySlug; - return this; - } - - public PrnfbNotificationBuilder withTrigger(PrnfbPullRequestAction trigger) { - this.triggers.add(trigger); - return this; - } - - public PrnfbNotificationBuilder withTriggerIfCanMerge(TRIGGER_IF_MERGE triggerIfCanMerge) { - this.triggerIfCanMerge = triggerIfCanMerge; - return this; - } - - public PrnfbNotificationBuilder withTriggerIgnoreState(PullRequestState triggerIgnoreState) { - this.triggerIgnoreStateList.add(triggerIgnoreState); - return this; - } - - public PrnfbNotificationBuilder withUrl(String url) { - this.url = url; - return this; - } - - public PrnfbNotificationBuilder withUser(String user) { - this.user = emptyToNull(user); - return this; - } - - public PrnfbNotificationBuilder withUuid(UUID uuid) { - this.uuid = uuid; - return this; - } + public static PrnfbNotificationBuilder prnfbNotificationBuilder() { + return new PrnfbNotificationBuilder(); + } + + public static PrnfbNotificationBuilder prnfbNotificationBuilder(PrnfbNotification from) { + PrnfbNotificationBuilder b = new PrnfbNotificationBuilder(); + + b.uuid = from.getUuid(); + b.password = from.getPassword().orNull(); + b.triggers = from.getTriggers(); + b.url = from.getUrl(); + b.user = from.getUser().orNull(); + b.filterRegexp = from.getFilterRegexp().orNull(); + b.filterString = from.getFilterString().orNull(); + b.method = from.getMethod(); + b.postContent = from.getPostContent().orNull(); + b.headers = from.getHeaders(); + b.triggerIgnoreStateList = from.getTriggerIgnoreStateList(); + b.proxyUser = from.getProxyUser().orNull(); + b.proxyPassword = from.getProxyPassword().orNull(); + b.proxyServer = from.getProxyServer().orNull(); + b.proxyPort = from.getProxyPort(); + b.name = from.getName(); + b.injectionUrl = from.getInjectionUrl().orNull(); + b.injectionUrlRegexp = from.getInjectionUrlRegexp().orNull(); + b.triggerIfCanMerge = from.getTriggerIfCanMerge(); + return b; + } + + private String filterRegexp; + private String filterString; + private List headers = newArrayList(); + private String injectionUrl; + private String injectionUrlRegexp; + private HTTP_METHOD method; + private String name; + private String password; + private String postContent; + private String projectKey; + private String proxyPassword; + private Integer proxyPort; + private String proxyServer; + private String proxyUser; + private String repositorySlug; + private TRIGGER_IF_MERGE triggerIfCanMerge; + private List triggerIgnoreStateList = newArrayList(); + private List triggers = newArrayList(); + private String url; + private String user; + private UUID uuid; + + private PrnfbNotificationBuilder() { + this.uuid = randomUUID(); + } + + public PrnfbNotification build() throws ValidationException { + return new PrnfbNotification(this); + } + + public String getFilterRegexp() { + return this.filterRegexp; + } + + public String getFilterString() { + return this.filterString; + } + + public List getHeaders() { + return this.headers; + } + + public String getInjectionUrl() { + return this.injectionUrl; + } + + public String getInjectionUrlRegexp() { + return this.injectionUrlRegexp; + } + + public HTTP_METHOD getMethod() { + return this.method; + } + + public String getName() { + return this.name; + } + + public String getPassword() { + return this.password; + } + + public String getPostContent() { + return this.postContent; + } + + public String getProjectKey() { + return this.projectKey; + } + + public String getProxyPassword() { + return this.proxyPassword; + } + + public Integer getProxyPort() { + return this.proxyPort; + } + + public String getProxyServer() { + return this.proxyServer; + } + + public String getProxyUser() { + return this.proxyUser; + } + + public String getRepositorySlug() { + return this.repositorySlug; + } + + public TRIGGER_IF_MERGE getTriggerIfCanMerge() { + return this.triggerIfCanMerge; + } + + public List getTriggerIgnoreStateList() { + return this.triggerIgnoreStateList; + } + + public List getTriggers() { + return this.triggers; + } + + public String getUrl() { + return this.url; + } + + public String getUser() { + return this.user; + } + + public UUID getUuid() { + return this.uuid; + } + + public UUID getUUID() { + return this.uuid; + } + + public PrnfbNotificationBuilder setHeaders(List headers) { + this.headers = headers; + return this; + } + + public PrnfbNotificationBuilder setTriggerIgnoreState( + List triggerIgnoreStateList) { + this.triggerIgnoreStateList = triggerIgnoreStateList; + return this; + } + + public PrnfbNotificationBuilder setTriggers(List triggers) { + this.triggers = triggers; + return this; + } + + public PrnfbNotificationBuilder withFilterRegexp(String filterRegexp) { + this.filterRegexp = emptyToNull(filterRegexp); + return this; + } + + public PrnfbNotificationBuilder withFilterString(String filterString) { + this.filterString = emptyToNull(filterString); + return this; + } + + public PrnfbNotificationBuilder withHeader(String name, String value) { + this.headers.add(new PrnfbHeader(name, value)); + return this; + } + + public PrnfbNotificationBuilder withInjectionUrl(String injectionUrl) { + this.injectionUrl = emptyToNull(injectionUrl); + return this; + } + + public PrnfbNotificationBuilder withInjectionUrlRegexp(String injectionUrlRegexp) { + this.injectionUrlRegexp = emptyToNull(injectionUrlRegexp); + return this; + } + + public PrnfbNotificationBuilder withMethod(HTTP_METHOD method) { + this.method = firstNonNull(method, GET); + return this; + } + + public PrnfbNotificationBuilder withName(String name) { + this.name = name; + return this; + } + + public PrnfbNotificationBuilder withPassword(String password) { + this.password = emptyToNull(password); + return this; + } + + public PrnfbNotificationBuilder withPostContent(String postContent) { + this.postContent = emptyToNull(postContent); + return this; + } + + public PrnfbNotificationBuilder withProjectKey(String projectKey) { + this.projectKey = projectKey; + return this; + } + + public PrnfbNotificationBuilder withProxyPassword(String s) { + this.proxyPassword = emptyToNull(s); + return this; + } + + public PrnfbNotificationBuilder withProxyPort(Integer s) { + this.proxyPort = s; + return this; + } + + public PrnfbNotificationBuilder withProxyServer(String s) { + this.proxyServer = emptyToNull(s); + return this; + } + + public PrnfbNotificationBuilder withProxyUser(String s) { + this.proxyUser = emptyToNull(s); + return this; + } + + public PrnfbNotificationBuilder withRepositorySlug(String repositorySlug) { + this.repositorySlug = repositorySlug; + return this; + } + + public PrnfbNotificationBuilder withTrigger(PrnfbPullRequestAction trigger) { + this.triggers.add(trigger); + return this; + } + + public PrnfbNotificationBuilder withTriggerIfCanMerge(TRIGGER_IF_MERGE triggerIfCanMerge) { + this.triggerIfCanMerge = triggerIfCanMerge; + return this; + } + + public PrnfbNotificationBuilder withTriggerIgnoreState(PullRequestState triggerIgnoreState) { + this.triggerIgnoreStateList.add(triggerIgnoreState); + return this; + } + + public PrnfbNotificationBuilder withUrl(String url) { + this.url = url; + return this; + } + + public PrnfbNotificationBuilder withUser(String user) { + this.user = emptyToNull(user); + return this; + } + + public PrnfbNotificationBuilder withUuid(UUID uuid) { + this.uuid = uuid; + return this; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettings.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettings.java index 951cf4b4..4c8b1992 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettings.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettings.java @@ -6,72 +6,72 @@ import java.util.List; public class PrnfbSettings { - private final List buttons; - private List notifications = newArrayList(); - private final PrnfbSettingsData prnfbSettingsData; + private final List buttons; + private List notifications = newArrayList(); + private final PrnfbSettingsData prnfbSettingsData; - public PrnfbSettings(PrnfbSettingsBuilder builder) { - this.notifications = checkNotNull(builder.getNotifications()); - this.buttons = checkNotNull(builder.getButtons()); - this.prnfbSettingsData = checkNotNull(builder.getPrnfbSettingsData(), "prnfbSettingsData"); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PrnfbSettings other = (PrnfbSettings) obj; - if (this.buttons == null) { - if (other.buttons != null) { - return false; - } - } else if (!this.buttons.equals(other.buttons)) { - return false; - } - if (this.notifications == null) { - if (other.notifications != null) { - return false; - } - } else if (!this.notifications.equals(other.notifications)) { - return false; - } - if (this.prnfbSettingsData == null) { - if (other.prnfbSettingsData != null) { - return false; - } - } else if (!this.prnfbSettingsData.equals(other.prnfbSettingsData)) { - return false; + public PrnfbSettings(PrnfbSettingsBuilder builder) { + this.notifications = checkNotNull(builder.getNotifications()); + this.buttons = checkNotNull(builder.getButtons()); + this.prnfbSettingsData = checkNotNull(builder.getPrnfbSettingsData(), "prnfbSettingsData"); } - return true; - } - public List getButtons() { - return this.buttons; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PrnfbSettings other = (PrnfbSettings) obj; + if (this.buttons == null) { + if (other.buttons != null) { + return false; + } + } else if (!this.buttons.equals(other.buttons)) { + return false; + } + if (this.notifications == null) { + if (other.notifications != null) { + return false; + } + } else if (!this.notifications.equals(other.notifications)) { + return false; + } + if (this.prnfbSettingsData == null) { + if (other.prnfbSettingsData != null) { + return false; + } + } else if (!this.prnfbSettingsData.equals(other.prnfbSettingsData)) { + return false; + } + return true; + } - public List getNotifications() { - return this.notifications; - } + public List getButtons() { + return this.buttons; + } - public PrnfbSettingsData getPrnfbSettingsData() { - return this.prnfbSettingsData; - } + public List getNotifications() { + return this.notifications; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.buttons == null) ? 0 : this.buttons.hashCode()); - result = prime * result + ((this.notifications == null) ? 0 : this.notifications.hashCode()); - result = prime * result + ((this.prnfbSettingsData == null) ? 0 : this.prnfbSettingsData.hashCode()); - return result; - } + public PrnfbSettingsData getPrnfbSettingsData() { + return this.prnfbSettingsData; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.buttons == null) ? 0 : this.buttons.hashCode()); + result = prime * result + ((this.notifications == null) ? 0 : this.notifications.hashCode()); + result = + prime * result + ((this.prnfbSettingsData == null) ? 0 : this.prnfbSettingsData.hashCode()); + return result; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsBuilder.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsBuilder.java index f784557f..e2917636 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsBuilder.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsBuilder.java @@ -8,69 +8,71 @@ import java.util.List; public class PrnfbSettingsBuilder { - public static PrnfbSettingsBuilder prnfbSettingsBuilder() { - return new PrnfbSettingsBuilder(); - } - - public static PrnfbSettingsBuilder prnfbSettingsBuilder(PrnfbSettings settings) { - return new PrnfbSettingsBuilder(settings); - } - - private List buttons; - private List notifications; - private PrnfbSettingsData prnfbSettingsData; - - private PrnfbSettingsBuilder() { - this.notifications = newArrayList(); - this.buttons = newArrayList(); - this.prnfbSettingsData = prnfbSettingsDataBuilder()// - .build(); - } - - private PrnfbSettingsBuilder(PrnfbSettings settings) { - this.notifications = firstNonNull(settings.getNotifications(), new ArrayList()); - this.buttons = firstNonNull(settings.getButtons(), new ArrayList()); - this.prnfbSettingsData = settings.getPrnfbSettingsData(); - } - - public PrnfbSettings build() { - return new PrnfbSettings(this); - } - - public List getButtons() { - return this.buttons; - } - - public List getNotifications() { - return this.notifications; - } - - public PrnfbSettingsData getPrnfbSettingsData() { - return this.prnfbSettingsData; - } - - public PrnfbSettingsBuilder setButtons(List buttons) { - this.buttons = buttons; - return this; - } - - public PrnfbSettingsBuilder setNotifications(List notifications) { - this.notifications = notifications; - return this; - } - - public PrnfbSettingsBuilder setPrnfbSettingsData(PrnfbSettingsData prnfbSettingsData) { - this.prnfbSettingsData = prnfbSettingsData; - return this; - } - - public PrnfbSettingsBuilder withButton(PrnfbButton prnfbButton) { - this.buttons.add(prnfbButton); - return this; - } - - public PrnfbSettingsBuilder withNotification(PrnfbNotification notification) { - this.notifications.add(notification); - return this; - } + public static PrnfbSettingsBuilder prnfbSettingsBuilder() { + return new PrnfbSettingsBuilder(); + } + + public static PrnfbSettingsBuilder prnfbSettingsBuilder(PrnfbSettings settings) { + return new PrnfbSettingsBuilder(settings); + } + + private List buttons; + private List notifications; + private PrnfbSettingsData prnfbSettingsData; + + private PrnfbSettingsBuilder() { + this.notifications = newArrayList(); + this.buttons = newArrayList(); + this.prnfbSettingsData = + prnfbSettingsDataBuilder() // + .build(); + } + + private PrnfbSettingsBuilder(PrnfbSettings settings) { + this.notifications = + firstNonNull(settings.getNotifications(), new ArrayList()); + this.buttons = firstNonNull(settings.getButtons(), new ArrayList()); + this.prnfbSettingsData = settings.getPrnfbSettingsData(); + } + + public PrnfbSettings build() { + return new PrnfbSettings(this); + } + + public List getButtons() { + return this.buttons; + } + + public List getNotifications() { + return this.notifications; + } + + public PrnfbSettingsData getPrnfbSettingsData() { + return this.prnfbSettingsData; + } + + public PrnfbSettingsBuilder setButtons(List buttons) { + this.buttons = buttons; + return this; + } + + public PrnfbSettingsBuilder setNotifications(List notifications) { + this.notifications = notifications; + return this; + } + + public PrnfbSettingsBuilder setPrnfbSettingsData(PrnfbSettingsData prnfbSettingsData) { + this.prnfbSettingsData = prnfbSettingsData; + return this; + } + + public PrnfbSettingsBuilder withButton(PrnfbButton prnfbButton) { + this.buttons.add(prnfbButton); + return this; + } + + public PrnfbSettingsBuilder withNotification(PrnfbNotification notification) { + this.notifications.add(notification); + return this; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsData.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsData.java index e9472d3d..a760416d 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsData.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsData.java @@ -6,107 +6,116 @@ import com.google.common.base.Optional; public class PrnfbSettingsData { - private final USER_LEVEL adminRestriction; - private final String keyStore; - private final String keyStorePassword; - private final String keyStoreType; - private final boolean shouldAcceptAnyCertificate; + private final USER_LEVEL adminRestriction; + private final String keyStore; + private final String keyStorePassword; + private final String keyStoreType; + private final boolean shouldAcceptAnyCertificate; - public PrnfbSettingsData() { - this.keyStore = null; - this.keyStoreType = null; - this.keyStorePassword = null; - this.shouldAcceptAnyCertificate = false; - this.adminRestriction = null; - } - - public PrnfbSettingsData(PrnfbSettingsDataBuilder builder) { - this.keyStore = emptyToNull(builder.getKeyStore()); - this.keyStoreType = builder.getKeyStoreType(); - this.keyStorePassword = emptyToNull(builder.getKeyStorePassword()); - this.shouldAcceptAnyCertificate = builder.shouldAcceptAnyCertificate(); - this.adminRestriction = builder.getAdminRestriction(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PrnfbSettingsData other = (PrnfbSettingsData) obj; - if (this.adminRestriction != other.adminRestriction) { - return false; + public PrnfbSettingsData() { + this.keyStore = null; + this.keyStoreType = null; + this.keyStorePassword = null; + this.shouldAcceptAnyCertificate = false; + this.adminRestriction = null; } - if (this.keyStore == null) { - if (other.keyStore != null) { - return false; - } - } else if (!this.keyStore.equals(other.keyStore)) { - return false; - } - if (this.keyStorePassword == null) { - if (other.keyStorePassword != null) { - return false; - } - } else if (!this.keyStorePassword.equals(other.keyStorePassword)) { - return false; - } - if (this.keyStoreType == null) { - if (other.keyStoreType != null) { - return false; - } - } else if (!this.keyStoreType.equals(other.keyStoreType)) { - return false; - } - if (this.shouldAcceptAnyCertificate != other.shouldAcceptAnyCertificate) { - return false; + + public PrnfbSettingsData(PrnfbSettingsDataBuilder builder) { + this.keyStore = emptyToNull(builder.getKeyStore()); + this.keyStoreType = builder.getKeyStoreType(); + this.keyStorePassword = emptyToNull(builder.getKeyStorePassword()); + this.shouldAcceptAnyCertificate = builder.shouldAcceptAnyCertificate(); + this.adminRestriction = builder.getAdminRestriction(); } - return true; - } - public USER_LEVEL getAdminRestriction() { - return this.adminRestriction; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PrnfbSettingsData other = (PrnfbSettingsData) obj; + if (this.adminRestriction != other.adminRestriction) { + return false; + } + if (this.keyStore == null) { + if (other.keyStore != null) { + return false; + } + } else if (!this.keyStore.equals(other.keyStore)) { + return false; + } + if (this.keyStorePassword == null) { + if (other.keyStorePassword != null) { + return false; + } + } else if (!this.keyStorePassword.equals(other.keyStorePassword)) { + return false; + } + if (this.keyStoreType == null) { + if (other.keyStoreType != null) { + return false; + } + } else if (!this.keyStoreType.equals(other.keyStoreType)) { + return false; + } + if (this.shouldAcceptAnyCertificate != other.shouldAcceptAnyCertificate) { + return false; + } + return true; + } - public Optional getKeyStore() { - return fromNullable(this.keyStore); - } + public USER_LEVEL getAdminRestriction() { + return this.adminRestriction; + } - public Optional getKeyStorePassword() { - return fromNullable(this.keyStorePassword); - } + public Optional getKeyStore() { + return fromNullable(this.keyStore); + } - public String getKeyStoreType() { - return this.keyStoreType; - } + public Optional getKeyStorePassword() { + return fromNullable(this.keyStorePassword); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.adminRestriction == null) ? 0 : this.adminRestriction.hashCode()); - result = prime * result + ((this.keyStore == null) ? 0 : this.keyStore.hashCode()); - result = prime * result + ((this.keyStorePassword == null) ? 0 : this.keyStorePassword.hashCode()); - result = prime * result + ((this.keyStoreType == null) ? 0 : this.keyStoreType.hashCode()); - result = prime * result + (this.shouldAcceptAnyCertificate ? 1231 : 1237); - return result; - } + public String getKeyStoreType() { + return this.keyStoreType; + } - public boolean isShouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = + prime * result + ((this.adminRestriction == null) ? 0 : this.adminRestriction.hashCode()); + result = prime * result + ((this.keyStore == null) ? 0 : this.keyStore.hashCode()); + result = + prime * result + ((this.keyStorePassword == null) ? 0 : this.keyStorePassword.hashCode()); + result = prime * result + ((this.keyStoreType == null) ? 0 : this.keyStoreType.hashCode()); + result = prime * result + (this.shouldAcceptAnyCertificate ? 1231 : 1237); + return result; + } - @Override - public String toString() { - return "PrnfbSettingsData [keyStore=" + this.keyStore + ", keyStoreType=" + this.keyStoreType + ", keyStorePassword=" - + this.keyStorePassword + ", shouldAcceptAnyCertificate=" + this.shouldAcceptAnyCertificate + ", adminRestriction=" - + this.adminRestriction + "]"; - } + public boolean isShouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; + } -} \ No newline at end of file + @Override + public String toString() { + return "PrnfbSettingsData [keyStore=" + + this.keyStore + + ", keyStoreType=" + + this.keyStoreType + + ", keyStorePassword=" + + this.keyStorePassword + + ", shouldAcceptAnyCertificate=" + + this.shouldAcceptAnyCertificate + + ", adminRestriction=" + + this.adminRestriction + + "]"; + } +} diff --git a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsDataBuilder.java b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsDataBuilder.java index 3c4b04a2..de144001 100644 --- a/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsDataBuilder.java +++ b/src/main/java/se/bjurr/prnfb/settings/PrnfbSettingsDataBuilder.java @@ -1,76 +1,76 @@ package se.bjurr.prnfb.settings; public class PrnfbSettingsDataBuilder { - public static PrnfbSettingsDataBuilder prnfbSettingsDataBuilder() { - return new PrnfbSettingsDataBuilder(); - } - - public static PrnfbSettingsDataBuilder prnfbSettingsDataBuilder(PrnfbSettingsData settings) { - return new PrnfbSettingsDataBuilder(settings); - } - - private USER_LEVEL adminRestriction; - private String keyStore; - private String keyStorePassword; - private String keyStoreType; - private boolean shouldAcceptAnyCertificate; - - private PrnfbSettingsDataBuilder() { - } - - private PrnfbSettingsDataBuilder(PrnfbSettingsData settings) { - this.shouldAcceptAnyCertificate = settings.isShouldAcceptAnyCertificate(); - this.keyStore = settings.getKeyStore().orNull(); - this.keyStoreType = settings.getKeyStoreType(); - this.keyStorePassword = settings.getKeyStorePassword().orNull(); - } - - public PrnfbSettingsData build() { - return new PrnfbSettingsData(this); - } - - public USER_LEVEL getAdminRestriction() { - return this.adminRestriction; - } - - public String getKeyStore() { - return this.keyStore; - } - - public String getKeyStorePassword() { - return this.keyStorePassword; - } - - public String getKeyStoreType() { - return this.keyStoreType; - } - - public PrnfbSettingsDataBuilder setAdminRestriction(USER_LEVEL adminRestriction) { - this.adminRestriction = adminRestriction; - return this; - } - - public PrnfbSettingsDataBuilder setKeyStore(String keyStore) { - this.keyStore = keyStore; - return this; - } - - public PrnfbSettingsDataBuilder setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - return this; - } - - public PrnfbSettingsDataBuilder setKeyStoreType(String keyStoreType) { - this.keyStoreType = keyStoreType; - return this; - } - - public PrnfbSettingsDataBuilder setShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { - this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; - return this; - } - - public boolean shouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } + public static PrnfbSettingsDataBuilder prnfbSettingsDataBuilder() { + return new PrnfbSettingsDataBuilder(); + } + + public static PrnfbSettingsDataBuilder prnfbSettingsDataBuilder(PrnfbSettingsData settings) { + return new PrnfbSettingsDataBuilder(settings); + } + + private USER_LEVEL adminRestriction; + private String keyStore; + private String keyStorePassword; + private String keyStoreType; + private boolean shouldAcceptAnyCertificate; + + private PrnfbSettingsDataBuilder() {} + + private PrnfbSettingsDataBuilder(PrnfbSettingsData settings) { + this.shouldAcceptAnyCertificate = settings.isShouldAcceptAnyCertificate(); + this.keyStore = settings.getKeyStore().orNull(); + this.keyStoreType = settings.getKeyStoreType(); + this.keyStorePassword = settings.getKeyStorePassword().orNull(); + } + + public PrnfbSettingsData build() { + return new PrnfbSettingsData(this); + } + + public USER_LEVEL getAdminRestriction() { + return this.adminRestriction; + } + + public String getKeyStore() { + return this.keyStore; + } + + public String getKeyStorePassword() { + return this.keyStorePassword; + } + + public String getKeyStoreType() { + return this.keyStoreType; + } + + public PrnfbSettingsDataBuilder setAdminRestriction(USER_LEVEL adminRestriction) { + this.adminRestriction = adminRestriction; + return this; + } + + public PrnfbSettingsDataBuilder setKeyStore(String keyStore) { + this.keyStore = keyStore; + return this; + } + + public PrnfbSettingsDataBuilder setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + return this; + } + + public PrnfbSettingsDataBuilder setKeyStoreType(String keyStoreType) { + this.keyStoreType = keyStoreType; + return this; + } + + public PrnfbSettingsDataBuilder setShouldAcceptAnyCertificate( + boolean shouldAcceptAnyCertificate) { + this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; + return this; + } + + public boolean shouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/TRIGGER_IF_MERGE.java b/src/main/java/se/bjurr/prnfb/settings/TRIGGER_IF_MERGE.java index 70082e22..bacb2aea 100644 --- a/src/main/java/se/bjurr/prnfb/settings/TRIGGER_IF_MERGE.java +++ b/src/main/java/se/bjurr/prnfb/settings/TRIGGER_IF_MERGE.java @@ -1,5 +1,7 @@ package se.bjurr.prnfb.settings; public enum TRIGGER_IF_MERGE { - ALWAYS, CONFLICTING, NOT_CONFLICTING + ALWAYS, + CONFLICTING, + NOT_CONFLICTING } diff --git a/src/main/java/se/bjurr/prnfb/settings/USER_LEVEL.java b/src/main/java/se/bjurr/prnfb/settings/USER_LEVEL.java index 68a66e4f..f8ad6649 100644 --- a/src/main/java/se/bjurr/prnfb/settings/USER_LEVEL.java +++ b/src/main/java/se/bjurr/prnfb/settings/USER_LEVEL.java @@ -1,5 +1,7 @@ package se.bjurr.prnfb.settings; public enum USER_LEVEL { - ADMIN, EVERYONE, SYSTEM_ADMIN + ADMIN, + EVERYONE, + SYSTEM_ADMIN } diff --git a/src/main/java/se/bjurr/prnfb/settings/ValidationException.java b/src/main/java/se/bjurr/prnfb/settings/ValidationException.java index bfd5ce48..6aa25bc1 100644 --- a/src/main/java/se/bjurr/prnfb/settings/ValidationException.java +++ b/src/main/java/se/bjurr/prnfb/settings/ValidationException.java @@ -1,30 +1,30 @@ package se.bjurr.prnfb.settings; public class ValidationException extends Exception { - private static final long serialVersionUID = 2203598567281456784L; - private final String error; - private final String field; + private static final long serialVersionUID = 2203598567281456784L; + private final String error; + private final String field; - public ValidationException() { - this.error = null; - this.field = null; - } + public ValidationException() { + this.error = null; + this.field = null; + } - public ValidationException(String field, String error) { - this.error = error; - this.field = field; - } + public ValidationException(String field, String error) { + this.error = error; + this.field = field; + } - public String getError() { - return this.error; - } + public String getError() { + return this.error; + } - public String getField() { - return this.field; - } + public String getField() { + return this.field; + } - @Override - public String getMessage() { - return this.field + "=" + this.error; - } + @Override + public String getMessage() { + return this.field + "=" + this.error; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/AdminFormValues.java b/src/main/java/se/bjurr/prnfb/settings/legacy/AdminFormValues.java index 9da237ef..465b67ff 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/AdminFormValues.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/AdminFormValues.java @@ -11,55 +11,62 @@ @XmlAccessorType(XmlAccessType.FIELD) @Deprecated public final class AdminFormValues extends ArrayList> { - public enum BUTTON_VISIBILITY { - ADMIN, EVERYONE, NONE, SYSTEM_ADMIN - } + public enum BUTTON_VISIBILITY { + ADMIN, + EVERYONE, + NONE, + SYSTEM_ADMIN + } - public enum FIELDS { - accept_any_certificate, // - admin_allowed, // - button_title, // - button_visibility, // - events, // - filter_regexp, // - filter_string, // - FORM_IDENTIFIER, // - FORM_TYPE, // - header_name, // - header_value, // - injection_url, // - injection_url_regexp, // - key_store, // - key_store_password, // - key_store_type, // - method, // - name, // - password, // - post_content, // - proxy_password, // - proxy_port, // - proxy_server, // - proxy_user, // - trigger_if_isconflicting, // - trigger_ignore_state, // - url, // - user, // - user_allowed; - } + public enum FIELDS { + accept_any_certificate, // + admin_allowed, // + button_title, // + button_visibility, // + events, // + filter_regexp, // + filter_string, // + FORM_IDENTIFIER, // + FORM_TYPE, // + header_name, // + header_value, // + injection_url, // + injection_url_regexp, // + key_store, // + key_store_password, // + key_store_type, // + method, // + name, // + password, // + post_content, // + proxy_password, // + proxy_port, // + proxy_server, // + proxy_user, // + trigger_if_isconflicting, // + trigger_ignore_state, // + url, // + user, // + user_allowed; + } - public enum FORM_TYPE { - BUTTON_CONFIG_FORM, GLOBAL_SETTINGS, TRIGGER_CONFIG_FORM - } + public enum FORM_TYPE { + BUTTON_CONFIG_FORM, + GLOBAL_SETTINGS, + TRIGGER_CONFIG_FORM + } - public enum TRIGGER_IF_MERGE { - ALWAYS, CONFLICTING, NOT_CONFLICTING - } + public enum TRIGGER_IF_MERGE { + ALWAYS, + CONFLICTING, + NOT_CONFLICTING + } - public static final String DEFAULT_NAME = "Unnamed trigger";; + public static final String DEFAULT_NAME = "Unnamed trigger";; - public static final String NAME = "name";; + public static final String NAME = "name";; - public static final String VALUE = "value";; + public static final String VALUE = "value";; - private static final long serialVersionUID = 9084184120202816120L; + private static final long serialVersionUID = 9084184120202816120L; } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/Header.java b/src/main/java/se/bjurr/prnfb/settings/legacy/Header.java index 5c63e706..38fbd0ac 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/Header.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/Header.java @@ -7,19 +7,19 @@ @Deprecated public class Header { - private final String name; - private final String value; + private final String name; + private final String value; - public Header(String name, String value) { - this.name = checkNotNull(emptyToNull(nullToEmpty(name).trim())); - this.value = checkNotNull(emptyToNull(nullToEmpty(value).trim())); - } + public Header(String name, String value) { + this.name = checkNotNull(emptyToNull(nullToEmpty(name).trim())); + this.value = checkNotNull(emptyToNull(nullToEmpty(value).trim())); + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getValue() { - return this.value; - } -} \ No newline at end of file + public String getValue() { + return this.value; + } +} diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbButton.java b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbButton.java index 0578d9bd..91c92cfb 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbButton.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbButton.java @@ -5,30 +5,30 @@ @Deprecated public class PrnfbButton { - private final String formIdentifier; - private final String title; - private final BUTTON_VISIBILITY visibility; - - public PrnfbButton(String title, BUTTON_VISIBILITY visibility, String formIdentifier) { - this.title = title; - this.visibility = visibility; - this.formIdentifier = formIdentifier; - } - - public String getFormIdentifier() { - return this.formIdentifier; - } - - public String getTitle() { - return this.title; - } - - public BUTTON_VISIBILITY getVisibility() { - return this.visibility; - } - - @Override - public String toString() { - return "Title: " + this.title; - } + private final String formIdentifier; + private final String title; + private final BUTTON_VISIBILITY visibility; + + public PrnfbButton(String title, BUTTON_VISIBILITY visibility, String formIdentifier) { + this.title = title; + this.visibility = visibility; + this.formIdentifier = formIdentifier; + } + + public String getFormIdentifier() { + return this.formIdentifier; + } + + public String getTitle() { + return this.title; + } + + public BUTTON_VISIBILITY getVisibility() { + return this.visibility; + } + + @Override + public String toString() { + return "Title: " + this.title; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotification.java b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotification.java index f82bc157..27e243b3 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotification.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotification.java @@ -31,142 +31,151 @@ @Deprecated public class PrnfbNotification { - public static boolean isOfType(AdminFormValues config, FORM_TYPE formType) { - Optional> formTypeOpt = tryFind(config, predicate(AdminFormValues.FIELDS.FORM_TYPE.name())); - return !formTypeOpt.isPresent() && formType.name().equals(TRIGGER_CONFIG_FORM.name()) - || formTypeOpt.get().get(VALUE).equals(TRIGGER_CONFIG_FORM.name()); - } - - private final String filterRegexp; - private final String filterString; - private final List
headers; - private final String injectionUrl; - private final String injectionUrlRegexp; - private final HTTP_METHOD method; - private final String name; - private final String password; - private final String postContent; - private final String proxyPassword; - private final Integer proxyPort; - private final String proxyServer; - private final String proxyUser; - private final TRIGGER_IF_MERGE triggerIfCanMerge; - private final List triggerIgnoreStateList; - private final List triggers; - private final String url; - - private final String user; - - public PrnfbNotification(PrnfbNotificationBuilder builder) throws ValidationException { - this.proxyUser = emptyToNull(nullToEmpty(builder.getProxyUser()).trim()); - this.proxyPassword = emptyToNull(nullToEmpty(builder.getProxyPassword()).trim()); - this.proxyServer = emptyToNull(nullToEmpty(builder.getProxyServer()).trim()); - this.proxyPort = Integer.valueOf(firstNonNull(emptyToNull(nullToEmpty(builder.getProxyPort()).trim()), "-1")); - this.headers = checkNotNull(builder.getHeaders()); - this.postContent = emptyToNull(nullToEmpty(builder.getPostContent()).trim()); - this.method = HTTP_METHOD.valueOf(firstNonNull(emptyToNull(nullToEmpty(builder.getMethod()).trim()), GET.name())); - this.triggerIfCanMerge = TRIGGER_IF_MERGE - .valueOf(firstNonNull(emptyToNull(nullToEmpty(builder.getTriggerIfCanMerge()).trim()), ALWAYS.name())); - if (nullToEmpty(builder.getUrl()).trim().isEmpty()) { - throw new ValidationException(FIELDS.url.name(), "URL not set!"); - } - try { - new URL(builder.getUrl()); - } catch (final Exception e) { - throw new ValidationException(FIELDS.url.name(), "URL not valid!"); - } - if (!nullToEmpty(builder.getFilterRegexp()).trim().isEmpty()) { - try { - compile(builder.getFilterRegexp()); - } catch (final Exception e) { - throw new ValidationException(filter_regexp.name(), - "Filter regexp not valid! " + e.getMessage().replaceAll("\n", " ")); - } - if (nullToEmpty(builder.getFilterString()).trim().isEmpty()) { - throw new ValidationException(filter_string.name(), "Filter string not set, nothing to match regexp against!"); - } - } - this.url = builder.getUrl(); - this.user = emptyToNull(nullToEmpty(builder.getUser()).trim()); - this.password = emptyToNull(nullToEmpty(builder.getPassword()).trim()); - this.triggers = checkNotNull(builder.getTriggers()); - this.filterString = builder.getFilterString(); - this.filterRegexp = builder.getFilterRegexp(); - this.name = firstNonNull(emptyToNull(nullToEmpty(builder.getName()).trim()), DEFAULT_NAME); - this.injectionUrl = emptyToNull(nullToEmpty(builder.getInjectionUrl()).trim()); - this.injectionUrlRegexp = emptyToNull(nullToEmpty(builder.getInjectionUrlRegexp()).trim()); - this.triggerIgnoreStateList = builder.getTriggerIgnoreStateList(); - } - - public Optional getFilterRegexp() { - return fromNullable(this.filterRegexp); - } - - public Optional getFilterString() { - return fromNullable(this.filterString); - } - - public List
getHeaders() { - return this.headers; - } - - public Optional getInjectionUrl() { - return fromNullable(this.injectionUrl); - } - - public Optional getInjectionUrlRegexp() { - return fromNullable(this.injectionUrlRegexp); - } - - public HTTP_METHOD getMethod() { - return this.method; - } - - public String getName() { - return this.name; - } - - public Optional getPassword() { - return fromNullable(this.password); - } - - public Optional getPostContent() { - return fromNullable(this.postContent); - } - - public Optional getProxyPassword() { - return fromNullable(this.proxyPassword); - } - - public Integer getProxyPort() { - return this.proxyPort; - } - - public Optional getProxyServer() { - return fromNullable(this.proxyServer); - } - - public Optional getProxyUser() { - return fromNullable(this.proxyUser); - } - - public TRIGGER_IF_MERGE getTriggerIfCanMerge() { - return this.triggerIfCanMerge; - } - - public List getTriggerIgnoreStateList() { - return this.triggerIgnoreStateList; - } - - public List getTriggers() { - return this.triggers; - } - - public String getUrl() { - return this.url; - } - - public Optional getUser() { - return fromNullable(this.user); - } + public static boolean isOfType(AdminFormValues config, FORM_TYPE formType) { + Optional> formTypeOpt = + tryFind(config, predicate(AdminFormValues.FIELDS.FORM_TYPE.name())); + return !formTypeOpt.isPresent() && formType.name().equals(TRIGGER_CONFIG_FORM.name()) + || formTypeOpt.get().get(VALUE).equals(TRIGGER_CONFIG_FORM.name()); + } + + private final String filterRegexp; + private final String filterString; + private final List
headers; + private final String injectionUrl; + private final String injectionUrlRegexp; + private final HTTP_METHOD method; + private final String name; + private final String password; + private final String postContent; + private final String proxyPassword; + private final Integer proxyPort; + private final String proxyServer; + private final String proxyUser; + private final TRIGGER_IF_MERGE triggerIfCanMerge; + private final List triggerIgnoreStateList; + private final List triggers; + private final String url; + + private final String user; + + public PrnfbNotification(PrnfbNotificationBuilder builder) throws ValidationException { + this.proxyUser = emptyToNull(nullToEmpty(builder.getProxyUser()).trim()); + this.proxyPassword = emptyToNull(nullToEmpty(builder.getProxyPassword()).trim()); + this.proxyServer = emptyToNull(nullToEmpty(builder.getProxyServer()).trim()); + this.proxyPort = + Integer.valueOf( + firstNonNull(emptyToNull(nullToEmpty(builder.getProxyPort()).trim()), "-1")); + this.headers = checkNotNull(builder.getHeaders()); + this.postContent = emptyToNull(nullToEmpty(builder.getPostContent()).trim()); + this.method = + HTTP_METHOD.valueOf( + firstNonNull(emptyToNull(nullToEmpty(builder.getMethod()).trim()), GET.name())); + this.triggerIfCanMerge = + TRIGGER_IF_MERGE.valueOf( + firstNonNull( + emptyToNull(nullToEmpty(builder.getTriggerIfCanMerge()).trim()), ALWAYS.name())); + if (nullToEmpty(builder.getUrl()).trim().isEmpty()) { + throw new ValidationException(FIELDS.url.name(), "URL not set!"); + } + try { + new URL(builder.getUrl()); + } catch (final Exception e) { + throw new ValidationException(FIELDS.url.name(), "URL not valid!"); + } + if (!nullToEmpty(builder.getFilterRegexp()).trim().isEmpty()) { + try { + compile(builder.getFilterRegexp()); + } catch (final Exception e) { + throw new ValidationException( + filter_regexp.name(), + "Filter regexp not valid! " + e.getMessage().replaceAll("\n", " ")); + } + if (nullToEmpty(builder.getFilterString()).trim().isEmpty()) { + throw new ValidationException( + filter_string.name(), "Filter string not set, nothing to match regexp against!"); + } + } + this.url = builder.getUrl(); + this.user = emptyToNull(nullToEmpty(builder.getUser()).trim()); + this.password = emptyToNull(nullToEmpty(builder.getPassword()).trim()); + this.triggers = checkNotNull(builder.getTriggers()); + this.filterString = builder.getFilterString(); + this.filterRegexp = builder.getFilterRegexp(); + this.name = firstNonNull(emptyToNull(nullToEmpty(builder.getName()).trim()), DEFAULT_NAME); + this.injectionUrl = emptyToNull(nullToEmpty(builder.getInjectionUrl()).trim()); + this.injectionUrlRegexp = emptyToNull(nullToEmpty(builder.getInjectionUrlRegexp()).trim()); + this.triggerIgnoreStateList = builder.getTriggerIgnoreStateList(); + } + + public Optional getFilterRegexp() { + return fromNullable(this.filterRegexp); + } + + public Optional getFilterString() { + return fromNullable(this.filterString); + } + + public List
getHeaders() { + return this.headers; + } + + public Optional getInjectionUrl() { + return fromNullable(this.injectionUrl); + } + + public Optional getInjectionUrlRegexp() { + return fromNullable(this.injectionUrlRegexp); + } + + public HTTP_METHOD getMethod() { + return this.method; + } + + public String getName() { + return this.name; + } + + public Optional getPassword() { + return fromNullable(this.password); + } + + public Optional getPostContent() { + return fromNullable(this.postContent); + } + + public Optional getProxyPassword() { + return fromNullable(this.proxyPassword); + } + + public Integer getProxyPort() { + return this.proxyPort; + } + + public Optional getProxyServer() { + return fromNullable(this.proxyServer); + } + + public Optional getProxyUser() { + return fromNullable(this.proxyUser); + } + + public TRIGGER_IF_MERGE getTriggerIfCanMerge() { + return this.triggerIfCanMerge; + } + + public List getTriggerIgnoreStateList() { + return this.triggerIgnoreStateList; + } + + public List getTriggers() { + return this.triggers; + } + + public String getUrl() { + return this.url; + } + + public Optional getUser() { + return fromNullable(this.user); + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotificationBuilder.java b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotificationBuilder.java index 7cbaa917..fb7d00a6 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotificationBuilder.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbNotificationBuilder.java @@ -11,204 +11,203 @@ @Deprecated public class PrnfbNotificationBuilder { - public static PrnfbNotificationBuilder prnfbNotificationBuilder() { - return new PrnfbNotificationBuilder(); - } - - private String filterRegexp; - private String filterString; - private final List
headers = newArrayList(); - private String injectionUrl; - private String injectionUrlRegexp; - private String method; - private String name; - private String password; - private String postContent; - private String proxyPassword; - private String proxyPort; - private String proxyServer; - private String proxyUser; - private boolean shouldAcceptAnyCertificate; - private String triggerIfCanMerge; - private final List triggerIgnoreStateList = newArrayList(); - private final List triggers = newArrayList(); - private String url; - private String user; - - private PrnfbNotificationBuilder() { - } - - public PrnfbNotification build() throws ValidationException { - return new PrnfbNotification(this); - } - - public String getFilterRegexp() { - return this.filterRegexp; - } - - public String getFilterString() { - return this.filterString; - } - - public List
getHeaders() { - return this.headers; - } - - public String getInjectionUrl() { - return this.injectionUrl; - } - - public String getInjectionUrlRegexp() { - return this.injectionUrlRegexp; - } - - public String getMethod() { - return this.method; - } - - public String getName() { - return this.name; - } - - public String getPassword() { - return this.password; - } - - public String getPostContent() { - return this.postContent; - } - - public String getProxyPassword() { - return this.proxyPassword; - } - - public String getProxyPort() { - return this.proxyPort; - } - - public String getProxyServer() { - return this.proxyServer; - } - - public String getProxyUser() { - return this.proxyUser; - } - - public String getTriggerIfCanMerge() { - return this.triggerIfCanMerge; - } - - public List getTriggerIgnoreStateList() { - return this.triggerIgnoreStateList; - } - - public List getTriggers() { - return this.triggers; - } - - public String getUrl() { - return this.url; - } - - public String getUser() { - return this.user; - } - - public void setShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { - this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; - } - - public boolean shouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } - - public PrnfbNotificationBuilder withFilterRegexp(String filterRegexp) { - this.filterRegexp = checkNotNull(filterRegexp); - return this; - } - - public PrnfbNotificationBuilder withFilterString(String filterString) { - this.filterString = checkNotNull(filterString); - return this; - } - - public PrnfbNotificationBuilder withHeader(String name, String value) { - this.headers.add(new Header(checkNotNull(name), checkNotNull(value))); - return this; - } - - public PrnfbNotificationBuilder withInjectionUrl(String injectionUrl) { - this.injectionUrl = checkNotNull(injectionUrl); - return this; - } - - public PrnfbNotificationBuilder withInjectionUrlRegexp(String injectionUrlRegexp) { - this.injectionUrlRegexp = checkNotNull(injectionUrlRegexp); - return this; - } - - public PrnfbNotificationBuilder withMethod(String method) { - this.method = checkNotNull(method); - return this; - } - - public PrnfbNotificationBuilder withName(String name) { - this.name = name; - return this; - } - - public PrnfbNotificationBuilder withPassword(String password) { - this.password = checkNotNull(password); - return this; - } - - public PrnfbNotificationBuilder withPostContent(String postContent) { - this.postContent = checkNotNull(postContent); - return this; - } - - public PrnfbNotificationBuilder withProxyPassword(String s) { - this.proxyPassword = checkNotNull(s); - return this; - } - - public PrnfbNotificationBuilder withProxyPort(String s) { - this.proxyPort = checkNotNull(s); - return this; - } - - public PrnfbNotificationBuilder withProxyServer(String s) { - this.proxyServer = checkNotNull(s); - return this; - } - - public PrnfbNotificationBuilder withProxyUser(String s) { - this.proxyUser = checkNotNull(s); - return this; - } - - public PrnfbNotificationBuilder withTrigger(PrnfbPullRequestAction trigger) { - this.triggers.add(checkNotNull(trigger)); - return this; - } - - public PrnfbNotificationBuilder withTriggerIfCanMerge(String triggerIfCanMerge) { - this.triggerIfCanMerge = triggerIfCanMerge; - return this; - } - - public PrnfbNotificationBuilder withTriggerIgnoreState(PullRequestState triggerIgnoreState) { - this.triggerIgnoreStateList.add(checkNotNull(triggerIgnoreState)); - return this; - } - - public PrnfbNotificationBuilder withUrl(String url) { - this.url = checkNotNull(url); - return this; - } - - public PrnfbNotificationBuilder withUser(String user) { - this.user = checkNotNull(user); - return this; - } + public static PrnfbNotificationBuilder prnfbNotificationBuilder() { + return new PrnfbNotificationBuilder(); + } + + private String filterRegexp; + private String filterString; + private final List
headers = newArrayList(); + private String injectionUrl; + private String injectionUrlRegexp; + private String method; + private String name; + private String password; + private String postContent; + private String proxyPassword; + private String proxyPort; + private String proxyServer; + private String proxyUser; + private boolean shouldAcceptAnyCertificate; + private String triggerIfCanMerge; + private final List triggerIgnoreStateList = newArrayList(); + private final List triggers = newArrayList(); + private String url; + private String user; + + private PrnfbNotificationBuilder() {} + + public PrnfbNotification build() throws ValidationException { + return new PrnfbNotification(this); + } + + public String getFilterRegexp() { + return this.filterRegexp; + } + + public String getFilterString() { + return this.filterString; + } + + public List
getHeaders() { + return this.headers; + } + + public String getInjectionUrl() { + return this.injectionUrl; + } + + public String getInjectionUrlRegexp() { + return this.injectionUrlRegexp; + } + + public String getMethod() { + return this.method; + } + + public String getName() { + return this.name; + } + + public String getPassword() { + return this.password; + } + + public String getPostContent() { + return this.postContent; + } + + public String getProxyPassword() { + return this.proxyPassword; + } + + public String getProxyPort() { + return this.proxyPort; + } + + public String getProxyServer() { + return this.proxyServer; + } + + public String getProxyUser() { + return this.proxyUser; + } + + public String getTriggerIfCanMerge() { + return this.triggerIfCanMerge; + } + + public List getTriggerIgnoreStateList() { + return this.triggerIgnoreStateList; + } + + public List getTriggers() { + return this.triggers; + } + + public String getUrl() { + return this.url; + } + + public String getUser() { + return this.user; + } + + public void setShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { + this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; + } + + public boolean shouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; + } + + public PrnfbNotificationBuilder withFilterRegexp(String filterRegexp) { + this.filterRegexp = checkNotNull(filterRegexp); + return this; + } + + public PrnfbNotificationBuilder withFilterString(String filterString) { + this.filterString = checkNotNull(filterString); + return this; + } + + public PrnfbNotificationBuilder withHeader(String name, String value) { + this.headers.add(new Header(checkNotNull(name), checkNotNull(value))); + return this; + } + + public PrnfbNotificationBuilder withInjectionUrl(String injectionUrl) { + this.injectionUrl = checkNotNull(injectionUrl); + return this; + } + + public PrnfbNotificationBuilder withInjectionUrlRegexp(String injectionUrlRegexp) { + this.injectionUrlRegexp = checkNotNull(injectionUrlRegexp); + return this; + } + + public PrnfbNotificationBuilder withMethod(String method) { + this.method = checkNotNull(method); + return this; + } + + public PrnfbNotificationBuilder withName(String name) { + this.name = name; + return this; + } + + public PrnfbNotificationBuilder withPassword(String password) { + this.password = checkNotNull(password); + return this; + } + + public PrnfbNotificationBuilder withPostContent(String postContent) { + this.postContent = checkNotNull(postContent); + return this; + } + + public PrnfbNotificationBuilder withProxyPassword(String s) { + this.proxyPassword = checkNotNull(s); + return this; + } + + public PrnfbNotificationBuilder withProxyPort(String s) { + this.proxyPort = checkNotNull(s); + return this; + } + + public PrnfbNotificationBuilder withProxyServer(String s) { + this.proxyServer = checkNotNull(s); + return this; + } + + public PrnfbNotificationBuilder withProxyUser(String s) { + this.proxyUser = checkNotNull(s); + return this; + } + + public PrnfbNotificationBuilder withTrigger(PrnfbPullRequestAction trigger) { + this.triggers.add(checkNotNull(trigger)); + return this; + } + + public PrnfbNotificationBuilder withTriggerIfCanMerge(String triggerIfCanMerge) { + this.triggerIfCanMerge = triggerIfCanMerge; + return this; + } + + public PrnfbNotificationBuilder withTriggerIgnoreState(PullRequestState triggerIgnoreState) { + this.triggerIgnoreStateList.add(checkNotNull(triggerIgnoreState)); + return this; + } + + public PrnfbNotificationBuilder withUrl(String url) { + this.url = checkNotNull(url); + return this; + } + + public PrnfbNotificationBuilder withUser(String user) { + this.user = checkNotNull(user); + return this; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbPredicates.java b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbPredicates.java index c87a77ff..a402627e 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbPredicates.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbPredicates.java @@ -8,16 +8,14 @@ @Deprecated public class PrnfbPredicates { - public static Predicate> predicate(final String name) { - return new Predicate>() { - @Override - public boolean apply(Map input) { - return input.get(NAME) != null && input.get(NAME).equals(name); - } - }; - } - - private PrnfbPredicates() { - } + public static Predicate> predicate(final String name) { + return new Predicate>() { + @Override + public boolean apply(Map input) { + return input.get(NAME) != null && input.get(NAME).equals(name); + } + }; + } + private PrnfbPredicates() {} } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettings.java b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettings.java index 66b1bf1f..81f767e6 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettings.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettings.java @@ -11,55 +11,55 @@ @Deprecated public class PrnfbSettings { - private final boolean adminsAllowed; - private final List buttons; - private final String keyStore; - private final String keyStorePassword; - private final String keyStoreType; - private List notifications = newArrayList(); - private final boolean shouldAcceptAnyCertificate; - private final boolean usersAllowed; + private final boolean adminsAllowed; + private final List buttons; + private final String keyStore; + private final String keyStorePassword; + private final String keyStoreType; + private List notifications = newArrayList(); + private final boolean shouldAcceptAnyCertificate; + private final boolean usersAllowed; - public PrnfbSettings(PrnfbSettingsBuilder builder) { - this.notifications = checkNotNull(builder.getNotifications()); - this.buttons = checkNotNull(builder.getButtons()); - this.usersAllowed = builder.isUsersAllowed(); - this.adminsAllowed = builder.isAdminsAllowed(); - this.keyStore = emptyToNull(builder.getKeyStore()); - this.keyStoreType = builder.getKeyStoreType(); - this.keyStorePassword = emptyToNull(builder.getKeyStorePassword()); - this.shouldAcceptAnyCertificate = builder.shouldAcceptAnyCertificate(); - } + public PrnfbSettings(PrnfbSettingsBuilder builder) { + this.notifications = checkNotNull(builder.getNotifications()); + this.buttons = checkNotNull(builder.getButtons()); + this.usersAllowed = builder.isUsersAllowed(); + this.adminsAllowed = builder.isAdminsAllowed(); + this.keyStore = emptyToNull(builder.getKeyStore()); + this.keyStoreType = builder.getKeyStoreType(); + this.keyStorePassword = emptyToNull(builder.getKeyStorePassword()); + this.shouldAcceptAnyCertificate = builder.shouldAcceptAnyCertificate(); + } - public List getButtons() { - return this.buttons; - } + public List getButtons() { + return this.buttons; + } - public Optional getKeyStore() { - return fromNullable(this.keyStore); - } + public Optional getKeyStore() { + return fromNullable(this.keyStore); + } - public Optional getKeyStorePassword() { - return fromNullable(this.keyStorePassword); - } + public Optional getKeyStorePassword() { + return fromNullable(this.keyStorePassword); + } - public String getKeyStoreType() { - return this.keyStoreType; - } + public String getKeyStoreType() { + return this.keyStoreType; + } - public List getNotifications() { - return this.notifications; - } + public List getNotifications() { + return this.notifications; + } - public boolean isAdminsAllowed() { - return this.adminsAllowed; - } + public boolean isAdminsAllowed() { + return this.adminsAllowed; + } - public boolean isUsersAllowed() { - return this.usersAllowed; - } + public boolean isUsersAllowed() { + return this.usersAllowed; + } - public boolean shouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } + public boolean shouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettingsBuilder.java b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettingsBuilder.java index 6df6283f..2bdd3edd 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettingsBuilder.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/PrnfbSettingsBuilder.java @@ -6,94 +6,93 @@ @Deprecated public class PrnfbSettingsBuilder { - public static PrnfbSettingsBuilder prnfbSettingsBuilder() { - return new PrnfbSettingsBuilder(); - } - - private boolean adminsAllowed; - private final List buttons = newArrayList(); - private String keyStore; - private String keyStorePassword; - private String keyStoreType; - private final List notifications = newArrayList(); - private boolean shouldAcceptAnyCertificate; - private boolean usersAllowed; - - private PrnfbSettingsBuilder() { - } - - public PrnfbSettings build() { - return new PrnfbSettings(this); - } - - public List getButtons() { - return this.buttons; - } - - public String getKeyStore() { - return this.keyStore; - } - - public String getKeyStorePassword() { - return this.keyStorePassword; - } - - public String getKeyStoreType() { - return this.keyStoreType; - } - - public List getNotifications() { - return this.notifications; - } - - public boolean isAdminsAllowed() { - return this.adminsAllowed; - } - - public boolean isUsersAllowed() { - return this.usersAllowed; - } - - public PrnfbSettingsBuilder setKeyStore(String keyStore) { - this.keyStore = keyStore; - return this; - } - - public PrnfbSettingsBuilder setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - return this; - } - - public PrnfbSettingsBuilder setKeyStoreType(String keyStoreType) { - this.keyStoreType = keyStoreType; - return this; - } - - public boolean shouldAcceptAnyCertificate() { - return this.shouldAcceptAnyCertificate; - } - - public PrnfbSettingsBuilder withAdminsAllowed(boolean allowed) { - this.adminsAllowed = allowed; - return this; - } - - public void withButton(PrnfbButton prnfbButton) { - this.buttons.add(prnfbButton); - } - - public PrnfbSettingsBuilder withNotification(PrnfbNotification notification) { - this.notifications.add(notification); - return this; - } - - public PrnfbSettingsBuilder withShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { - this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; - return this; - } - - public PrnfbSettingsBuilder withUsersAllowed(boolean allowed) { - this.usersAllowed = allowed; - return this; - } + public static PrnfbSettingsBuilder prnfbSettingsBuilder() { + return new PrnfbSettingsBuilder(); + } + + private boolean adminsAllowed; + private final List buttons = newArrayList(); + private String keyStore; + private String keyStorePassword; + private String keyStoreType; + private final List notifications = newArrayList(); + private boolean shouldAcceptAnyCertificate; + private boolean usersAllowed; + + private PrnfbSettingsBuilder() {} + + public PrnfbSettings build() { + return new PrnfbSettings(this); + } + + public List getButtons() { + return this.buttons; + } + + public String getKeyStore() { + return this.keyStore; + } + + public String getKeyStorePassword() { + return this.keyStorePassword; + } + + public String getKeyStoreType() { + return this.keyStoreType; + } + + public List getNotifications() { + return this.notifications; + } + + public boolean isAdminsAllowed() { + return this.adminsAllowed; + } + + public boolean isUsersAllowed() { + return this.usersAllowed; + } + + public PrnfbSettingsBuilder setKeyStore(String keyStore) { + this.keyStore = keyStore; + return this; + } + + public PrnfbSettingsBuilder setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + return this; + } + + public PrnfbSettingsBuilder setKeyStoreType(String keyStoreType) { + this.keyStoreType = keyStoreType; + return this; + } + + public boolean shouldAcceptAnyCertificate() { + return this.shouldAcceptAnyCertificate; + } + + public PrnfbSettingsBuilder withAdminsAllowed(boolean allowed) { + this.adminsAllowed = allowed; + return this; + } + + public void withButton(PrnfbButton prnfbButton) { + this.buttons.add(prnfbButton); + } + + public PrnfbSettingsBuilder withNotification(PrnfbNotification notification) { + this.notifications.add(notification); + return this; + } + + public PrnfbSettingsBuilder withShouldAcceptAnyCertificate(boolean shouldAcceptAnyCertificate) { + this.shouldAcceptAnyCertificate = shouldAcceptAnyCertificate; + return this; + } + + public PrnfbSettingsBuilder withUsersAllowed(boolean allowed) { + this.usersAllowed = allowed; + return this; + } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/SettingsStorage.java b/src/main/java/se/bjurr/prnfb/settings/legacy/SettingsStorage.java index a1f27bd4..33c27457 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/SettingsStorage.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/SettingsStorage.java @@ -69,249 +69,280 @@ @Deprecated public class SettingsStorage { - public static final String STORAGE_KEY = "se.bjurr.prnfb.admin.AdminFormValues_2"; - public static final String STORAGE_KEY_PRNFS = "se.bjurr.prnfs.admin.AdminFormValues_2"; + public static final String STORAGE_KEY = "se.bjurr.prnfb.admin.AdminFormValues_2"; + public static final String STORAGE_KEY_PRNFS = "se.bjurr.prnfs.admin.AdminFormValues_2"; - private static final Gson gson = new Gson(); + private static final Gson gson = new Gson(); - private static Logger logger = Logger.getLogger(SettingsStorage.class.getName()); - private static Random random = new Random(currentTimeMillis()); + private static Logger logger = Logger.getLogger(SettingsStorage.class.getName()); + private static Random random = new Random(currentTimeMillis()); - public static void checkFieldsRecognized(AdminFormValues adminFormValues) throws ValidationException { - for (final Map m : adminFormValues) { - for (final Entry entry : m.entrySet()) { - if (entry.getKey().equals(NAME)) { - if (valueOf(entry.getValue()) == null) { - throw new ValidationException(entry.getValue(), "Field not recognized!"); - } - } else if (!entry.getKey().equals(VALUE)) { - throw new ValidationException(entry.getKey(), "Key not recognized!"); + public static void checkFieldsRecognized(AdminFormValues adminFormValues) + throws ValidationException { + for (final Map m : adminFormValues) { + for (final Entry entry : m.entrySet()) { + if (entry.getKey().equals(NAME)) { + if (valueOf(entry.getValue()) == null) { + throw new ValidationException(entry.getValue(), "Field not recognized!"); + } + } else if (!entry.getKey().equals(VALUE)) { + throw new ValidationException(entry.getKey(), "Key not recognized!"); + } + } } - } } - } - public static void deleteSettings(PluginSettings pluginSettings, String id) { - final Map map = getNotificationsMap(pluginSettings); - map.remove(id); - try { - storeNotificationsMap(pluginSettings, map); - } catch (final ValidationException e) { - logger.log(SEVERE, "", e); + public static void deleteSettings(PluginSettings pluginSettings, String id) { + final Map map = getNotificationsMap(pluginSettings); + map.remove(id); + try { + storeNotificationsMap(pluginSettings, map); + } catch (final ValidationException e) { + logger.log(SEVERE, "", e); + } } - } - - @VisibleForTesting - public static void fakeRandom(Random random) { - SettingsStorage.random = random; - } - - public static String formIdentifierGnerator() { - return random.nextLong() + ""; - } - - @VisibleForTesting - public static Logger getLogger() { - return logger; - } - public static PrnfbButton getPrnfbButton(AdminFormValues adminFormValues) throws ValidationException { - final Optional> titleOpt = tryFind(adminFormValues, predicate(button_title.name())); - String title = "Trigger Notification"; - if (titleOpt.isPresent()) { - title = titleOpt.get().get(VALUE); + @VisibleForTesting + public static void fakeRandom(Random random) { + SettingsStorage.random = random; } - final Optional> visibilityOpt = tryFind(adminFormValues, predicate(button_visibility.name())); - BUTTON_VISIBILITY visibility = NONE; - if (visibilityOpt.isPresent()) { - visibility = BUTTON_VISIBILITY.valueOf(visibilityOpt.get().get(VALUE)); + public static String formIdentifierGnerator() { + return random.nextLong() + ""; } - return new PrnfbButton(title, visibility, find(adminFormValues, predicate(FORM_IDENTIFIER.name())).get(VALUE)); - } - public static PrnfbNotification getPrnfbNotification(AdminFormValues adminFormValues) throws ValidationException { - final Optional> urlOpt = tryFind(adminFormValues, predicate(url.name())); - if (!urlOpt.isPresent()) { - throw new ValidationException("url", "URL not set"); - } - final PrnfbNotificationBuilder prnfbNotificationBuilder = prnfbNotificationBuilder().withUrl(urlOpt.get().get(VALUE)); - for (final Map event : filter(adminFormValues, predicate(events.name()))) { - prnfbNotificationBuilder.withTrigger(PrnfbPullRequestAction.valueOf(event.get(VALUE))); - } - Iterator> headerValues = filter(adminFormValues, predicate(header_value.name())).iterator(); - for (final Map headerName : filter(adminFormValues, predicate(header_name.name()))) { - if (headerName.get(VALUE).trim().isEmpty()) { - continue; - } - String headerValue = headerValues.next().get(VALUE); - if (isNullOrEmpty(headerValue)) { - throw new ValidationException(header_value.name(), "Value cannot be null"); - } - prnfbNotificationBuilder.withHeader(headerName.get(VALUE), headerValue); - } - if (tryFind(adminFormValues, predicate(proxy_server.name())).isPresent()) { - prnfbNotificationBuilder.withProxyServer(find(adminFormValues, predicate(proxy_server.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(proxy_port.name())).isPresent()) { - prnfbNotificationBuilder.withProxyPort(find(adminFormValues, predicate(proxy_port.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(proxy_user.name())).isPresent()) { - prnfbNotificationBuilder.withProxyUser(find(adminFormValues, predicate(proxy_user.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(proxy_password.name())).isPresent()) { - prnfbNotificationBuilder.withProxyPassword(find(adminFormValues, predicate(proxy_password.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(user.name())).isPresent()) { - prnfbNotificationBuilder.withUser(find(adminFormValues, predicate(user.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(password.name())).isPresent()) { - prnfbNotificationBuilder.withPassword(find(adminFormValues, predicate(password.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(filter_string.name())).isPresent()) { - prnfbNotificationBuilder.withFilterString(find(adminFormValues, predicate(filter_string.name())).get(VALUE)); + @VisibleForTesting + public static Logger getLogger() { + return logger; } - if (tryFind(adminFormValues, predicate(filter_regexp.name())).isPresent()) { - prnfbNotificationBuilder.withFilterRegexp(find(adminFormValues, predicate(filter_regexp.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(method.name())).isPresent()) { - prnfbNotificationBuilder.withMethod(find(adminFormValues, predicate(method.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(post_content.name())).isPresent()) { - prnfbNotificationBuilder.withPostContent(find(adminFormValues, predicate(post_content.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(name.name())).isPresent()) { - prnfbNotificationBuilder.withName(find(adminFormValues, predicate(name.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(injection_url.name())).isPresent()) { - prnfbNotificationBuilder.withInjectionUrl(find(adminFormValues, predicate(injection_url.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(injection_url_regexp.name())).isPresent()) { - prnfbNotificationBuilder - .withInjectionUrlRegexp(find(adminFormValues, predicate(injection_url_regexp.name())).get(VALUE)); - } - if (tryFind(adminFormValues, predicate(trigger_if_isconflicting.name())).isPresent()) { - prnfbNotificationBuilder - .withTriggerIfCanMerge(find(adminFormValues, predicate(trigger_if_isconflicting.name())).get(VALUE)); + + public static PrnfbButton getPrnfbButton(AdminFormValues adminFormValues) + throws ValidationException { + final Optional> titleOpt = + tryFind(adminFormValues, predicate(button_title.name())); + String title = "Trigger Notification"; + if (titleOpt.isPresent()) { + title = titleOpt.get().get(VALUE); + } + + final Optional> visibilityOpt = + tryFind(adminFormValues, predicate(button_visibility.name())); + BUTTON_VISIBILITY visibility = NONE; + if (visibilityOpt.isPresent()) { + visibility = BUTTON_VISIBILITY.valueOf(visibilityOpt.get().get(VALUE)); + } + return new PrnfbButton( + title, visibility, find(adminFormValues, predicate(FORM_IDENTIFIER.name())).get(VALUE)); } - for (final Map event : filter(adminFormValues, predicate(trigger_ignore_state.name()))) { - prnfbNotificationBuilder.withTriggerIgnoreState(PullRequestState.valueOf(event.get(VALUE))); + + public static PrnfbNotification getPrnfbNotification(AdminFormValues adminFormValues) + throws ValidationException { + final Optional> urlOpt = tryFind(adminFormValues, predicate(url.name())); + if (!urlOpt.isPresent()) { + throw new ValidationException("url", "URL not set"); + } + final PrnfbNotificationBuilder prnfbNotificationBuilder = + prnfbNotificationBuilder().withUrl(urlOpt.get().get(VALUE)); + for (final Map event : filter(adminFormValues, predicate(events.name()))) { + prnfbNotificationBuilder.withTrigger(PrnfbPullRequestAction.valueOf(event.get(VALUE))); + } + Iterator> headerValues = + filter(adminFormValues, predicate(header_value.name())).iterator(); + for (final Map headerName : + filter(adminFormValues, predicate(header_name.name()))) { + if (headerName.get(VALUE).trim().isEmpty()) { + continue; + } + String headerValue = headerValues.next().get(VALUE); + if (isNullOrEmpty(headerValue)) { + throw new ValidationException(header_value.name(), "Value cannot be null"); + } + prnfbNotificationBuilder.withHeader(headerName.get(VALUE), headerValue); + } + if (tryFind(adminFormValues, predicate(proxy_server.name())).isPresent()) { + prnfbNotificationBuilder.withProxyServer( + find(adminFormValues, predicate(proxy_server.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(proxy_port.name())).isPresent()) { + prnfbNotificationBuilder.withProxyPort( + find(adminFormValues, predicate(proxy_port.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(proxy_user.name())).isPresent()) { + prnfbNotificationBuilder.withProxyUser( + find(adminFormValues, predicate(proxy_user.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(proxy_password.name())).isPresent()) { + prnfbNotificationBuilder.withProxyPassword( + find(adminFormValues, predicate(proxy_password.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(user.name())).isPresent()) { + prnfbNotificationBuilder.withUser(find(adminFormValues, predicate(user.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(password.name())).isPresent()) { + prnfbNotificationBuilder.withPassword( + find(adminFormValues, predicate(password.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(filter_string.name())).isPresent()) { + prnfbNotificationBuilder.withFilterString( + find(adminFormValues, predicate(filter_string.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(filter_regexp.name())).isPresent()) { + prnfbNotificationBuilder.withFilterRegexp( + find(adminFormValues, predicate(filter_regexp.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(method.name())).isPresent()) { + prnfbNotificationBuilder.withMethod( + find(adminFormValues, predicate(method.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(post_content.name())).isPresent()) { + prnfbNotificationBuilder.withPostContent( + find(adminFormValues, predicate(post_content.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(name.name())).isPresent()) { + prnfbNotificationBuilder.withName(find(adminFormValues, predicate(name.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(injection_url.name())).isPresent()) { + prnfbNotificationBuilder.withInjectionUrl( + find(adminFormValues, predicate(injection_url.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(injection_url_regexp.name())).isPresent()) { + prnfbNotificationBuilder.withInjectionUrlRegexp( + find(adminFormValues, predicate(injection_url_regexp.name())).get(VALUE)); + } + if (tryFind(adminFormValues, predicate(trigger_if_isconflicting.name())).isPresent()) { + prnfbNotificationBuilder.withTriggerIfCanMerge( + find(adminFormValues, predicate(trigger_if_isconflicting.name())).get(VALUE)); + } + for (final Map event : + filter(adminFormValues, predicate(trigger_ignore_state.name()))) { + prnfbNotificationBuilder.withTriggerIgnoreState(PullRequestState.valueOf(event.get(VALUE))); + } + return prnfbNotificationBuilder.build(); } - return prnfbNotificationBuilder.build(); - } - public static PrnfbSettings getPrnfbSettings(PluginSettings pluginSettings) throws ValidationException { - final PrnfbSettingsBuilder prnfbSettingsBuilder = prnfbSettingsBuilder(); - for (final AdminFormValues adminFormValues : getSettingsAsFormValues(pluginSettings)) { - if (isOfType(adminFormValues, TRIGGER_CONFIG_FORM)) { - prnfbSettingsBuilder.withNotification(getPrnfbNotification(adminFormValues)); - } else { - prnfbSettingsBuilder.withButton(getPrnfbButton(adminFormValues)); - } + public static PrnfbSettings getPrnfbSettings(PluginSettings pluginSettings) + throws ValidationException { + final PrnfbSettingsBuilder prnfbSettingsBuilder = prnfbSettingsBuilder(); + for (final AdminFormValues adminFormValues : getSettingsAsFormValues(pluginSettings)) { + if (isOfType(adminFormValues, TRIGGER_CONFIG_FORM)) { + prnfbSettingsBuilder.withNotification(getPrnfbNotification(adminFormValues)); + } else { + prnfbSettingsBuilder.withButton(getPrnfbButton(adminFormValues)); + } - prnfbSettingsBuilder.withUsersAllowed(tryFind(adminFormValues, predicate(user_allowed.name())).isPresent()); - prnfbSettingsBuilder.withAdminsAllowed(tryFind(adminFormValues, predicate(admin_allowed.name())).isPresent()); + prnfbSettingsBuilder.withUsersAllowed( + tryFind(adminFormValues, predicate(user_allowed.name())).isPresent()); + prnfbSettingsBuilder.withAdminsAllowed( + tryFind(adminFormValues, predicate(admin_allowed.name())).isPresent()); - prnfbSettingsBuilder// - .withShouldAcceptAnyCertificate(tryFind(adminFormValues, predicate(accept_any_certificate.name())).isPresent()); - if (tryFind(adminFormValues, predicate(key_store.name())).isPresent()) { - prnfbSettingsBuilder.setKeyStore(tryFind(adminFormValues, predicate(key_store.name())).get().get(VALUE)); - } - if (tryFind(adminFormValues, predicate(key_store_type.name())).isPresent()) { - prnfbSettingsBuilder.setKeyStoreType(tryFind(adminFormValues, predicate(key_store_type.name())).get().get(VALUE)); - } - if (tryFind(adminFormValues, predicate(key_store_password.name())).isPresent()) { - prnfbSettingsBuilder - .setKeyStorePassword(tryFind(adminFormValues, predicate(key_store_password.name())).get().get(VALUE)); - } + prnfbSettingsBuilder // + .withShouldAcceptAnyCertificate( + tryFind(adminFormValues, predicate(accept_any_certificate.name())).isPresent()); + if (tryFind(adminFormValues, predicate(key_store.name())).isPresent()) { + prnfbSettingsBuilder.setKeyStore( + tryFind(adminFormValues, predicate(key_store.name())).get().get(VALUE)); + } + if (tryFind(adminFormValues, predicate(key_store_type.name())).isPresent()) { + prnfbSettingsBuilder.setKeyStoreType( + tryFind(adminFormValues, predicate(key_store_type.name())).get().get(VALUE)); + } + if (tryFind(adminFormValues, predicate(key_store_password.name())).isPresent()) { + prnfbSettingsBuilder.setKeyStorePassword( + tryFind(adminFormValues, predicate(key_store_password.name())).get().get(VALUE)); + } + } + return prnfbSettingsBuilder.build(); } - return prnfbSettingsBuilder.build(); - } - public static List getSettingsAsFormValues(PluginSettings settings) { - final List toReturn = newArrayList(); - try { - /** - * The storage key was accidently changed when migrating to Bitbucket 4. This - * is an attempt to load 1.x settings if they exist. - */ - Optional settingsToUse = fromNullable(settings.get(STORAGE_KEY)); - if (!settingsToUse.isPresent()) { - settingsToUse = fromNullable(settings.get(STORAGE_KEY_PRNFS)); - if (!settingsToUse.isPresent()) { - return toReturn; + public static List getSettingsAsFormValues(PluginSettings settings) { + final List toReturn = newArrayList(); + try { + /** + * The storage key was accidently changed when migrating to Bitbucket 4. This is an attempt to + * load 1.x settings if they exist. + */ + Optional settingsToUse = fromNullable(settings.get(STORAGE_KEY)); + if (!settingsToUse.isPresent()) { + settingsToUse = fromNullable(settings.get(STORAGE_KEY_PRNFS)); + if (!settingsToUse.isPresent()) { + return toReturn; + } + } + @SuppressWarnings("unchecked") + final List settingsList = newArrayList((List) settingsToUse.get()); + for (final String storedJson : settingsList) { + toReturn.add(injectConfigurationName(gson.fromJson(storedJson, AdminFormValues.class))); + } + } catch (final Exception e) { + logger.log(SEVERE, "Unable to deserialize settings", e); } - } - @SuppressWarnings("unchecked") - final List settingsList = newArrayList((List) settingsToUse.get()); - for (final String storedJson : settingsList) { - toReturn.add(injectConfigurationName(gson.fromJson(storedJson, AdminFormValues.class))); - } - } catch (final Exception e) { - logger.log(SEVERE, "Unable to deserialize settings", e); + return toReturn; } - return toReturn; - } - public static void injectFormIdentifierIfNotSet(final AdminFormValues config) { - final Optional> formIdOpt = tryFind(config, predicate(FORM_IDENTIFIER.name())); - if (!formIdOpt.isPresent() || formIdOpt.get().get(VALUE).trim().isEmpty()) { - final String generatedIdentifier = formIdentifierGnerator(); - removeIf(config, predicate(FORM_IDENTIFIER.name())); - config.add(new ImmutableMap.Builder().put(NAME, FORM_IDENTIFIER.name()) - .put(VALUE, generatedIdentifier).build()); + public static void injectFormIdentifierIfNotSet(final AdminFormValues config) { + final Optional> formIdOpt = + tryFind(config, predicate(FORM_IDENTIFIER.name())); + if (!formIdOpt.isPresent() || formIdOpt.get().get(VALUE).trim().isEmpty()) { + final String generatedIdentifier = formIdentifierGnerator(); + removeIf(config, predicate(FORM_IDENTIFIER.name())); + config.add( + new ImmutableMap.Builder() + .put(NAME, FORM_IDENTIFIER.name()) + .put(VALUE, generatedIdentifier) + .build()); + } } - } - @VisibleForTesting - public static void setLogger(Logger loggerParam) { - logger = loggerParam; - } + @VisibleForTesting + public static void setLogger(Logger loggerParam) { + logger = loggerParam; + } - public static void storeSettings(PluginSettings pluginSettings, final AdminFormValues config) - throws ValidationException { - injectFormIdentifierIfNotSet(config); - final Map allNotificationsMap = getNotificationsMap(pluginSettings); - allNotificationsMap.put(find(config, predicate(FORM_IDENTIFIER.name())).get(VALUE), config); - storeNotificationsMap(pluginSettings, allNotificationsMap); - } + public static void storeSettings(PluginSettings pluginSettings, final AdminFormValues config) + throws ValidationException { + injectFormIdentifierIfNotSet(config); + final Map allNotificationsMap = getNotificationsMap(pluginSettings); + allNotificationsMap.put(find(config, predicate(FORM_IDENTIFIER.name())).get(VALUE), config); + storeNotificationsMap(pluginSettings, allNotificationsMap); + } - private static Map getNotificationsMap(PluginSettings pluginSettings) { - final Map allNotificationsMap = newTreeMap(); - for (final AdminFormValues a : getSettingsAsFormValues(pluginSettings)) { - if (tryFind(a, predicate(FORM_IDENTIFIER.name())).isPresent()) { - allNotificationsMap.put(find(a, predicate(FORM_IDENTIFIER.name())).get(VALUE), a); - } + private static Map getNotificationsMap(PluginSettings pluginSettings) { + final Map allNotificationsMap = newTreeMap(); + for (final AdminFormValues a : getSettingsAsFormValues(pluginSettings)) { + if (tryFind(a, predicate(FORM_IDENTIFIER.name())).isPresent()) { + allNotificationsMap.put(find(a, predicate(FORM_IDENTIFIER.name())).get(VALUE), a); + } + } + return allNotificationsMap; } - return allNotificationsMap; - } - /** - * Inject a default name for the trigger. To make the plugin backwards - * compatible. - */ - private static AdminFormValues injectConfigurationName(AdminFormValues adminFormValues) { - final Optional> nameMapOpt = tryFind(adminFormValues, predicate(name.name())); - if (nameMapOpt.isPresent()) { - return adminFormValues; + /** Inject a default name for the trigger. To make the plugin backwards compatible. */ + private static AdminFormValues injectConfigurationName(AdminFormValues adminFormValues) { + final Optional> nameMapOpt = + tryFind(adminFormValues, predicate(name.name())); + if (nameMapOpt.isPresent()) { + return adminFormValues; + } + adminFormValues.add( + ImmutableMap.builder() // + .put(NAME, name.name()) // + .put(VALUE, DEFAULT_NAME) // + .build()); + return adminFormValues; } - adminFormValues.add(ImmutableMap.builder()// - .put(NAME, name.name())// - .put(VALUE, DEFAULT_NAME)// - .build()); - return adminFormValues; - } - private static void storeNotificationsMap(PluginSettings pluginSettings, - Map allNotificationsMap) throws ValidationException { - final List toStore = newArrayList(); - for (final AdminFormValues adminFormValues : allNotificationsMap.values()) { - final Optional> formIdOpt = tryFind(adminFormValues, predicate(FORM_IDENTIFIER.name())); - if (!formIdOpt.isPresent() || formIdOpt.get().get(VALUE).trim().isEmpty()) { - throw new ValidationException(FORM_IDENTIFIER.name(), "Not set!"); - } - toStore.add(new Gson().toJson(adminFormValues)); + private static void storeNotificationsMap( + PluginSettings pluginSettings, Map allNotificationsMap) + throws ValidationException { + final List toStore = newArrayList(); + for (final AdminFormValues adminFormValues : allNotificationsMap.values()) { + final Optional> formIdOpt = + tryFind(adminFormValues, predicate(FORM_IDENTIFIER.name())); + if (!formIdOpt.isPresent() || formIdOpt.get().get(VALUE).trim().isEmpty()) { + throw new ValidationException(FORM_IDENTIFIER.name(), "Not set!"); + } + toStore.add(new Gson().toJson(adminFormValues)); + } + pluginSettings.put(STORAGE_KEY, toStore); } - pluginSettings.put(STORAGE_KEY, toStore); - } } diff --git a/src/main/java/se/bjurr/prnfb/settings/legacy/ValidationException.java b/src/main/java/se/bjurr/prnfb/settings/legacy/ValidationException.java index f69a6214..211f0c0e 100644 --- a/src/main/java/se/bjurr/prnfb/settings/legacy/ValidationException.java +++ b/src/main/java/se/bjurr/prnfb/settings/legacy/ValidationException.java @@ -2,30 +2,30 @@ @Deprecated public class ValidationException extends Exception { - private static final long serialVersionUID = 2203598567281456784L; - private final String error; - private final String field; + private static final long serialVersionUID = 2203598567281456784L; + private final String error; + private final String field; - public ValidationException() { - this.error = null; - this.field = null; - } + public ValidationException() { + this.error = null; + this.field = null; + } - public ValidationException(String field, String error) { - this.error = error; - this.field = field; - } + public ValidationException(String field, String error) { + this.error = error; + this.field = field; + } - public String getError() { - return this.error; - } + public String getError() { + return this.error; + } - public String getField() { - return this.field; - } + public String getField() { + return this.field; + } - @Override - public String getMessage() { - return this.field + "=" + this.error; - } + @Override + public String getMessage() { + return this.field + "=" + this.error; + } } diff --git a/src/main/java/se/bjurr/prnfb/transformer/ButtonTransformer.java b/src/main/java/se/bjurr/prnfb/transformer/ButtonTransformer.java index 8b2fea25..f137f8c8 100644 --- a/src/main/java/se/bjurr/prnfb/transformer/ButtonTransformer.java +++ b/src/main/java/se/bjurr/prnfb/transformer/ButtonTransformer.java @@ -14,52 +14,54 @@ public class ButtonTransformer { - public static ButtonDTO toButtonDto(PrnfbButton from) { - ButtonDTO to = new ButtonDTO(); - to.setName(from.getName()); - to.setUserLevel(from.getUserLevel()); - to.setUuid(from.getUuid()); - to.setProjectKey(from.getProjectKey().orNull()); - to.setRepositorySlug(from.getRepositorySlug().orNull()); - to.setConfirmation(from.getConfirmation()); - to.setButtonForm(from.getButtonForm()); - return to; - } + public static ButtonDTO toButtonDto(PrnfbButton from) { + ButtonDTO to = new ButtonDTO(); + to.setName(from.getName()); + to.setUserLevel(from.getUserLevel()); + to.setUuid(from.getUuid()); + to.setProjectKey(from.getProjectKey().orNull()); + to.setRepositorySlug(from.getRepositorySlug().orNull()); + to.setConfirmation(from.getConfirmation()); + to.setButtonForm(from.getButtonForm()); + return to; + } - public static List toButtonDtoList(Iterable allowedButtons) { - List to = newArrayList(); - for (PrnfbButton from : allowedButtons) { - to.add(toButtonDto(from)); + public static List toButtonDtoList(Iterable allowedButtons) { + List to = newArrayList(); + for (PrnfbButton from : allowedButtons) { + to.add(toButtonDto(from)); + } + return to; } - return to; - } - public static PrnfbButton toPrnfbButton(ButtonDTO buttonDto) { - return new PrnfbButton(// - buttonDto.getUUID(), // - buttonDto.getName(), // - buttonDto.getUserLevel(), // - buttonDto.getConfirmation(), // - buttonDto.getProjectKey().orNull(), // - buttonDto.getRepositorySlug().orNull(), - buttonDto.getButtonForm());// - } + public static PrnfbButton toPrnfbButton(ButtonDTO buttonDto) { + return new PrnfbButton( // + buttonDto.getUUID(), // + buttonDto.getName(), // + buttonDto.getUserLevel(), // + buttonDto.getConfirmation(), // + buttonDto.getProjectKey().orNull(), // + buttonDto.getRepositorySlug().orNull(), + buttonDto.getButtonForm()); // + } - public static ButtonPressDTO toTriggerResultDto(PrnfbButton button, List results) { - List notificationResponses = newArrayList(); - for (NotificationResponse from : results) { - String content = null; - int status = 0; - URI uri = null; - if (from.getHttpResponse() != null) { - content = from.getHttpResponse().getContent(); - status = from.getHttpResponse().getStatus(); - uri = from.getHttpResponse().getUri(); - } - UUID notification = from.getNotification(); - String notificationName = from.getNotificationName(); - notificationResponses.add(new NotificationResponseDTO(uri, content, status, notification, notificationName)); + public static ButtonPressDTO toTriggerResultDto( + PrnfbButton button, List results) { + List notificationResponses = newArrayList(); + for (NotificationResponse from : results) { + String content = null; + int status = 0; + URI uri = null; + if (from.getHttpResponse() != null) { + content = from.getHttpResponse().getContent(); + status = from.getHttpResponse().getStatus(); + uri = from.getHttpResponse().getUri(); + } + UUID notification = from.getNotification(); + String notificationName = from.getNotificationName(); + notificationResponses.add( + new NotificationResponseDTO(uri, content, status, notification, notificationName)); + } + return new ButtonPressDTO(button.getConfirmation(), notificationResponses); } - return new ButtonPressDTO(button.getConfirmation(), notificationResponses); - } } diff --git a/src/main/java/se/bjurr/prnfb/transformer/NotificationTransformer.java b/src/main/java/se/bjurr/prnfb/transformer/NotificationTransformer.java index 5070aea6..ab3d3c4e 100644 --- a/src/main/java/se/bjurr/prnfb/transformer/NotificationTransformer.java +++ b/src/main/java/se/bjurr/prnfb/transformer/NotificationTransformer.java @@ -17,131 +17,131 @@ public class NotificationTransformer { - public static NotificationDTO toNotificationDto(PrnfbNotification from) { - NotificationDTO to = new NotificationDTO(); - to.setProjectKey(from.getProjectKey().orNull()); - to.setRepositorySlug(from.getRepositorySlug().orNull()); - to.setFilterRegexp(from.getFilterRegexp().orNull()); - to.setFilterString(from.getFilterString().orNull()); - to.setInjectionUrl(from.getInjectionUrl().orNull()); - to.setInjectionUrlRegexp(from.getInjectionUrlRegexp().orNull()); - to.setMethod(from.getMethod()); - to.setName(from.getName()); - to.setHeaders(toHeaders(from.getHeaders())); - to.setPassword(from.getPassword().orNull()); - to.setPostContent(from.getPostContent().orNull()); - to.setProxyPassword(from.getProxyPassword().orNull()); - to.setProxyPort(from.getProxyPort()); - to.setProxyServer(from.getProxyServer().orNull()); - to.setProxyUser(from.getProxyUser().orNull()); - to.setTriggerIfCanMerge(from.getTriggerIfCanMerge()); - to.setTriggerIgnoreStateList(toPullRequestStateStrings(from.getTriggerIgnoreStateList())); - to.setTriggers(toStrings(from.getTriggers())); - to.setUrl(from.getUrl()); - to.setUser(from.getUser().orNull()); - to.setUuid(from.getUuid()); - return to; - } - - public static List toNotificationDtoList(List from) { - List to = newArrayList(); - if (from != null) { - for (PrnfbNotification n : from) { - to.add(toNotificationDto(n)); - } + public static NotificationDTO toNotificationDto(PrnfbNotification from) { + NotificationDTO to = new NotificationDTO(); + to.setProjectKey(from.getProjectKey().orNull()); + to.setRepositorySlug(from.getRepositorySlug().orNull()); + to.setFilterRegexp(from.getFilterRegexp().orNull()); + to.setFilterString(from.getFilterString().orNull()); + to.setInjectionUrl(from.getInjectionUrl().orNull()); + to.setInjectionUrlRegexp(from.getInjectionUrlRegexp().orNull()); + to.setMethod(from.getMethod()); + to.setName(from.getName()); + to.setHeaders(toHeaders(from.getHeaders())); + to.setPassword(from.getPassword().orNull()); + to.setPostContent(from.getPostContent().orNull()); + to.setProxyPassword(from.getProxyPassword().orNull()); + to.setProxyPort(from.getProxyPort()); + to.setProxyServer(from.getProxyServer().orNull()); + to.setProxyUser(from.getProxyUser().orNull()); + to.setTriggerIfCanMerge(from.getTriggerIfCanMerge()); + to.setTriggerIgnoreStateList(toPullRequestStateStrings(from.getTriggerIgnoreStateList())); + to.setTriggers(toStrings(from.getTriggers())); + to.setUrl(from.getUrl()); + to.setUser(from.getUser().orNull()); + to.setUuid(from.getUuid()); + return to; } - return to; - } - public static PrnfbNotification toPrnfbNotification(NotificationDTO from) throws ValidationException { - return prnfbNotificationBuilder()// - .withFilterRegexp(from.getFilterRegexp())// - .withFilterString(from.getFilterString())// - .setHeaders(toHeaders(from))// - .withInjectionUrl(from.getInjectionUrl())// - .withInjectionUrlRegexp(from.getInjectionUrlRegexp())// - .withMethod(from.getMethod())// - .withName(from.getName())// - .withPassword(from.getPassword())// - .withPostContent(from.getPostContent())// - .withProxyPassword(from.getProxyPassword())// - .withProxyPort(from.getProxyPort())// - .withProxyServer(from.getProxyServer())// - .withProxyUser(from.getProxyUser())// - .setTriggers(toPrnfbPullRequestActions(from.getTriggers()))// - .withTriggerIfCanMerge(from.getTriggerIfCanMerge())// - .setTriggerIgnoreState(toPullRequestStates(from.getTriggerIgnoreStateList()))// - .withUrl(from.getUrl())// - .withUser(from.getUser())// - .withUuid(from.getUuid())// - .withRepositorySlug(from.getRepositorySlug())// - .withProjectKey(from.getProjectKey())// - .build(); - } + public static List toNotificationDtoList(List from) { + List to = newArrayList(); + if (from != null) { + for (PrnfbNotification n : from) { + to.add(toNotificationDto(n)); + } + } + return to; + } - private static List toHeaders(List headers) { - List to = newArrayList(); - if (headers != null) { - for (PrnfbHeader h : headers) { - HeaderDTO t = new HeaderDTO(); - t.setName(h.getName()); - t.setValue(h.getValue()); - to.add(t); - } + public static PrnfbNotification toPrnfbNotification(NotificationDTO from) + throws ValidationException { + return prnfbNotificationBuilder() // + .withFilterRegexp(from.getFilterRegexp()) // + .withFilterString(from.getFilterString()) // + .setHeaders(toHeaders(from)) // + .withInjectionUrl(from.getInjectionUrl()) // + .withInjectionUrlRegexp(from.getInjectionUrlRegexp()) // + .withMethod(from.getMethod()) // + .withName(from.getName()) // + .withPassword(from.getPassword()) // + .withPostContent(from.getPostContent()) // + .withProxyPassword(from.getProxyPassword()) // + .withProxyPort(from.getProxyPort()) // + .withProxyServer(from.getProxyServer()) // + .withProxyUser(from.getProxyUser()) // + .setTriggers(toPrnfbPullRequestActions(from.getTriggers())) // + .withTriggerIfCanMerge(from.getTriggerIfCanMerge()) // + .setTriggerIgnoreState(toPullRequestStates(from.getTriggerIgnoreStateList())) // + .withUrl(from.getUrl()) // + .withUser(from.getUser()) // + .withUuid(from.getUuid()) // + .withRepositorySlug(from.getRepositorySlug()) // + .withProjectKey(from.getProjectKey()) // + .build(); } - return to; - } - private static List toHeaders(NotificationDTO from) { - List to = newArrayList(); - if (from.getHeaders() != null) { - for (HeaderDTO headerDto : from.getHeaders()) { - if (!isNullOrEmpty(headerDto.getName()) && !isNullOrEmpty(headerDto.getValue())) { - to.add(new PrnfbHeader(headerDto.getName(), headerDto.getValue())); + private static List toHeaders(List headers) { + List to = newArrayList(); + if (headers != null) { + for (PrnfbHeader h : headers) { + HeaderDTO t = new HeaderDTO(); + t.setName(h.getName()); + t.setValue(h.getValue()); + to.add(t); + } } - } + return to; } - return to; - } - private static List toPrnfbPullRequestActions(List strings) { - List to = newArrayList(); - if (strings != null) { - for (String from : strings) { - to.add(PrnfbPullRequestAction.valueOf(from)); - } + private static List toHeaders(NotificationDTO from) { + List to = newArrayList(); + if (from.getHeaders() != null) { + for (HeaderDTO headerDto : from.getHeaders()) { + if (!isNullOrEmpty(headerDto.getName()) && !isNullOrEmpty(headerDto.getValue())) { + to.add(new PrnfbHeader(headerDto.getName(), headerDto.getValue())); + } + } + } + return to; } - return to; - } - private static List toPullRequestStates(List strings) { - List to = newArrayList(); - if (strings != null) { - for (String from : strings) { - to.add(PullRequestState.valueOf(from)); - } + private static List toPrnfbPullRequestActions(List strings) { + List to = newArrayList(); + if (strings != null) { + for (String from : strings) { + to.add(PrnfbPullRequestAction.valueOf(from)); + } + } + return to; } - return to; - } - private static List toPullRequestStateStrings(List list) { - List to = newArrayList(); - if (list != null) { - for (Enum e : list) { - to.add(e.name()); - } + private static List toPullRequestStates(List strings) { + List to = newArrayList(); + if (strings != null) { + for (String from : strings) { + to.add(PullRequestState.valueOf(from)); + } + } + return to; } - return to; - } - private static List toStrings(List list) { - List to = newArrayList(); - if (list != null) { - for (Enum e : list) { - to.add(e.name()); - } + private static List toPullRequestStateStrings(List list) { + List to = newArrayList(); + if (list != null) { + for (Enum e : list) { + to.add(e.name()); + } + } + return to; } - return to; - } + private static List toStrings(List list) { + List to = newArrayList(); + if (list != null) { + for (Enum e : list) { + to.add(e.name()); + } + } + return to; + } } diff --git a/src/main/java/se/bjurr/prnfb/transformer/SettingsTransformer.java b/src/main/java/se/bjurr/prnfb/transformer/SettingsTransformer.java index 172cd4b5..54423d61 100644 --- a/src/main/java/se/bjurr/prnfb/transformer/SettingsTransformer.java +++ b/src/main/java/se/bjurr/prnfb/transformer/SettingsTransformer.java @@ -6,23 +6,23 @@ public class SettingsTransformer { - public static SettingsDataDTO toDto(PrnfbSettingsData settingsData) { - SettingsDataDTO dto = new SettingsDataDTO(); - dto.setAdminRestriction(settingsData.getAdminRestriction()); - dto.setKeyStore(settingsData.getKeyStore().orNull()); - dto.setKeyStorePassword(settingsData.getKeyStorePassword().orNull()); - dto.setKeyStoreType(settingsData.getKeyStoreType()); - dto.setShouldAcceptAnyCertificate(settingsData.isShouldAcceptAnyCertificate()); - return dto; - } + public static SettingsDataDTO toDto(PrnfbSettingsData settingsData) { + SettingsDataDTO dto = new SettingsDataDTO(); + dto.setAdminRestriction(settingsData.getAdminRestriction()); + dto.setKeyStore(settingsData.getKeyStore().orNull()); + dto.setKeyStorePassword(settingsData.getKeyStorePassword().orNull()); + dto.setKeyStoreType(settingsData.getKeyStoreType()); + dto.setShouldAcceptAnyCertificate(settingsData.isShouldAcceptAnyCertificate()); + return dto; + } - public static PrnfbSettingsData toPrnfbSettingsData(SettingsDataDTO settingsDataDto) { - return prnfbSettingsDataBuilder()// - .setAdminRestriction(settingsDataDto.getAdminRestriction())// - .setKeyStore(settingsDataDto.getKeyStore())// - .setKeyStorePassword(settingsDataDto.getKeyStorePassword())// - .setKeyStoreType(settingsDataDto.getKeyStoreType())// - .setShouldAcceptAnyCertificate(settingsDataDto.isShouldAcceptAnyCertificate())// - .build(); - } + public static PrnfbSettingsData toPrnfbSettingsData(SettingsDataDTO settingsDataDto) { + return prnfbSettingsDataBuilder() // + .setAdminRestriction(settingsDataDto.getAdminRestriction()) // + .setKeyStore(settingsDataDto.getKeyStore()) // + .setKeyStorePassword(settingsDataDto.getKeyStorePassword()) // + .setKeyStoreType(settingsDataDto.getKeyStoreType()) // + .setShouldAcceptAnyCertificate(settingsDataDto.isShouldAcceptAnyCertificate()) // + .build(); + } } diff --git a/src/main/resources/admin.vm b/src/main/resources/admin.vm index 4c6ea397..def5bf12 100644 --- a/src/main/resources/admin.vm +++ b/src/main/resources/admin.vm @@ -244,11 +244,11 @@
Whether to show a confirmation dialog.
- +
-
Put a JSON representation of your desired form here.
+
Put a JSON representation of your desired form here. This is documented here.
@@ -533,4 +533,4 @@ - + \ No newline at end of file diff --git a/src/main/resources/atlassian-plugin.xml b/src/main/resources/atlassian-plugin.xml index 96408b5c..355c7341 100644 --- a/src/main/resources/atlassian-plugin.xml +++ b/src/main/resources/atlassian-plugin.xml @@ -61,4 +61,4 @@ com.atlassian.bitbucket.bitbucket-web-plugin:global bitbucket.page.pullRequest.view - + \ No newline at end of file diff --git a/src/main/resources/pr-triggerbutton.js b/src/main/resources/pr-triggerbutton.js index d13bf1d7..b4641a11 100644 --- a/src/main/resources/pr-triggerbutton.js +++ b/src/main/resources/pr-triggerbutton.js @@ -13,136 +13,146 @@ define('plugin/prnfb/pr-triggerbutton', [ var buttonTemplate = function(name) { return $('
  • '); }; - - var dialogTemplate = function(name, content) { - var escapedName = _.escape(name); - return '' - } + + var dialogTemplate = function(name, content) { + var escapedName = _.escape(name); + return ''; + }; var inputTemplate = function(name, item) { var escapedName = _.escape(name); var escapedLabel = _.escape(item.label); var escapedValue = _.escape(item.defaultValue); var escapedDescription = _.escape(item.defaultDescription); - return $(''+ -'
    ' + - ''+ - ''+ - '
    '+escapedDescription+'
    '+ -'
    ') + return $('' + + '
    ' + // + '' + // + '' + // + '
    ' + escapedDescription + '
    ' + // + '
    '); }; - + var textareaTemplate = function(name, item) { var escapedName = _.escape(name); var escapedLabel = _.escape(item.label); var escapedValue = _.escape(item.defaultValue); var escapedDescription = _.escape(item.defaultDescription); - return $(''+ -'
    ' + - ''+ - ''+ - '
    '+escapedDescription+'
    '+ -'
    ') + return $('' + + '
    ' + // + '' + // + '' + // + '
    ' + escapedDescription + '
    ' + // + '
    '); }; var checkboxTemplate = function(name, item) { - var checkboxItemTemplate = function(nestedItem, num) { - var isChecked = nestedItem.defaultValue; - var outerName = _.escape(name); - var itemName = _.escape(nestedItem.name); - var itemLabel = _.escape(nestedItem.label); - return $('
    \ -
    '); - } - - var escapedLabel = _.escape(item.label); - var escapedDescription = _.escape(item.description); - var checkboxItems = [$(''+escapedLabel+'')]; - for(var i = 0; i < item.options.length; i++) { - checkboxItems.push(checkboxItemTemplate(item.options[i], i)); - } - checkboxItems.push( $('
    '+escapedDescription+'
    ')); - return $("
    ").append(checkboxItems); + var checkboxItemTemplate = function(nestedItem, num) { + var isChecked = nestedItem.defaultValue; + var outerName = _.escape(name); + var itemName = _.escape(nestedItem.name); + var itemLabel = _.escape(nestedItem.label); + return $('
    ' + // + '' + // + '
    '); + }; + + var escapedLabel = _.escape(item.label); + var escapedDescription = _.escape(item.description); + var checkboxItems = [$('' + escapedLabel + '')]; + for (var i = 0; i < item.options.length; i++) { + checkboxItems.push(checkboxItemTemplate(item.options[i], i)); + } + checkboxItems.push($('
    ' + escapedDescription + '
    ')); + return $("
    ").append(checkboxItems); }; - + var radioTemplate = function(name, item) { - var radioItemTemplate = function(nestedItem, num) { - var isChecked = nestedItem.name === item.defaultValue; - var outerName = _.escape(name); - var itemName = _.escape(nestedItem.name); - var itemLabel = _.escape(nestedItem.label); - return $('
    \ -
    '); - } - - var escapedLabel = _.escape(item.label); - var escapedDescription = _.escape(item.description); - var radioItems = [$(''+escapedLabel+'')]; - for(var i = 0; i < item.options.length; i++) { - radioItems.push(radioItemTemplate(item.options[i], i)); - } - radioItems.push( $('
    '+escapedDescription+'
    ')); - return $("
    ").append(radioItems); + var radioItemTemplate = function(nestedItem, num) { + var isChecked = nestedItem.name === item.defaultValue; + var outerName = _.escape(name); + var itemName = _.escape(nestedItem.name); + var itemLabel = _.escape(nestedItem.label); + return $('
    ' + // + '' + // + '
    '); + }; + + var escapedLabel = _.escape(item.label); + var escapedDescription = _.escape(item.description); + var radioItems = [$('' + escapedLabel + '')]; + for (var i = 0; i < item.options.length; i++) { + radioItems.push(radioItemTemplate(item.options[i], i)); + } + radioItems.push($('
    ' + escapedDescription + '
    ')); + return $("
    ").append(radioItems); }; - + var formTemplate = function(formDescription) { - if (!formDescription || formDescription.length === 0) { - return null; - } - - var parsedForm = JSON.parse(formDescription); - - var formItems = []; - for(var i = 0; i < parsedForm.length; i++) { - var item = parsedForm[i]; - switch(item.type) { - case "input": { - formItems.push(inputTemplate(item.name, item)); - break; - } - case "textarea": { - formItems.push(textareaTemplate(item.name, item)); - break; - } - case "checkbox": { - formItems.push(checkboxTemplate(item.name, item)); - break; - } - case "radio": { - formItems.push(radioTemplate(item.name, item)); - break; - } - } + if (!formDescription || formDescription.length === 0) { + return null; + } + + var parsedForm = JSON.parse(formDescription); + + var formItems = []; + for (var i = 0; i < parsedForm.length; i++) { + var item = parsedForm[i]; + switch (item.type) { + case "input": + { + formItems.push(inputTemplate(item.name, item)); + break; + } + case "textarea": + { + formItems.push(textareaTemplate(item.name, item)); + break; + } + case "checkbox": + { + formItems.push(checkboxTemplate(item.name, item)); + break; + } + case "radio": + { + formItems.push(radioTemplate(item.name, item)); + break; + } } - var form = $("
    ") - form.append(formItems); - - return form; + } + var form = $("
    "); + form.append(formItems); + + return form; }; var presentResult = function(response) { @@ -196,24 +206,26 @@ define('plugin/prnfb/pr-triggerbutton', [ var $buttonDropdownItem = buttonTemplate(item.name.replace(/