diff --git a/src/main/java/jenkins/plugins/logstash/LogstashBuildWrapper.java b/src/main/java/jenkins/plugins/logstash/LogstashBuildWrapper.java index 81ec9f41..e3e6a7ea 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashBuildWrapper.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashBuildWrapper.java @@ -45,31 +45,25 @@ * @author K Jonathan Harker */ @Deprecated -public class LogstashBuildWrapper extends BuildWrapper -{ +public class LogstashBuildWrapper extends BuildWrapper { /** * Create a new {@link LogstashBuildWrapper}. */ @DataBoundConstructor - public LogstashBuildWrapper() - {} + public LogstashBuildWrapper() {} /** * {@inheritDoc} */ @Override public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) - throws IOException, InterruptedException - { - return new Environment() - { - }; + throws IOException, InterruptedException { + return new Environment() {}; } @Override - public DescriptorImpl getDescriptor() - { + public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } @@ -77,11 +71,9 @@ public DescriptorImpl getDescriptor() * Registers {@link LogstashBuildWrapper} as a {@link BuildWrapper}. */ @Extension - public static class DescriptorImpl extends BuildWrapperDescriptor - { + public static class DescriptorImpl extends BuildWrapperDescriptor { - public DescriptorImpl() - { + public DescriptorImpl() { super(LogstashBuildWrapper.class); load(); } @@ -90,8 +82,7 @@ public DescriptorImpl() * {@inheritDoc} */ @Override - public String getDisplayName() - { + public String getDisplayName() { return Messages.DisplayName(); } @@ -99,8 +90,7 @@ public String getDisplayName() * {@inheritDoc} */ @Override - public boolean isApplicable(AbstractProject item) - { + public boolean isApplicable(AbstractProject item) { return false; } } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashConfiguration.java b/src/main/java/jenkins/plugins/logstash/LogstashConfiguration.java index 462d9177..bc098bc8 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashConfiguration.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashConfiguration.java @@ -31,8 +31,8 @@ import net.sf.json.JSONObject; @Extension -public class LogstashConfiguration extends GlobalConfiguration -{ +public class LogstashConfiguration extends GlobalConfiguration { + private static final Logger LOGGER = Logger.getLogger(LogstashConfiguration.class.getName()); private static final FastDateFormat MILLIS_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); private static final FastDateFormat LEGACY_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZ"); @@ -47,61 +47,46 @@ public class LogstashConfiguration extends GlobalConfiguration // a flag indicating if we're currently in the configure method. private transient boolean configuring = false; - public LogstashConfiguration() - { + public LogstashConfiguration() { load(); - if (enabled == null) - { - if (logstashIndexer == null) - { + if (enabled == null) { + if (logstashIndexer == null) { enabled = false; - } - else - { + } else { enabled = true; } } activeIndexer = logstashIndexer; } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled == null ? false: enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public boolean isEnableGlobally() - { + public boolean isEnableGlobally() { return enableGlobally; } - public void setEnableGlobally(boolean enableGlobally) - { + public void setEnableGlobally(boolean enableGlobally) { this.enableGlobally = enableGlobally; } - public boolean isMilliSecondTimestamps() - { + public boolean isMilliSecondTimestamps() { return milliSecondTimestamps; } - public void setMilliSecondTimestamps(boolean milliSecondTimestamps) - { + public void setMilliSecondTimestamps(boolean milliSecondTimestamps) { this.milliSecondTimestamps = milliSecondTimestamps; } - public FastDateFormat getDateFormatter() - { - if (milliSecondTimestamps) - { + public FastDateFormat getDateFormatter() { + if (milliSecondTimestamps) { return MILLIS_FORMATTER; - } - else - { + } else { return LEGACY_FORMATTER; } } @@ -111,16 +96,13 @@ public FastDateFormat getDateFormatter() * * @return configuration instance */ - public LogstashIndexer getLogstashIndexer() - { + public LogstashIndexer getLogstashIndexer() { return logstashIndexer; } - public void setLogstashIndexer(LogstashIndexer logstashIndexer) - { + public void setLogstashIndexer(LogstashIndexer logstashIndexer) { this.logstashIndexer = logstashIndexer; - if (!configuring && !Objects.equals(logstashIndexer, activeIndexer)) - { + if (!configuring && !Objects.equals(logstashIndexer, activeIndexer)) { activeIndexer = logstashIndexer; } } @@ -130,33 +112,25 @@ public void setLogstashIndexer(LogstashIndexer logstashIndexer) * @return dao instance */ @CheckForNull - public LogstashIndexerDao getIndexerInstance() - { - if (activeIndexer != null) - { + public LogstashIndexerDao getIndexerInstance() { + if (activeIndexer != null) { return activeIndexer.getInstance(); } return null; } - - public List getIndexerTypes() - { + public List getIndexerTypes() { return LogstashIndexer.all(); } @SuppressWarnings("deprecation") @Initializer(after = InitMilestone.JOB_LOADED) - public void migrateData() - { - if (!dataMigrated) - { + public void migrateData() { + if (!dataMigrated) { Descriptor descriptor = LogstashInstallation.getLogstashDescriptor(); - if (descriptor.getType() != null) - { + if (descriptor.getType() != null) { IndexerType type = descriptor.getType(); - switch (type) - { + switch (type) { case REDIS: LOGGER.log(Level.INFO, "Migrating logstash configuration for Redis"); Redis redis = new Redis(); @@ -170,8 +144,7 @@ public void migrateData() case ELASTICSEARCH: LOGGER.log(Level.INFO, "Migrating logstash configuration for Elastic Search"); URI uri; - try - { + try { uri = (new URIBuilder(descriptor.getHost())) .setPort(descriptor.getPort()) .setPath("/" + descriptor.getKey()).build(); @@ -181,9 +154,7 @@ public void migrateData() es.setPassword(Secret.fromString(descriptor.getPassword())); logstashIndexer = es; enabled = true; - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { enabled = false; LOGGER.log(Level.INFO, "Migrating logstash configuration for Elastic Search failed: " + e.toString()); } @@ -205,8 +176,7 @@ public void migrateData() syslog.setHost(descriptor.getHost()); syslog.setPort(descriptor.getPort()); syslog.setSyslogProtocol(descriptor.getSyslogProtocol()); - switch (descriptor.getSyslogFormat()) - { + switch (descriptor.getSyslogFormat()) { case RFC3164: syslog.setMessageFormat(MessageFormat.RFC_3164); break; @@ -234,15 +204,12 @@ public void migrateData() } @Override - public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws FormException - { - + public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws FormException { // When not enabling the plugin we just save the enabled state // without binding the JSON and then return. This avoids problems with missing configuration // like URLs which can't be parsed when empty, which would lead to errors in the UI. Boolean e = json.getBoolean("enabled"); - if (!e) - { + if (!e) { enabled = false; save(); return true; @@ -254,8 +221,7 @@ public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws // logstashIndexer is holder for the dao instance. // To avoid that we get a new dao instance in case there was no change in configuration // we compare it to the currently active configuration. - try - { + try { staplerRequest.bindJSON(this, json); try { @@ -270,23 +236,18 @@ public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws throw new IllegalArgumentException(ex); } - if (!Objects.equals(logstashIndexer, activeIndexer)) - { + if (!Objects.equals(logstashIndexer, activeIndexer)) { activeIndexer = logstashIndexer; } save(); return true; - } - finally - { + } finally { configuring = false; } } - public static LogstashConfiguration getInstance() - { + public static LogstashConfiguration getInstance() { return GlobalConfiguration.all().get(LogstashConfiguration.class); } - } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashConsoleLogFilter.java b/src/main/java/jenkins/plugins/logstash/LogstashConsoleLogFilter.java index 9eb7ec0a..bc0c7d58 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashConsoleLogFilter.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashConsoleLogFilter.java @@ -13,62 +13,50 @@ import hudson.model.Run; @Extension(ordinal = 1000) -public class LogstashConsoleLogFilter extends ConsoleLogFilter implements Serializable -{ +public class LogstashConsoleLogFilter extends ConsoleLogFilter implements Serializable { private static final Logger LOGGER = Logger.getLogger(LogstashConsoleLogFilter.class.getName()); - public LogstashConsoleLogFilter() {} - private static final long serialVersionUID = 1L; + public LogstashConsoleLogFilter() {} + @Override - public OutputStream decorateLogger(Run build, OutputStream logger) throws IOException, InterruptedException - { + public OutputStream decorateLogger(Run build, OutputStream logger) throws IOException, InterruptedException { LogstashConfiguration configuration = LogstashConfiguration.getInstance(); - if (!configuration.isEnabled()) - { + if (!configuration.isEnabled()) { LOGGER.log(Level.FINE, "Logstash is disabled. Logs will not be forwarded."); return logger; } - if (build != null && build instanceof AbstractBuild) - { - if (isLogstashEnabled(build)) - { + if (build != null && build instanceof AbstractBuild) { + if (isLogstashEnabled(build)) { LogstashWriter logstash = getLogStashWriter(build, logger); return new LogstashOutputStream(logger, logstash); - } - else - { + } else { return logger; } } + return logger; } - LogstashWriter getLogStashWriter(Run build, OutputStream errorStream) - { + LogstashWriter getLogStashWriter(Run build, OutputStream errorStream) { return new LogstashWriter(build, errorStream, null, build.getCharset()); } - private boolean isLogstashEnabled(Run build) - { + private boolean isLogstashEnabled(Run build) { LogstashConfiguration configuration = LogstashConfiguration.getInstance(); - if (configuration.isEnableGlobally()) - { + if (configuration.isEnableGlobally()) { return true; } - if (build.getParent() instanceof AbstractProject) - { + if (build.getParent() instanceof AbstractProject) { AbstractProject project = (AbstractProject)build.getParent(); - if (project.getProperty(LogstashJobProperty.class) != null) - { + if (project.getProperty(LogstashJobProperty.class) != null) { return true; } } return false; } - } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashInstallation.java b/src/main/java/jenkins/plugins/logstash/LogstashInstallation.java index ae5922df..a73cab57 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashInstallation.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashInstallation.java @@ -45,6 +45,7 @@ * @since 1.0.0 */ public class LogstashInstallation extends ToolInstallation { + private static final long serialVersionUID = -5730780734005293851L; @DataBoundConstructor @@ -72,59 +73,41 @@ public Descriptor() { load(); } - @Override public String getDisplayName() { return Messages.DisplayName(); } - - public IndexerType getType() - { + public IndexerType getType() { return type; } - - public SyslogFormat getSyslogFormat() - { + public SyslogFormat getSyslogFormat() { return syslogFormat; } - - public SyslogProtocol getSyslogProtocol() - { + public SyslogProtocol getSyslogProtocol() { return syslogProtocol; } - - public String getHost() - { + public String getHost() { return host; } - - public Integer getPort() - { + public Integer getPort() { return port; } - - public String getUsername() - { + public String getUsername() { return username; } - - public String getPassword() - { + public String getPassword() { return password; } - - public String getKey() - { + public String getKey() { return key; } - } } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashItemListener.java b/src/main/java/jenkins/plugins/logstash/LogstashItemListener.java index 1ef9069d..8801f6fd 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashItemListener.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashItemListener.java @@ -16,54 +16,41 @@ import jenkins.model.Jenkins; @Extension -public class LogstashItemListener extends ItemListener -{ +public class LogstashItemListener extends ItemListener { private static final Logger LOGGER = Logger.getLogger(LogstashItemListener.class.getName()); @Override - public void onCreated(Item item) - { - if (item instanceof BuildableItemWithBuildWrappers) - { + public void onCreated(Item item) { + if (item instanceof BuildableItemWithBuildWrappers) { convertBuildWrapperToJobProperty((BuildableItemWithBuildWrappers)item); } } @Override - public void onLoaded() - { - for (BuildableItemWithBuildWrappers item : Jenkins.getInstance().getAllItems(BuildableItemWithBuildWrappers.class)) - { + public void onLoaded() { + for (BuildableItemWithBuildWrappers item : Jenkins.getInstance().getAllItems(BuildableItemWithBuildWrappers.class)) { convertBuildWrapperToJobProperty(item); } } - static void convertBuildWrapperToJobProperty(BuildableItemWithBuildWrappers item) - { + static void convertBuildWrapperToJobProperty(BuildableItemWithBuildWrappers item) { DescribableList> wrappers = item.getBuildWrappersList(); @SuppressWarnings("deprecation") LogstashBuildWrapper logstashBuildWrapper = wrappers.get(LogstashBuildWrapper.class); - if (logstashBuildWrapper != null && item instanceof AbstractProject) - { + if (logstashBuildWrapper != null && item instanceof AbstractProject) { AbstractProject project = (AbstractProject)item; BulkChange bc = new BulkChange(project); - try - { + try { project.addProperty(new LogstashJobProperty()); wrappers.remove(logstashBuildWrapper); bc.commit(); - } - catch (IOException e) - { + } catch (IOException e) { LOGGER.log(Level.SEVERE, "Failed to convert LogstashBuildWrapper to LogstashJobProperty for project " + project.getFullName(), e); - } - finally - { + } finally { bc.abort(); } } } - } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashJobProperty.java b/src/main/java/jenkins/plugins/logstash/LogstashJobProperty.java index e595d928..cc46b5d1 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashJobProperty.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashJobProperty.java @@ -12,37 +12,30 @@ /** * This JobProperty is a marker to decide if logs should be sent to an indexer. - * */ -public class LogstashJobProperty extends JobProperty> -{ +public class LogstashJobProperty extends JobProperty> { @DataBoundConstructor - public LogstashJobProperty() - {} + public LogstashJobProperty() {} @Extension - public static class DescriptorImpl extends JobPropertyDescriptor - { + public static class DescriptorImpl extends JobPropertyDescriptor { + @Override - public JobProperty newInstance(StaplerRequest req, JSONObject formData) throws FormException - { - if (formData.containsKey("enable")) - { + public JobProperty newInstance(StaplerRequest req, JSONObject formData) throws FormException { + if (formData.containsKey("enable")) { return new LogstashJobProperty(); } return null; } @Override - public String getDisplayName() - { + public String getDisplayName() { return Messages.DisplayName(); } @Override - public boolean isApplicable(Class jobType) - { + public boolean isApplicable(Class jobType) { return AbstractProject.class.isAssignableFrom(jobType); } } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashNotifier.java b/src/main/java/jenkins/plugins/logstash/LogstashNotifier.java index 1e43e525..4e6f25f1 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashNotifier.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashNotifier.java @@ -68,13 +68,11 @@ public LogstashNotifier(int maxLines, boolean failBuild) { this.failBuild = failBuild; } - public int getMaxLines() - { + public int getMaxLines() { return maxLines; } - public boolean isFailBuild() - { + public boolean isFailBuild() { return failBuild; } @@ -93,8 +91,7 @@ public void perform(Run run, FilePath workspace, Launcher launcher, private boolean perform(Run run, TaskListener listener) { LogstashConfiguration configuration = LogstashConfiguration.getInstance(); - if (!configuration.isEnabled()) - { + if (!configuration.isEnabled()) { LOGGER.log(Level.FINE, "Logstash is disabled. Logs will not be forwarded."); return true; } @@ -146,6 +143,5 @@ public FormValidation doCheckMaxLines(@QueryParameter("value") String value) { return FormValidation.ok(); } - } } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashOutputStream.java b/src/main/java/jenkins/plugins/logstash/LogstashOutputStream.java index f6ae5de2..270f03e7 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashOutputStream.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashOutputStream.java @@ -38,6 +38,7 @@ * @author Rusty Gerard */ public class LogstashOutputStream extends LineTransformationOutputStream { + private final OutputStream delegate; private final LogstashWriter logstash; @@ -48,8 +49,7 @@ public LogstashOutputStream(OutputStream delegate, LogstashWriter logstash) { } // for testing purposes - LogstashWriter getLogstashWriter() - { + LogstashWriter getLogstashWriter() { return logstash; } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashSaveableListener.java b/src/main/java/jenkins/plugins/logstash/LogstashSaveableListener.java index 010562c5..0351199a 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashSaveableListener.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashSaveableListener.java @@ -7,15 +7,12 @@ import hudson.model.listeners.SaveableListener; @Extension -public class LogstashSaveableListener extends SaveableListener -{ +public class LogstashSaveableListener extends SaveableListener { @Override - public void onChange(Saveable o, XmlFile file) - { - if (o instanceof BuildableItemWithBuildWrappers) - { - LogstashItemListener.convertBuildWrapperToJobProperty((BuildableItemWithBuildWrappers)o); + public void onChange(Saveable o, XmlFile file) { + if (o instanceof BuildableItemWithBuildWrappers) { + LogstashItemListener.convertBuildWrapperToJobProperty((BuildableItemWithBuildWrappers) o); } } diff --git a/src/main/java/jenkins/plugins/logstash/LogstashWriter.java b/src/main/java/jenkins/plugins/logstash/LogstashWriter.java index aad77e3a..195b76a2 100644 --- a/src/main/java/jenkins/plugins/logstash/LogstashWriter.java +++ b/src/main/java/jenkins/plugins/logstash/LogstashWriter.java @@ -80,6 +80,7 @@ public LogstashWriter(Run run, OutputStream error, TaskListener listener, this.listener = listener; this.charset = charset.toString(); this.dao = this.getDaoOrNull(); + if (this.dao == null) { this.jenkinsUrl = ""; this.buildData = null; @@ -94,14 +95,12 @@ public LogstashWriter(Run run, OutputStream error, TaskListener listener, * * @return the charset */ - public String getCharset() - { + public String getCharset() { return charset; } // for testing only - LogstashIndexerDao getDao() - { + LogstashIndexerDao getDao() { return dao; } @@ -199,8 +198,7 @@ private void write(List lines) { private LogstashIndexerDao getDaoOrNull() { try { LogstashIndexerDao dao = getIndexerDao(); - if (dao == null) - { + if (dao == null) { logErrorMessage("[logstash-plugin]: Unable to instantiate LogstashIndexerDao with current configuration.\n"); } return dao; @@ -228,5 +226,4 @@ private void logErrorMessage(String msg) { ex.printStackTrace(); } } - } diff --git a/src/main/java/jenkins/plugins/logstash/PluginImpl.java b/src/main/java/jenkins/plugins/logstash/PluginImpl.java index 932a1b2b..6873e10d 100644 --- a/src/main/java/jenkins/plugins/logstash/PluginImpl.java +++ b/src/main/java/jenkins/plugins/logstash/PluginImpl.java @@ -35,6 +35,7 @@ import org.kohsuke.stapler.Stapler; public class PluginImpl extends Plugin { + private final static Logger LOG = Logger.getLogger(PluginImpl.class.getName()); /* @@ -49,8 +50,7 @@ public void start() throws Exception { Stapler.CONVERT_UTILS.register(new URIConverter(), URI.class); } - public DescriptorExtensionList, Descriptor>> getAllIndexers() - { + public DescriptorExtensionList, Descriptor>> getAllIndexers() { return LogstashIndexer.all(); } } diff --git a/src/main/java/jenkins/plugins/logstash/configuration/ElasticSearch.java b/src/main/java/jenkins/plugins/logstash/configuration/ElasticSearch.java index 7e739115..6d8c62d7 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/ElasticSearch.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/ElasticSearch.java @@ -43,8 +43,8 @@ import jenkins.plugins.logstash.Messages; import jenkins.plugins.logstash.persistence.ElasticSearchDao; -public class ElasticSearch extends LogstashIndexer -{ +public class ElasticSearch extends LogstashIndexer { + private static final Logger LOGGER = Logger.getLogger(ElasticSearch.class.getName()); private String username; @@ -54,17 +54,14 @@ public class ElasticSearch extends LogstashIndexer private String customServerCertificateId; @DataBoundConstructor - public ElasticSearch() - { - } + public ElasticSearch() {} - public URI getUri() - { + public URI getUri() { return uri; } @Override - public void validate() throws MimeTypeParseException { + public void validate() throws MimeTypeParseException { new MimeType(this.mimeType); } @@ -72,35 +69,29 @@ public void validate() throws MimeTypeParseException { * We use URL for the setter as stapler can autoconvert a string to a URL but not to a URI */ @DataBoundSetter - public void setUri(URL url) throws URISyntaxException - { + public void setUri(URL url) throws URISyntaxException { this.uri = url.toURI(); } - public void setUri(URI uri) - { + public void setUri(URI uri) { this.uri = uri; } - public String getUsername() - { + public String getUsername() { return username; } @DataBoundSetter - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } - public Secret getPassword() - { + public Secret getPassword() { return password; } @DataBoundSetter - public void setPassword(Secret password) - { + public void setPassword(Secret password) { this.password = password; } @@ -114,68 +105,54 @@ public String getMimeType() { } @DataBoundSetter - public void setCustomServerCertificateId(String customServerCertificateId) - { + public void setCustomServerCertificateId(String customServerCertificateId) { this.customServerCertificateId = customServerCertificateId; } - public String getCustomServerCertificateId() - { + public String getCustomServerCertificateId() { return customServerCertificateId; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; + ElasticSearch other = (ElasticSearch) obj; - if (!Secret.toString(password).equals(Secret.toString(other.getPassword()))) - { + + if (!Secret.toString(password).equals(Secret.toString(other.getPassword()))) { return false; } - if (uri == null) - { + if (uri == null) { if (other.uri != null) return false; - } - else if (!uri.equals(other.uri)) - { + } else if (!uri.equals(other.uri)) { return false; } - if (username == null) - { + if (username == null) { if (other.username != null) return false; - } - else if (!username.equals(other.username)) - { + } else if (!username.equals(other.username)) { return false; - } - else if (!mimeType.equals(other.mimeType)) - { + } else if (!mimeType.equals(other.mimeType)) { return false; } - - if (this.customServerCertificateId == null) - { + if (this.customServerCertificateId == null) { if (other.customServerCertificateId != null) return false; - } - else if (!this.customServerCertificateId.equals(other.customServerCertificateId)) - { + } else if (!this.customServerCertificateId.equals(other.customServerCertificateId)) { return false; } + return true; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((uri == null) ? 0 : uri.hashCode()); @@ -185,8 +162,7 @@ public int hashCode() } @Override - public ElasticSearchDao createIndexerInstance() - { + public ElasticSearchDao createIndexerInstance() { ElasticSearchDao esDao = new ElasticSearchDao(getUri(), username, Secret.toString(password)); esDao.setMimeType(getMimeType()); @@ -205,8 +181,7 @@ public ElasticSearchDao createIndexerInstance() return esDao; } - private StandardCertificateCredentials getCredentials(String credentials) - { + private StandardCertificateCredentials getCredentials(String credentials) { return (StandardCertificateCredentials) CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials(StandardCertificateCredentials.class, Jenkins.get(), ACL.SYSTEM, Collections.emptyList()), @@ -216,24 +191,20 @@ private StandardCertificateCredentials getCredentials(String credentials) @Extension @Symbol("elasticSearch") - public static class ElasticSearchDescriptor extends LogstashIndexerDescriptor - { + public static class ElasticSearchDescriptor extends LogstashIndexerDescriptor { @Override - public String getDisplayName() - { + public String getDisplayName() { return "Elastic Search"; } @Override - public int getDefaultPort() - { + public int getDefaultPort() { return 0; } public ListBoxModel doFillCustomServerCertificateIdItems( @AncestorInPath Item item, - @QueryParameter String customServerCertificateId) - { + @QueryParameter String customServerCertificateId) { return new StandardListBoxModel().withEmptySelection() .withMatching( // CredentialsMatchers.anyOf( @@ -247,33 +218,28 @@ public ListBoxModel doFillCustomServerCertificateIdItems( ); } - public FormValidation doCheckUrl(@QueryParameter("value") String value) - { - if (StringUtils.isBlank(value)) - { + public FormValidation doCheckUrl(@QueryParameter("value") String value) { + if (StringUtils.isBlank(value)) { return FormValidation.warning(Messages.PleaseProvideHost()); } - try - { + try { URL url = new URL(value); - if (url.getUserInfo() != null) - { + if (url.getUserInfo() != null) { return FormValidation.error("Please specify user and password not as part of the url."); } - if(StringUtils.isBlank(url.getPath()) || url.getPath().trim().matches("^\\/+$")) { + if (StringUtils.isBlank(url.getPath()) || url.getPath().trim().matches("^\\/+$")) { return FormValidation.warning("Elastic Search requires a key to be able to index the logs."); } url.toURI(); - } - catch (MalformedURLException | URISyntaxException e) - { + } catch (MalformedURLException | URISyntaxException e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); } + public FormValidation doCheckMimeType(@QueryParameter("value") String value) { if (StringUtils.isBlank(value)) { return FormValidation.error(Messages.ValueIsRequired()); diff --git a/src/main/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexer.java b/src/main/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexer.java index 055551a6..bebef6f3 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexer.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexer.java @@ -4,8 +4,8 @@ import jenkins.plugins.logstash.persistence.AbstractLogstashIndexerDao; -public abstract class HostBasedLogstashIndexer extends LogstashIndexer -{ +public abstract class HostBasedLogstashIndexer extends LogstashIndexer { + private String host; private int port; @@ -14,8 +14,7 @@ public abstract class HostBasedLogstashIndexer other = (HostBasedLogstashIndexer) obj; + if (host == null) { if (other.host != null) return false; @@ -78,6 +76,7 @@ public boolean equals(Object obj) { return false; if (port != other.port) return false; + return true; } } diff --git a/src/main/java/jenkins/plugins/logstash/configuration/Logstash.java b/src/main/java/jenkins/plugins/logstash/configuration/Logstash.java index 8fd8a662..4335960a 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/Logstash.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/Logstash.java @@ -6,36 +6,28 @@ import hudson.Extension; import jenkins.plugins.logstash.persistence.LogstashDao; -public class Logstash extends HostBasedLogstashIndexer -{ +public class Logstash extends HostBasedLogstashIndexer { @DataBoundConstructor - public Logstash() - { - } + public Logstash() {} @Override - protected LogstashDao createIndexerInstance() - { + protected LogstashDao createIndexerInstance() { return new LogstashDao(getHost(), getPort()); } @Extension @Symbol("logstash") - public static class Descriptor extends LogstashIndexerDescriptor - { + public static class Descriptor extends LogstashIndexerDescriptor { @Override - public String getDisplayName() - { + public String getDisplayName() { return "Logstash TCP"; } @Override - public int getDefaultPort() - { + public int getDefaultPort() { return 9000; } - } } diff --git a/src/main/java/jenkins/plugins/logstash/configuration/LogstashIndexer.java b/src/main/java/jenkins/plugins/logstash/configuration/LogstashIndexer.java index 1a0066d9..3a4e3a65 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/LogstashIndexer.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/LogstashIndexer.java @@ -27,8 +27,8 @@ */ public abstract class LogstashIndexer extends AbstractDescribableImpl> - implements ExtensionPoint, ReconfigurableDescribable> -{ + implements ExtensionPoint, ReconfigurableDescribable> { + protected transient T instance; /** @@ -38,10 +38,8 @@ public abstract class LogstashIndexer * @return {@link AbstractLogstashIndexerDao} instance */ @NonNull - public synchronized T getInstance() - { - if (instance == null) - { + public synchronized T getInstance() { + if (instance == null) { instance = createIndexerInstance(); } return instance; @@ -53,10 +51,7 @@ public synchronized T getInstance() * * @throws Exception on erroneous input */ - public void validate() throws Exception { - } - - + public void validate() throws Exception {} /** * Creates a new {@link AbstractLogstashIndexerDao} instance corresponding to this configuration. @@ -65,36 +60,27 @@ public void validate() throws Exception { */ protected abstract T createIndexerInstance(); - @SuppressWarnings("unchecked") - public static DescriptorExtensionList, Descriptor>> all() - { + public static DescriptorExtensionList, Descriptor>> all() { return (DescriptorExtensionList, Descriptor>>) Jenkins.getInstance().getDescriptorList(LogstashIndexer.class); } - public static abstract class LogstashIndexerDescriptor extends Descriptor> - { + public static abstract class LogstashIndexerDescriptor extends Descriptor> { /* * Form validation methods */ - public FormValidation doCheckPort(@QueryParameter("value") String value) - { - try - { + public FormValidation doCheckPort(@QueryParameter("value") String value) { + try { Integer.parseInt(value); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return FormValidation.error(Messages.ValueIsInt()); } return FormValidation.ok(); } - public FormValidation doCheckHost(@QueryParameter("value") String value) - { - if (StringUtils.isBlank(value)) - { + public FormValidation doCheckHost(@QueryParameter("value") String value) { + if (StringUtils.isBlank(value)) { return FormValidation.warning(Messages.PleaseProvideHost()); } @@ -108,8 +94,7 @@ public FormValidation doCheckHost(@QueryParameter("value") String value) * {@inheritDoc} */ @Override - public LogstashIndexer reconfigure(StaplerRequest req, JSONObject form) throws FormException - { + public LogstashIndexer reconfigure(StaplerRequest req, JSONObject form) throws FormException { req.bindJSON(this, form); return this; } diff --git a/src/main/java/jenkins/plugins/logstash/configuration/RabbitMq.java b/src/main/java/jenkins/plugins/logstash/configuration/RabbitMq.java index 1047547e..e767f673 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/RabbitMq.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/RabbitMq.java @@ -16,8 +16,7 @@ import jenkins.plugins.logstash.Messages; import jenkins.plugins.logstash.persistence.RabbitMqDao; -public class RabbitMq extends HostBasedLogstashIndexer -{ +public class RabbitMq extends HostBasedLogstashIndexer { private String queue; private String username; @@ -26,129 +25,102 @@ public class RabbitMq extends HostBasedLogstashIndexer private String virtualHost; @DataBoundConstructor - public RabbitMq(String charset) - { - if (charset == null || charset.isEmpty()) - { + public RabbitMq(String charset) { + if (charset == null || charset.isEmpty()) { this.charset = Charset.defaultCharset().toString(); - } - else - { + } else { this.charset = Charset.forName(charset).toString(); } } - protected Object readResolve() - { - if (charset == null) - { + protected Object readResolve() { + if (charset == null) { charset = Charset.defaultCharset().toString(); } - if (virtualHost == null) - { + if (virtualHost == null) { virtualHost = "/"; } return this; } - public String getCharset() - { + public String getCharset() { return charset; } // package visibility for testing only @Restricted(NoExternalUse.class) - Charset getEffectiveCharset() - { - try - { + Charset getEffectiveCharset() { + try { return Charset.forName(charset); - - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { return Charset.defaultCharset(); } } - public String getVirtualHost() - { + public String getVirtualHost() { return virtualHost; } @DataBoundSetter - public void setVirtualHost(String virtualHost) - { + public void setVirtualHost(String virtualHost) { this.virtualHost = virtualHost; } - public String getQueue() - { + public String getQueue() { return queue; } @DataBoundSetter - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } - public String getUsername() - { + public String getUsername() { return username; } @DataBoundSetter - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } - public Secret getPassword() - { + public Secret getPassword() { return password; } @DataBoundSetter - public void setPassword(Secret password) - { + public void setPassword(Secret password) { this.password = password; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; + RabbitMq other = (RabbitMq) obj; - if (!Secret.toString(password).equals(Secret.toString(other.getPassword()))) - { + + if (!Secret.toString(password).equals(Secret.toString(other.getPassword()))) { return false; } - if (!StringUtils.equals(queue, other.queue)) - { + if (!StringUtils.equals(queue, other.queue)) { return false; } - if (!StringUtils.equals(username, other.username)) - { + if (!StringUtils.equals(username, other.username)) { return false; } - if (!StringUtils.equals(virtualHost, other.virtualHost)) - { + if (!StringUtils.equals(virtualHost, other.virtualHost)) { return false; } - if (charset == null) - { - if (other.charset != null) - { + if (charset == null) { + if (other.charset != null) { return false; } - } else if (!charset.equals(other.charset)) - { + } else if (!charset.equals(other.charset)) { return false; } @@ -156,8 +128,7 @@ public boolean equals(Object obj) } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((queue == null) ? 0 : queue.hashCode()); @@ -169,36 +140,29 @@ public int hashCode() } @Override - public RabbitMqDao createIndexerInstance() - { + public RabbitMqDao createIndexerInstance() { return new RabbitMqDao(getHost(), getPort(), queue, username, Secret.toString(password), getEffectiveCharset(), getVirtualHost()); } @Extension @Symbol("rabbitMq") - public static class RabbitMqDescriptor extends LogstashIndexerDescriptor - { + public static class RabbitMqDescriptor extends LogstashIndexerDescriptor { @Override - public String getDisplayName() - { + public String getDisplayName() { return "RabbitMQ"; } @Override - public int getDefaultPort() - { + public int getDefaultPort() { return 5672; } - public FormValidation doCheckQueue(@QueryParameter("value") String value) - { - if (StringUtils.isBlank(value)) - { + public FormValidation doCheckQueue(@QueryParameter("value") String value) { + if (StringUtils.isBlank(value)) { return FormValidation.error(Messages.ValueIsRequired()); } return FormValidation.ok(); } - } } diff --git a/src/main/java/jenkins/plugins/logstash/configuration/Redis.java b/src/main/java/jenkins/plugins/logstash/configuration/Redis.java index 373743be..4df9acc9 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/Redis.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/Redis.java @@ -12,68 +12,58 @@ import jenkins.plugins.logstash.Messages; import jenkins.plugins.logstash.persistence.RedisDao; -public class Redis extends HostBasedLogstashIndexer -{ +public class Redis extends HostBasedLogstashIndexer { protected String key; protected Secret password; @DataBoundConstructor - public Redis() - { - } + public Redis() {} - public String getKey() - { + public String getKey() { return key; } @DataBoundSetter - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } - public Secret getPassword() - { + public Secret getPassword() { return password; } @DataBoundSetter - public void setPassword(Secret password) - { + public void setPassword(Secret password) { this.password = password; } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; + Redis other = (Redis) obj; - if (!Secret.toString(password).equals(Secret.toString(other.getPassword()))) - { + + if (!Secret.toString(password).equals(Secret.toString(other.getPassword()))) { return false; } - if (key == null) - { + if (key == null) { if (other.key != null) return false; - } - else if (!key.equals(other.key)) - { + } else if (!key.equals(other.key)) { return false; } + return true; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((key == null) ? 0 : key.hashCode()); @@ -83,32 +73,26 @@ public int hashCode() @Override - public RedisDao createIndexerInstance() - { + public RedisDao createIndexerInstance() { return new RedisDao(getHost(), getPort(), key, Secret.toString(password)); } @Extension @Symbol("redis") - public static class RedisDescriptor extends LogstashIndexerDescriptor - { + public static class RedisDescriptor extends LogstashIndexerDescriptor { @Override - public String getDisplayName() - { + public String getDisplayName() { return "Redis"; } @Override - public int getDefaultPort() - { + public int getDefaultPort() { return 6379; } - public FormValidation doCheckKey(@QueryParameter("value") String value) - { - if (StringUtils.isBlank(value)) - { + public FormValidation doCheckKey(@QueryParameter("value") String value) { + if (StringUtils.isBlank(value)) { return FormValidation.error(Messages.ValueIsRequired()); } diff --git a/src/main/java/jenkins/plugins/logstash/configuration/Syslog.java b/src/main/java/jenkins/plugins/logstash/configuration/Syslog.java index a190d8fb..679312d0 100644 --- a/src/main/java/jenkins/plugins/logstash/configuration/Syslog.java +++ b/src/main/java/jenkins/plugins/logstash/configuration/Syslog.java @@ -10,40 +10,34 @@ import jenkins.plugins.logstash.persistence.LogstashIndexerDao.SyslogProtocol; import jenkins.plugins.logstash.persistence.SyslogDao; -public class Syslog extends HostBasedLogstashIndexer -{ +public class Syslog extends HostBasedLogstashIndexer { + private MessageFormat messageFormat; private SyslogProtocol syslogProtocol; @DataBoundConstructor - public Syslog() - {} + public Syslog() {} - public MessageFormat getMessageFormat() - { + public MessageFormat getMessageFormat() { return messageFormat; } @DataBoundSetter - public void setMessageFormat(MessageFormat messageFormat) - { + public void setMessageFormat(MessageFormat messageFormat) { this.messageFormat = messageFormat; } - public SyslogProtocol getSyslogProtocol() - { + public SyslogProtocol getSyslogProtocol() { return syslogProtocol; } @DataBoundSetter() - public void setSyslogProtocol(SyslogProtocol syslogProtocol) - { + public void setSyslogProtocol(SyslogProtocol syslogProtocol) { this.syslogProtocol = syslogProtocol; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((messageFormat == null) ? 0 : messageFormat.hashCode()); @@ -52,25 +46,26 @@ public int hashCode() } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; + Syslog other = (Syslog)obj; + if (messageFormat != other.messageFormat) return false; if (syslogProtocol != other.syslogProtocol) return false; + return true; } @Override - public SyslogDao createIndexerInstance() - { + public SyslogDao createIndexerInstance() { SyslogDao syslogDao = new SyslogDao(getHost(), getPort()); syslogDao.setMessageFormat(messageFormat); return syslogDao; @@ -78,18 +73,15 @@ public SyslogDao createIndexerInstance() @Extension @Symbol("syslog") - public static class SyslogDescriptor extends LogstashIndexerDescriptor - { + public static class SyslogDescriptor extends LogstashIndexerDescriptor { @Override - public String getDisplayName() - { + public String getDisplayName() { return "Syslog"; } @Override - public int getDefaultPort() - { + public int getDefaultPort() { return 519; } } diff --git a/src/main/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDao.java b/src/main/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDao.java index 47a16241..0ab1d98f 100644 --- a/src/main/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDao.java +++ b/src/main/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDao.java @@ -52,5 +52,4 @@ public JSONObject buildPayload(BuildData buildData, String jenkinsUrl, List failedTestsWithErrorDetail; @@ -77,19 +78,18 @@ public static class TestData implements Serializable { public static class FailedTest implements Serializable { private final String fullName, errorDetails; + public FailedTest(String fullName, String errorDetails) { super(); this.fullName = fullName; this.errorDetails = errorDetails; } - public String getFullName() - { + public String getFullName() { return fullName; } - public String getErrorDetails() - { + public String getErrorDetails() { return errorDetails; } } @@ -124,33 +124,27 @@ public TestData(Action action) { } } - public int getTotalCount() - { + public int getTotalCount() { return totalCount; } - public int getSkipCount() - { + public int getSkipCount() { return skipCount; } - public int getFailCount() - { + public int getFailCount() { return failCount; } - public int getPassCount() - { + public int getPassCount() { return passCount; } - public List getFailedTestsWithErrorDetail() - { + public List getFailedTestsWithErrorDetail() { return failedTestsWithErrorDetail; } - public List getFailedTests() - { + public List getFailedTests() { return failedTests; } } @@ -239,7 +233,6 @@ public BuildData(Run build, Date currentTime, TaskListener listener, Strin } private void initData(Run build, Date currentTime) { - this.build = build; Executor executor = build.getExecutor(); if (executor == null) { @@ -269,8 +262,7 @@ private void initData(Run build, Date currentTime) { updateResult(); } - public void updateResult() - { + public void updateResult() { if (build != null) { if (result == null && build.getResult() != null) { Result result = build.getResult(); diff --git a/src/main/java/jenkins/plugins/logstash/persistence/ElasticSearchDao.java b/src/main/java/jenkins/plugins/logstash/persistence/ElasticSearchDao.java index 5fdfae00..e0b18854 100644 --- a/src/main/java/jenkins/plugins/logstash/persistence/ElasticSearchDao.java +++ b/src/main/java/jenkins/plugins/logstash/persistence/ElasticSearchDao.java @@ -52,7 +52,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jenkins.plugins.logstash.utils.SSLHelper; - /** * Elastic Search Data Access Object. * @@ -79,9 +78,7 @@ public ElasticSearchDao(URI uri, String username, String password) { // Factored for unit testing ElasticSearchDao(HttpClientBuilder factory, URI uri, String username, String password) { - - if (uri == null) - { + if (uri == null) { throw new IllegalArgumentException("uri field must not be empty"); } @@ -89,13 +86,9 @@ public ElasticSearchDao(URI uri, String username, String password) { this.username = username; this.password = password; - - try - { + try { uri.toURL(); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } @@ -137,38 +130,31 @@ private synchronized HttpClientBuilder getClientBuilder() throws IOException { return clientBuilder; } - - public URI getUri() - { + public URI getUri() { return uri; } - public String getHost() - { + + public String getHost() { return uri.getHost(); } - public String getScheme() - { + public String getScheme() { return uri.getScheme(); } - public int getPort() - { + public int getPort() { return uri.getPort(); } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - public String getKey() - { + public String getKey() { return uri.getPath(); } @@ -180,8 +166,7 @@ public void setMimeType(String mimeType) { this.mimeType = mimeType; } - String getAuth() - { + String getAuth() { return auth; } @@ -239,9 +224,7 @@ private String getErrorMessage(CloseableHttpResponse response) { } stream.flush(); return byteStream.toString(StandardCharsets.UTF_8.name()); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { return ExceptionUtils.getStackTrace(e); } finally { if (stream != null) { @@ -250,10 +233,8 @@ private String getErrorMessage(CloseableHttpResponse response) { } } - @Override - public String getDescription() - { + public String getDescription() { return uri.toString(); } } diff --git a/src/main/java/jenkins/plugins/logstash/persistence/HostBasedLogstashIndexerDao.java b/src/main/java/jenkins/plugins/logstash/persistence/HostBasedLogstashIndexerDao.java index 41cc0c3d..9f0bbebe 100644 --- a/src/main/java/jenkins/plugins/logstash/persistence/HostBasedLogstashIndexerDao.java +++ b/src/main/java/jenkins/plugins/logstash/persistence/HostBasedLogstashIndexerDao.java @@ -22,7 +22,6 @@ package jenkins.plugins.logstash.persistence; - import org.apache.commons.lang.StringUtils; /** diff --git a/src/main/java/jenkins/plugins/logstash/persistence/LogstashDao.java b/src/main/java/jenkins/plugins/logstash/persistence/LogstashDao.java index 11580e0f..ceb281d1 100644 --- a/src/main/java/jenkins/plugins/logstash/persistence/LogstashDao.java +++ b/src/main/java/jenkins/plugins/logstash/persistence/LogstashDao.java @@ -14,8 +14,7 @@ public LogstashDao(String logstashHostString, int logstashPortInt) { @Override public void push(String data) throws IOException { - try (Socket logstashClientSocket = new Socket(getHost(), getPort())) - { + try (Socket logstashClientSocket = new Socket(getHost(), getPort())) { OutputStream out = logstashClientSocket.getOutputStream(); out.write(data.getBytes(StandardCharsets.UTF_8)); out.write(10); diff --git a/src/main/java/jenkins/plugins/logstash/persistence/RabbitMqDao.java b/src/main/java/jenkins/plugins/logstash/persistence/RabbitMqDao.java index fbbda53c..9f7f7adb 100644 --- a/src/main/java/jenkins/plugins/logstash/persistence/RabbitMqDao.java +++ b/src/main/java/jenkins/plugins/logstash/persistence/RabbitMqDao.java @@ -95,8 +95,7 @@ private synchronized ConnectionFactory getPool() { } private void initPool() { - if (pool != null) - { + if (pool != null) { pool.setHost(getHost()); pool.setPort(getPort()); if (virtualHost != null) { @@ -110,23 +109,19 @@ private void initPool() { } } - public String getQueue() - { + public String getQueue() { return queue; } - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - public String getVirtualHost() - { + public String getVirtualHost() { return virtualHost; } diff --git a/src/main/java/jenkins/plugins/logstash/persistence/RedisDao.java b/src/main/java/jenkins/plugins/logstash/persistence/RedisDao.java index 63848b12..4289fbcd 100644 --- a/src/main/java/jenkins/plugins/logstash/persistence/RedisDao.java +++ b/src/main/java/jenkins/plugins/logstash/persistence/RedisDao.java @@ -80,13 +80,11 @@ private synchronized void getJedisPool() { } } - public String getPassword() - { + public String getPassword() { return password; } - public String getKey() - { + public String getKey() { return key; } diff --git a/src/main/java/jenkins/plugins/logstash/pipeline/LogstashSendStep.java b/src/main/java/jenkins/plugins/logstash/pipeline/LogstashSendStep.java index df0b88b3..1ebc49b6 100644 --- a/src/main/java/jenkins/plugins/logstash/pipeline/LogstashSendStep.java +++ b/src/main/java/jenkins/plugins/logstash/pipeline/LogstashSendStep.java @@ -22,88 +22,74 @@ * Sends the tail of the log in a single event to a logstash indexer. * Pipeline counterpart of the LogstashNotifier. */ -public class LogstashSendStep extends Step -{ +public class LogstashSendStep extends Step { private int maxLines; private boolean failBuild; @DataBoundConstructor - public LogstashSendStep(int maxLines, boolean failBuild) - { + public LogstashSendStep(int maxLines, boolean failBuild) { this.maxLines = maxLines; this.failBuild = failBuild; } - public int getMaxLines() - { + public int getMaxLines() { return maxLines; } - public boolean isFailBuild() - { + public boolean isFailBuild() { return failBuild; } @Override - public StepExecution start(StepContext context) throws Exception - { + public StepExecution start(StepContext context) throws Exception { return new Execution(context, maxLines, failBuild); } @SuppressFBWarnings(value="SE_TRANSIENT_FIELD_NOT_RESTORED", justification="Only used when starting.") - private static class Execution extends SynchronousNonBlockingStepExecution - { + private static class Execution extends SynchronousNonBlockingStepExecution { private static final long serialVersionUID = 1L; private transient final int maxLines; private transient final boolean failBuild; - Execution(StepContext context, int maxLines, boolean failBuild) - { + Execution(StepContext context, int maxLines, boolean failBuild) { super(context); this.maxLines = maxLines; this.failBuild = failBuild; } @Override - protected Void run() throws Exception - { + protected Void run() throws Exception { Run run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); PrintStream errorStream = listener.getLogger(); LogstashWriter logstash = new LogstashWriter(run, errorStream, listener, run.getCharset()); logstash.writeBuildLog(maxLines); - if (failBuild && logstash.isConnectionBroken()) - { + if (failBuild && logstash.isConnectionBroken()) { throw new Exception("Failed to send data to Indexer"); } return null; } - } @Extension - public static class DescriptorImpl extends StepDescriptor - { + public static class DescriptorImpl extends StepDescriptor { /** {@inheritDoc} */ @Override - public String getDisplayName() - { + public String getDisplayName() { return Messages.DisplayName(); } @Override - public String getFunctionName() - { + public String getFunctionName() { return "logstashSend"; } @Override - public Set> getRequiredContext() - { + public Set> getRequiredContext() { Set> contexts = new HashSet<>(); contexts.add(TaskListener.class); contexts.add(Run.class); diff --git a/src/main/java/jenkins/plugins/logstash/pipeline/LogstashStep.java b/src/main/java/jenkins/plugins/logstash/pipeline/LogstashStep.java index d7f5c7e3..17fcfe03 100644 --- a/src/main/java/jenkins/plugins/logstash/pipeline/LogstashStep.java +++ b/src/main/java/jenkins/plugins/logstash/pipeline/LogstashStep.java @@ -45,25 +45,21 @@ public class LogstashStep extends Step { public LogstashStep() {} @Override - public StepExecution start(StepContext context) throws Exception - { + public StepExecution start(StepContext context) throws Exception { return new Execution(context); } /** Execution for {@link LogstashStep}. */ public static class Execution extends AbstractStepExecutionImpl { - public Execution(StepContext context) - { + public Execution(StepContext context) { super(context); } private static final long serialVersionUID = 1L; @Override - public void onResume() - { - } + public void onResume() {} /** {@inheritDoc} */ @Override @@ -170,5 +166,4 @@ public Set> getRequiredContext() { return Collections.unmodifiableSet(context); } } - } diff --git a/src/main/java/jenkins/plugins/logstash/utils/SSLHelper.java b/src/main/java/jenkins/plugins/logstash/utils/SSLHelper.java index 362e2362..97907419 100644 --- a/src/main/java/jenkins/plugins/logstash/utils/SSLHelper.java +++ b/src/main/java/jenkins/plugins/logstash/utils/SSLHelper.java @@ -39,28 +39,24 @@ import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; - public class SSLHelper { public static void setClientBuilderSSLContext(HttpClientBuilder clientBuilder, KeyStore customKeyStore) - throws CertificateException, NoSuchAlgorithmException, - IOException, KeyStoreException, KeyManagementException - { - if (customKeyStore == null) + throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, KeyManagementException { + if (customKeyStore == null) { return; + } String alias = customKeyStore.aliases().nextElement(); X509Certificate certificate = (X509Certificate) customKeyStore.getCertificate(alias); - if (certificate != null) + if (certificate != null) { clientBuilder.setSslcontext(SSLHelper.createSSLContext(alias, certificate)); + } } public static SSLContext createSSLContext(String alias, X509Certificate certificate) - throws CertificateException, NoSuchAlgorithmException, - IOException, KeyStoreException, KeyManagementException - { + throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, KeyManagementException { // Step 1: Get all defaults - TrustManagerFactory tmf = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Using null here initialises the TMF with the default trust store. tmf.init((KeyStore) null); @@ -79,8 +75,7 @@ public static SSLContext createSSLContext(String alias, X509Certificate certific ks.setEntry(alias, new KeyStore.TrustedCertificateEntry(certificate), null); // Create TMF with our custom cert's KS - tmf = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); // Get hold of the custom trust manager diff --git a/src/main/java/jenkins/plugins/logstash/utils/URIConverter.java b/src/main/java/jenkins/plugins/logstash/utils/URIConverter.java index 3fdd9944..e5f41f30 100644 --- a/src/main/java/jenkins/plugins/logstash/utils/URIConverter.java +++ b/src/main/java/jenkins/plugins/logstash/utils/URIConverter.java @@ -4,19 +4,15 @@ import org.apache.commons.beanutils.converters.AbstractConverter; -public class URIConverter extends AbstractConverter -{ +public class URIConverter extends AbstractConverter { @Override - protected Object convertToType(Class type, Object value) throws Throwable - { + protected Object convertToType(Class type, Object value) throws Throwable { return new URI(value.toString()); } @Override - protected Class getDefaultType() - { + protected Class getDefaultType() { return URI.class; } - } diff --git a/src/test/java/jenkins/plugins/logstash/ConfigAsCodeTest.java b/src/test/java/jenkins/plugins/logstash/ConfigAsCodeTest.java index b7e4cc73..93704c88 100644 --- a/src/test/java/jenkins/plugins/logstash/ConfigAsCodeTest.java +++ b/src/test/java/jenkins/plugins/logstash/ConfigAsCodeTest.java @@ -15,14 +15,12 @@ import jenkins.plugins.logstash.configuration.RabbitMq; import jenkins.plugins.logstash.configuration.Redis; -public class ConfigAsCodeTest -{ +public class ConfigAsCodeTest { @Rule public JenkinsRule r = new JenkinsRule(); @Test - public void elasticSearch() throws ConfiguratorException - { + public void elasticSearch() throws ConfiguratorException { ConfigurationAsCode.get().configure(ConfigAsCodeTest.class.getResource("/jcasc/elasticSearch.yaml").toString()); LogstashConfiguration c = LogstashConfiguration.getInstance(); assertThat(c.isEnabled(), is(true)); @@ -36,8 +34,7 @@ public void elasticSearch() throws ConfiguratorException } @Test - public void logstash() throws ConfiguratorException - { + public void logstash() throws ConfiguratorException { ConfigurationAsCode.get().configure(ConfigAsCodeTest.class.getResource("/jcasc/logstash.yaml").toString()); LogstashConfiguration c = LogstashConfiguration.getInstance(); assertThat(c.isEnabled(), is(true)); @@ -50,8 +47,7 @@ public void logstash() throws ConfiguratorException } @Test - public void rabbitMq() throws ConfiguratorException - { + public void rabbitMq() throws ConfiguratorException { ConfigurationAsCode.get().configure(ConfigAsCodeTest.class.getResource("/jcasc/rabbitmq.yaml").toString()); LogstashConfiguration c = LogstashConfiguration.getInstance(); assertThat(c.isEnabled(), is(true)); @@ -66,8 +62,7 @@ public void rabbitMq() throws ConfiguratorException } @Test - public void redis() throws ConfiguratorException - { + public void redis() throws ConfiguratorException { ConfigurationAsCode.get().configure(ConfigAsCodeTest.class.getResource("/jcasc/redis.yaml").toString()); LogstashConfiguration c = LogstashConfiguration.getInstance(); assertThat(c.isEnabled(), is(true)); diff --git a/src/test/java/jenkins/plugins/logstash/LogstashBuildWrapperConversionTest.java b/src/test/java/jenkins/plugins/logstash/LogstashBuildWrapperConversionTest.java index f569a8f0..8974d806 100644 --- a/src/test/java/jenkins/plugins/logstash/LogstashBuildWrapperConversionTest.java +++ b/src/test/java/jenkins/plugins/logstash/LogstashBuildWrapperConversionTest.java @@ -21,32 +21,28 @@ import hudson.model.Project; -public class LogstashBuildWrapperConversionTest -{ +public class LogstashBuildWrapperConversionTest { + @Rule public JenkinsRule j; - public LogstashBuildWrapperConversionTest() throws Exception - { + public LogstashBuildWrapperConversionTest() throws Exception { j = new JenkinsRule().withExistingHome(new File("src/test/resources/home")); } @Test - public void existingJobIsConvertedAtStartup() - { + public void existingJobIsConvertedAtStartup() { Project project = (Project)j.getInstance().getItem("test"); checkNoBuildWrapper(project); } @Before - public void setup() - { + public void setup() { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); } @Test - public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToNewJob() throws IOException - { + public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToNewJob() throws IOException { j.jenkins.setCrumbIssuer(null); String newJobName = "newJob"; URL apiURL = new URL(MessageFormat.format( @@ -56,8 +52,7 @@ public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToNewJob() throws request.setAdditionalHeader("Content-Type", "application/xml"); int result = -1; - try - { + try { request.setRequestBody("\n\n" + "" + "" + @@ -65,9 +60,7 @@ public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToNewJob() throws "" + ""); result = j.createWebClient().getPage(request).getWebResponse().getStatusCode(); - } - catch (FailingHttpStatusCodeException e) - { + } catch (FailingHttpStatusCodeException e) { result = e.getResponse().getStatusCode(); } @@ -77,8 +70,7 @@ public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToNewJob() throws } @Test - public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToExistingJob() throws IOException - { + public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToExistingJob() throws IOException { j.jenkins.setCrumbIssuer(null); String newJobName = "newJob"; j.createFreeStyleProject(newJobName); @@ -89,8 +81,7 @@ public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToExistingJob() th request.setAdditionalHeader("Content-Type", "application/xml"); int result = -1; - try - { + try { request.setRequestBody("\n\n" + "" + "" + @@ -98,9 +89,7 @@ public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToExistingJob() th "" + ""); result = j.createWebClient().getPage(request).getWebResponse().getStatusCode(); - } - catch (FailingHttpStatusCodeException e) - { + } catch (FailingHttpStatusCodeException e) { result = e.getResponse().getStatusCode(); } @@ -109,8 +98,7 @@ public void buildWrapperIsConvertedToJobPropertyWhenPostingXMLToExistingJob() th checkNoBuildWrapper(project); } - private void checkNoBuildWrapper(Project project) - { + private void checkNoBuildWrapper(Project project) { assertThat(project.getBuildWrappersList().get(LogstashBuildWrapper.class), equalTo(null)); assertThat(project.getProperty(LogstashJobProperty.class), not(equalTo(null))); } diff --git a/src/test/java/jenkins/plugins/logstash/LogstashConfigurationMigrationTest.java b/src/test/java/jenkins/plugins/logstash/LogstashConfigurationMigrationTest.java index ff575801..0f867248 100644 --- a/src/test/java/jenkins/plugins/logstash/LogstashConfigurationMigrationTest.java +++ b/src/test/java/jenkins/plugins/logstash/LogstashConfigurationMigrationTest.java @@ -36,8 +36,7 @@ @RunWith(PowerMockRunner.class) @PrepareForTest({ LogstashInstallation.class, Descriptor.class }) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.crypto.*", "javax.xml.*", "org.xml.*"}) -public class LogstashConfigurationMigrationTest extends LogstashConfigurationTestBase -{ +public class LogstashConfigurationMigrationTest extends LogstashConfigurationTestBase { @Rule public JenkinsRule j = new JenkinsRule(); @@ -48,8 +47,7 @@ public class LogstashConfigurationMigrationTest extends LogstashConfigurationTes LogstashConfiguration configuration; @Before - public void setup() - { + public void setup() { mockStatic(LogstashInstallation.class); configFile = new File("notExisting.xml"); when(LogstashInstallation.getLogstashDescriptor()).thenAnswer(invocationOnMock -> descriptor); @@ -62,16 +60,14 @@ public void setup() } @Test - public void NoConfigMigration() - { + public void NoConfigMigration() { when(descriptor.getType()).thenReturn(null); configuration.migrateData(); assertThat(configuration.isEnabled(),equalTo(false)); } @Test - public void redisMigration() - { + public void redisMigration() { when(descriptor.getType()).thenReturn(IndexerType.REDIS); configuration.migrateData(); LogstashIndexer indexer = configuration.getLogstashIndexer(); @@ -86,8 +82,7 @@ public void redisMigration() } @Test - public void syslogMigrationRFC3164() - { + public void syslogMigrationRFC3164() { when(descriptor.getType()).thenReturn(IndexerType.SYSLOG); when(descriptor.getSyslogFormat()).thenReturn(SyslogFormat.RFC3164); configuration.migrateData(); @@ -102,8 +97,7 @@ public void syslogMigrationRFC3164() } @Test - public void syslogMigrationRFC5424() - { + public void syslogMigrationRFC5424() { when(descriptor.getType()).thenReturn(IndexerType.SYSLOG); when(descriptor.getSyslogFormat()).thenReturn(SyslogFormat.RFC5424); configuration.migrateData(); @@ -118,8 +112,7 @@ public void syslogMigrationRFC5424() } @Test - public void elasticSearchMigration() throws URISyntaxException, MalformedURLException - { + public void elasticSearchMigration() throws URISyntaxException, MalformedURLException { when(descriptor.getType()).thenReturn(IndexerType.ELASTICSEARCH); when(descriptor.getHost()).thenReturn("http://localhost"); configuration.migrateData(); @@ -135,8 +128,7 @@ public void elasticSearchMigration() throws URISyntaxException, MalformedURLExce } @Test - public void rabbitMqMigration() - { + public void rabbitMqMigration() { when(descriptor.getType()).thenReturn(IndexerType.RABBIT_MQ); configuration.migrateData(); LogstashIndexer indexer = configuration.getLogstashIndexer(); diff --git a/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTest.java b/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTest.java index a83c31f4..782ddfb3 100644 --- a/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTest.java +++ b/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTest.java @@ -24,15 +24,13 @@ import jenkins.plugins.logstash.persistence.RedisDao; import jenkins.plugins.logstash.persistence.SyslogDao; -public class LogstashConfigurationTest extends LogstashConfigurationTestBase -{ +public class LogstashConfigurationTest extends LogstashConfigurationTestBase { @Rule public JenkinsRule j = new JenkinsRule(); @Test - public void unconfiguredWillReturnNull() - { + public void unconfiguredWillReturnNull() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/notExisting.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.getIndexerInstance(), equalTo(null)); @@ -40,16 +38,14 @@ public void unconfiguredWillReturnNull() } @Test - public void disabled() - { + public void disabled() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/disabled.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.isEnabled(), equalTo(false)); } @Test - public void elasticSearchIsProperlyConfigured() - { + public void elasticSearchIsProperlyConfigured() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/elasticSearch.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.getIndexerInstance(), IsInstanceOf.instanceOf(ElasticSearchDao.class)); @@ -57,8 +53,7 @@ public void elasticSearchIsProperlyConfigured() } @Test - public void rabbitMqIsProperlyConfigured() - { + public void rabbitMqIsProperlyConfigured() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/rabbitmq.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.getIndexerInstance(), IsInstanceOf.instanceOf(RabbitMqDao.class)); @@ -67,8 +62,7 @@ public void rabbitMqIsProperlyConfigured() } @Test - public void redisIsProperlyConfigured() - { + public void redisIsProperlyConfigured() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/redis.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.getIndexerInstance(), IsInstanceOf.instanceOf(RedisDao.class)); @@ -76,8 +70,7 @@ public void redisIsProperlyConfigured() } @Test - public void syslogIsProperlyConfigured() - { + public void syslogIsProperlyConfigured() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/syslog.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.getIndexerInstance(), IsInstanceOf.instanceOf(SyslogDao.class)); @@ -85,8 +78,7 @@ public void syslogIsProperlyConfigured() } @Test - public void milliSecondsConfigured() - { + public void milliSecondsConfigured() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/rabbitmq.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.isMilliSecondTimestamps(),equalTo(true)); @@ -99,16 +91,14 @@ public void milliSecondsConfigured() * changing anything i.e. plugin is disabled. (JENKINS-51793) */ @Test - public void jenkinsInitialConfigurationCanBeSaved() throws Exception - { + public void jenkinsInitialConfigurationCanBeSaved() throws Exception { HtmlPage p = j.createWebClient().goTo("configure"); HtmlForm f = p.getFormByName("config"); j.submit(f); } @Test - public void programmaticConfigurationChangesActiveIndexer() throws Exception - { + public void programmaticConfigurationChangesActiveIndexer() throws Exception { LogstashConfigurationTestBase.configFile = new File("src/test/resources/rabbitmq.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); ElasticSearch es = new ElasticSearch(); diff --git a/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTestBase.java b/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTestBase.java index 19ffa704..5b0712dc 100644 --- a/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTestBase.java +++ b/src/test/java/jenkins/plugins/logstash/LogstashConfigurationTestBase.java @@ -4,21 +4,17 @@ import hudson.XmlFile; -public class LogstashConfigurationTestBase -{ +public class LogstashConfigurationTestBase { + protected static File configFile; - public static class LogstashConfigurationForTest extends LogstashConfiguration - { + public static class LogstashConfigurationForTest extends LogstashConfiguration { @Override - public synchronized void save() - { - } + public synchronized void save() {} @Override - protected XmlFile getConfigFile() - { + protected XmlFile getConfigFile() { return new XmlFile(configFile); } } diff --git a/src/test/java/jenkins/plugins/logstash/LogstashConsoleLogFilterTest.java b/src/test/java/jenkins/plugins/logstash/LogstashConsoleLogFilterTest.java index 71f303a2..c1a41e48 100644 --- a/src/test/java/jenkins/plugins/logstash/LogstashConsoleLogFilterTest.java +++ b/src/test/java/jenkins/plugins/logstash/LogstashConsoleLogFilterTest.java @@ -131,8 +131,7 @@ public void decorateLoggerSuccessBadWriter() throws Exception { } @Test - public void decorateLoggerSuccessEnabledGlobally() throws IOException, InterruptedException - { + public void decorateLoggerSuccessEnabledGlobally() throws IOException, InterruptedException { when(logstashConfiguration.isEnableGlobally()).thenReturn(true); MockLogstashConsoleLogFilter buildWrapper = new MockLogstashConsoleLogFilter(mockWriter); diff --git a/src/test/java/jenkins/plugins/logstash/LogstashIntegrationTest.java b/src/test/java/jenkins/plugins/logstash/LogstashIntegrationTest.java index 7a912cca..48861e88 100644 --- a/src/test/java/jenkins/plugins/logstash/LogstashIntegrationTest.java +++ b/src/test/java/jenkins/plugins/logstash/LogstashIntegrationTest.java @@ -37,8 +37,8 @@ import net.sf.json.JSONException; import net.sf.json.JSONObject; -public class LogstashIntegrationTest -{ +public class LogstashIntegrationTest { + @Rule public JenkinsRule jenkins = new JenkinsRule(); @@ -52,8 +52,7 @@ public class LogstashIntegrationTest private MemoryDao memoryDao; @Before - public void setup() throws Exception - { + public void setup() throws Exception { memoryDao = new MemoryDao(); LogstashConfiguration config = LogstashConfiguration.getInstance(); MemoryIndexer indexer = new MemoryIndexer(memoryDao); @@ -66,8 +65,7 @@ public void setup() throws Exception } @Test - public void dataIsSetWhenEnabledViaJobPropertyOnMaster() throws Exception - { + public void dataIsSetWhenEnabledViaJobPropertyOnMaster() throws Exception { project.addProperty(new LogstashJobProperty()); QueueTaskFuture f = project.scheduleBuild2(0); FreeStyleBuild build = f.get(); @@ -83,8 +81,7 @@ public void dataIsSetWhenEnabledViaJobPropertyOnMaster() throws Exception } @Test - public void dataIsSetWhenEnabledViaJobPropertyOnSlave() throws Exception - { + public void dataIsSetWhenEnabledViaJobPropertyOnSlave() throws Exception { project.addProperty(new LogstashJobProperty()); project.setAssignedNode(slave); @@ -102,8 +99,7 @@ public void dataIsSetWhenEnabledViaJobPropertyOnSlave() throws Exception } @Test - public void dataIsSetForNotifierOnMaster() throws Exception - { + public void dataIsSetForNotifierOnMaster() throws Exception { project.getPublishersList().add(new LogstashNotifier(10, false)); QueueTaskFuture f = project.scheduleBuild2(0); FreeStyleBuild build = f.get(); @@ -117,8 +113,7 @@ public void dataIsSetForNotifierOnMaster() throws Exception } @Test - public void dataIsSetForNotifierOnSlave() throws Exception - { + public void dataIsSetForNotifierOnSlave() throws Exception { project.getPublishersList().add(new LogstashNotifier(10, false)); project.setAssignedNode(slave); QueueTaskFuture f = project.scheduleBuild2(0); @@ -133,8 +128,7 @@ public void dataIsSetForNotifierOnSlave() throws Exception } @Test - public void buildJobPropertyUpdatesResult() throws Exception - { + public void buildJobPropertyUpdatesResult() throws Exception { project.addProperty(new LogstashJobProperty()); QueueTaskFuture f = project.scheduleBuild2(0); FreeStyleBuild build = f.get(); @@ -152,8 +146,7 @@ public void buildJobPropertyUpdatesResult() throws Exception } @Test - public void passwordsAreMaskedWithMaskpasswordsBuildWrapper() throws Exception - { + public void passwordsAreMaskedWithMaskpasswordsBuildWrapper() throws Exception { EnvInjectJobPropertyInfo info = new EnvInjectJobPropertyInfo(null, "PWD=myPassword", null, null, false, null); EnvInjectBuildWrapper e = new EnvInjectBuildWrapper(info); @@ -170,8 +163,7 @@ public void passwordsAreMaskedWithMaskpasswordsBuildWrapper() throws Exception FreeStyleBuild build = f.get(); assertThat(build.getResult(), equalTo(Result.SUCCESS)); List dataLines = memoryDao.getOutput(); - for (JSONObject line: dataLines) - { + for (JSONObject line : dataLines) { JSONArray message = line.getJSONArray("message"); String logline = (String) message.get(0); assertThat(logline,not(containsString("myPassword"))); @@ -179,8 +171,7 @@ public void passwordsAreMaskedWithMaskpasswordsBuildWrapper() throws Exception } @Test - public void passwordsAreMaskedWithGlobalMaskPasswordsConfiguration() throws Exception - { + public void passwordsAreMaskedWithGlobalMaskPasswordsConfiguration() throws Exception { MaskPasswordsConfig config = MaskPasswordsConfig.getInstance(); config.setGlobalVarEnabledGlobally(true); VarPasswordPair pwdPair = new VarPasswordPair("PWD", "myPassword"); @@ -195,8 +186,7 @@ public void passwordsAreMaskedWithGlobalMaskPasswordsConfiguration() throws Exce FreeStyleBuild build = f.get(); assertThat(build.getResult(), equalTo(Result.SUCCESS)); List dataLines = memoryDao.getOutput(); - for (JSONObject line: dataLines) - { + for (JSONObject line : dataLines) { JSONArray message = line.getJSONArray("message"); String logline = (String) message.get(0); assertThat(logline,not(containsString("myPassword"))); @@ -204,8 +194,7 @@ public void passwordsAreMaskedWithGlobalMaskPasswordsConfiguration() throws Exce } @Test - public void enableGlobally() throws Exception - { + public void enableGlobally() throws Exception { LogstashConfiguration.getInstance().setEnableGlobally(true); QueueTaskFuture f = project.scheduleBuild2(0); @@ -222,9 +211,7 @@ public void enableGlobally() throws Exception } @Test - public void milliSecondTimestamps() throws Exception - { - + public void milliSecondTimestamps() throws Exception { LogstashConfiguration.getInstance().setMilliSecondTimestamps(true); project.addProperty(new LogstashJobProperty()); QueueTaskFuture f = project.scheduleBuild2(0); @@ -232,16 +219,14 @@ public void milliSecondTimestamps() throws Exception FreeStyleBuild build = f.get(); assertThat(build.getResult(), equalTo(Result.SUCCESS)); List dataLines = memoryDao.getOutput(); - for (JSONObject line: dataLines) - { + for (JSONObject line : dataLines) { String timestamp = line.getString("@timestamp"); assertThat(timestamp,matchesPattern("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}[+-]\\d{4}$")); } } @Test - public void secondTimestamps() throws Exception - { + public void secondTimestamps() throws Exception { LogstashConfiguration.getInstance().setMilliSecondTimestamps(false); project.addProperty(new LogstashJobProperty()); QueueTaskFuture f = project.scheduleBuild2(0); @@ -249,16 +234,14 @@ public void secondTimestamps() throws Exception FreeStyleBuild build = f.get(); assertThat(build.getResult(), equalTo(Result.SUCCESS)); List dataLines = memoryDao.getOutput(); - for (JSONObject line: dataLines) - { + for (JSONObject line : dataLines) { String timestamp = line.getString("@timestamp"); assertThat(timestamp,matchesPattern("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}[+-]\\d{4}$")); } } @Test - public void ansiColorAnnotationsAreNotIncluded() throws Exception - { + public void ansiColorAnnotationsAreNotIncluded() throws Exception { AnsiColorBuildWrapper ansi = new AnsiColorBuildWrapper("vga"); project.addProperty(new LogstashJobProperty()); project.getBuildWrappersList().add(ansi); @@ -273,8 +256,7 @@ public void ansiColorAnnotationsAreNotIncluded() throws Exception } @Test - public void disabledWillNotWrite() throws Exception - { + public void disabledWillNotWrite() throws Exception { LogstashConfiguration.getInstance().setEnabled(false); project.addProperty(new LogstashJobProperty()); Cause cause = new Cause.UserIdCause(); diff --git a/src/test/java/jenkins/plugins/logstash/PipelineTest.java b/src/test/java/jenkins/plugins/logstash/PipelineTest.java index 98820341..51f4d128 100644 --- a/src/test/java/jenkins/plugins/logstash/PipelineTest.java +++ b/src/test/java/jenkins/plugins/logstash/PipelineTest.java @@ -21,8 +21,7 @@ import jenkins.plugins.logstash.persistence.MemoryDao; import net.sf.json.JSONObject; -public class PipelineTest -{ +public class PipelineTest { @ClassRule public static BuildWatcher buildWatcher = new BuildWatcher(); @@ -31,8 +30,7 @@ public class PipelineTest private MemoryDao memoryDao; @Before - public void setup() throws Exception - { + public void setup() throws Exception { memoryDao = new MemoryDao(); LogstashConfiguration config = LogstashConfiguration.getInstance(); MemoryIndexer indexer = new MemoryIndexer(memoryDao); @@ -41,8 +39,7 @@ public void setup() throws Exception } @Test - public void logstash() throws Exception - { + public void logstash() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("logstash {\n" + "currentBuild.result = 'SUCCESS'\n" + @@ -57,8 +54,7 @@ public void logstash() throws Exception } @Test - public void logstashStageAndAgent() throws Exception - { + public void logstashStageAndAgent() throws Exception { Slave slave = j.createOnlineSlave(); String agentName = slave.getNodeName(); WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); @@ -79,8 +75,7 @@ public void logstashStageAndAgent() throws Exception } @Test - public void globalLogstash() throws Exception - { + public void globalLogstash() throws Exception { LogstashConfiguration config = LogstashConfiguration.getInstance(); config.setEnableGlobally(true); WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); @@ -96,8 +91,7 @@ public void globalLogstash() throws Exception } @Test - public void logstashSendNotifier() throws Exception - { + public void logstashSendNotifier() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("node {" + "echo 'Message'\n" + @@ -113,8 +107,7 @@ public void logstashSendNotifier() throws Exception } @Test - public void logstashSend() throws Exception - { + public void logstashSend() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "echo 'Message'\n" + diff --git a/src/test/java/jenkins/plugins/logstash/configuration/ElasticSearchTest.java b/src/test/java/jenkins/plugins/logstash/configuration/ElasticSearchTest.java index 4e924180..e20e3197 100644 --- a/src/test/java/jenkins/plugins/logstash/configuration/ElasticSearchTest.java +++ b/src/test/java/jenkins/plugins/logstash/configuration/ElasticSearchTest.java @@ -13,8 +13,7 @@ import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; -public class ElasticSearchTest -{ +public class ElasticSearchTest { @Rule public JenkinsRule j = new JenkinsRule(); @@ -23,8 +22,7 @@ public class ElasticSearchTest private ElasticSearch indexer2; @Before - public void setup() throws MalformedURLException, URISyntaxException - { + public void setup() throws MalformedURLException, URISyntaxException { URL url = new URL("http://localhost:4567/key"); indexer = new ElasticSearch(); indexer.setUri(url); @@ -37,31 +35,27 @@ public void setup() throws MalformedURLException, URISyntaxException indexer2.setPassword(Secret.fromString("password")); indexer2.setUsername("user"); indexer2.setMimeType("application/json"); -} + } @Test - public void sameSettingsAreEqual() - { + public void sameSettingsAreEqual() { assertThat(indexer.equals(indexer2), is(true)); } @Test - public void passwordChangeIsNotEqual() - { + public void passwordChangeIsNotEqual() { indexer.setPassword(Secret.fromString("newPassword")); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void urlChangeIsNotEqual() throws MalformedURLException, URISyntaxException - { + public void urlChangeIsNotEqual() throws MalformedURLException, URISyntaxException { indexer.setUri(new URL("https://localhost:4567/key")); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void usernameChangeIsNotEqual() - { + public void usernameChangeIsNotEqual() { indexer.setUsername("newUser"); assertThat(indexer.equals(indexer2), is(false)); } diff --git a/src/test/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexerTest.java b/src/test/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexerTest.java index 7d203add..f3731f16 100644 --- a/src/test/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexerTest.java +++ b/src/test/java/jenkins/plugins/logstash/configuration/HostBasedLogstashIndexerTest.java @@ -8,51 +8,43 @@ import jenkins.plugins.logstash.persistence.MemoryDao; -public class HostBasedLogstashIndexerTest -{ +public class HostBasedLogstashIndexerTest { private LogstashIndexerForTest indexer; private LogstashIndexerForTest indexer2; @Before - public void setup() - { + public void setup() { indexer = new LogstashIndexerForTest("localhost", 4567); indexer2 = new LogstashIndexerForTest("localhost", 4567); } @Test - public void sameSettingsAreEqual() - { + public void sameSettingsAreEqual() { assertThat(indexer.equals(indexer2), is(true)); } @Test - public void hostChangeIsNotEqual() - { + public void hostChangeIsNotEqual() { indexer.setHost("remoteHost"); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void portChangeIsNotEqual() - { + public void portChangeIsNotEqual() { indexer.setPort(7654); assertThat(indexer.equals(indexer2), is(false)); } - public static class LogstashIndexerForTest extends HostBasedLogstashIndexer - { + public static class LogstashIndexerForTest extends HostBasedLogstashIndexer { - public LogstashIndexerForTest(String host, int port) - { + public LogstashIndexerForTest(String host, int port) { setHost(host); setPort(port); } @Override - public MemoryDao createIndexerInstance() - { + public MemoryDao createIndexerInstance() { return new MemoryDao(); } } diff --git a/src/test/java/jenkins/plugins/logstash/configuration/MemoryIndexer.java b/src/test/java/jenkins/plugins/logstash/configuration/MemoryIndexer.java index a8fdc6f5..00ffe646 100644 --- a/src/test/java/jenkins/plugins/logstash/configuration/MemoryIndexer.java +++ b/src/test/java/jenkins/plugins/logstash/configuration/MemoryIndexer.java @@ -2,18 +2,16 @@ import jenkins.plugins.logstash.persistence.MemoryDao; -public class MemoryIndexer extends LogstashIndexer -{ +public class MemoryIndexer extends LogstashIndexer { + final MemoryDao dao; - public MemoryIndexer(MemoryDao dao) - { + public MemoryIndexer(MemoryDao dao) { this.dao = dao; } @Override - protected MemoryDao createIndexerInstance() - { + protected MemoryDao createIndexerInstance() { return dao; } diff --git a/src/test/java/jenkins/plugins/logstash/configuration/RabbitMqTest.java b/src/test/java/jenkins/plugins/logstash/configuration/RabbitMqTest.java index 18bcb32f..69bbc2bb 100644 --- a/src/test/java/jenkins/plugins/logstash/configuration/RabbitMqTest.java +++ b/src/test/java/jenkins/plugins/logstash/configuration/RabbitMqTest.java @@ -19,8 +19,7 @@ import jenkins.plugins.logstash.LogstashConfigurationTestBase.LogstashConfigurationForTest; import jenkins.plugins.logstash.persistence.RabbitMqDao; -public class RabbitMqTest extends LogstashConfigurationTestBase -{ +public class RabbitMqTest extends LogstashConfigurationTestBase { @Rule public JenkinsRule j = new JenkinsRule(); @@ -30,8 +29,7 @@ public class RabbitMqTest extends LogstashConfigurationTestBase private RabbitMq indexer3; @Before - public void setup() - { + public void setup() { indexer = new RabbitMq("UTF-8"); indexer.setHost("localhost"); indexer.setPort(4567); @@ -58,47 +56,40 @@ public void setup() } @Test - public void sameSettingsAreEqual() - { + public void sameSettingsAreEqual() { assertThat(indexer.equals(indexer2), is(true)); } @Test - public void passwordChangeIsNotEqual() - { + public void passwordChangeIsNotEqual() { indexer.setPassword(Secret.fromString("newPassword")); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void usernameChangeIsNotEqual() - { + public void usernameChangeIsNotEqual() { indexer.setUsername("newUser"); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void queueChangeIsNotEqual() - { + public void queueChangeIsNotEqual() { indexer.setQueue("newQueue"); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void charsetChangeIsNotEqual() - { + public void charsetChangeIsNotEqual() { assertThat(indexer.equals(indexer3), is(false)); } - public void vhostChangeIsNotEqual() - { + public void vhostChangeIsNotEqual() { indexer.setVirtualHost("newVhost"); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void rabbitMqBrokenCharset_returns_default_charset() - { + public void rabbitMqBrokenCharset_returns_default_charset() { LogstashConfigurationTestBase.configFile = new File("src/test/resources/rabbitmq_brokenCharset.xml"); LogstashConfiguration configuration = new LogstashConfigurationForTest(); assertThat(configuration.getIndexerInstance(), IsInstanceOf.instanceOf(RabbitMqDao.class)); diff --git a/src/test/java/jenkins/plugins/logstash/configuration/RedisTest.java b/src/test/java/jenkins/plugins/logstash/configuration/RedisTest.java index e9747ddd..25b922b2 100644 --- a/src/test/java/jenkins/plugins/logstash/configuration/RedisTest.java +++ b/src/test/java/jenkins/plugins/logstash/configuration/RedisTest.java @@ -9,8 +9,7 @@ import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; -public class RedisTest -{ +public class RedisTest { @Rule public JenkinsRule j = new JenkinsRule(); @@ -19,8 +18,7 @@ public class RedisTest private Redis indexer2; @Before - public void setup() - { + public void setup() { indexer = new Redis(); indexer.setHost("localhost"); indexer.setPort(4567); @@ -32,24 +30,21 @@ public void setup() indexer2.setPort(4567); indexer2.setKey("key"); indexer2.setPassword(Secret.fromString("password")); -} + } @Test - public void sameSettingsAreEqual() - { + public void sameSettingsAreEqual() { assertThat(indexer.equals(indexer2), is(true)); } @Test - public void passwordChangeIsNotEqual() - { + public void passwordChangeIsNotEqual() { indexer.setPassword(Secret.fromString("newPassword")); assertThat(indexer.equals(indexer2), is(false)); } @Test - public void keyChangeIsNotEqual() - { + public void keyChangeIsNotEqual() { indexer.setKey("newKey"); assertThat(indexer.equals(indexer2), is(false)); } diff --git a/src/test/java/jenkins/plugins/logstash/configuration/SyslogTest.java b/src/test/java/jenkins/plugins/logstash/configuration/SyslogTest.java index 5052e248..89fdc240 100644 --- a/src/test/java/jenkins/plugins/logstash/configuration/SyslogTest.java +++ b/src/test/java/jenkins/plugins/logstash/configuration/SyslogTest.java @@ -8,15 +8,13 @@ import com.cloudbees.syslog.MessageFormat; -public class SyslogTest -{ +public class SyslogTest { private Syslog indexer; private Syslog indexer2; @Before - public void setup() - { + public void setup() { indexer = new Syslog(); indexer.setHost("localhost"); indexer.setPort(4567); @@ -26,17 +24,15 @@ public void setup() indexer2.setHost("localhost"); indexer2.setPort(4567); indexer2.setMessageFormat(MessageFormat.RFC_3164); -} + } @Test - public void sameSettingsAreEqual() - { + public void sameSettingsAreEqual() { assertThat(indexer.equals(indexer2), is(true)); } @Test - public void messageFormatChangeIsNotEqual() - { + public void messageFormatChangeIsNotEqual() { indexer.setMessageFormat(MessageFormat.RFC_5424); assertThat(indexer.equals(indexer2), is(false)); } diff --git a/src/test/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDaoTest.java b/src/test/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDaoTest.java index 8213fd72..d16fb1b8 100644 --- a/src/test/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDaoTest.java +++ b/src/test/java/jenkins/plugins/logstash/persistence/AbstractLogstashIndexerDaoTest.java @@ -24,6 +24,7 @@ @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.crypto.*", "javax.xml.*", "org.xml.*"}) @PrepareForTest(LogstashConfiguration.class) public class AbstractLogstashIndexerDaoTest { + static final String EMPTY_STRING = "{\"@buildTimestamp\":\"2000-01-01\",\"data\":{},\"message\":[],\"source\":\"jenkins\",\"source_host\":\"http://localhost:8080/jenkins\",\"@version\":1}"; static final String ONE_LINE_STRING = "{\"@buildTimestamp\":\"2000-01-01\",\"data\":{},\"message\":[\"LINE 1\"],\"source\":\"jenkins\",\"source_host\":\"http://localhost:8080/jenkins\",\"@version\":1}"; static final String TWO_LINE_STRING = "{\"@buildTimestamp\":\"2000-01-01\",\"data\":{},\"message\":[\"LINE 1\", \"LINE 2\"],\"source\":\"jenkins\",\"source_host\":\"http://localhost:8080/jenkins\",\"@version\":1}"; @@ -81,11 +82,10 @@ private AbstractLogstashIndexerDao getInstance() { return new AbstractLogstashIndexerDao() { @Override - public void push(String data) throws IOException {} + public void push(String data) throws IOException {} @Override - public String getDescription() - { + public String getDescription() { return "test"; } }; diff --git a/src/test/java/jenkins/plugins/logstash/persistence/BuildDataTest.java b/src/test/java/jenkins/plugins/logstash/persistence/BuildDataTest.java index 8d55d074..cfa98102 100644 --- a/src/test/java/jenkins/plugins/logstash/persistence/BuildDataTest.java +++ b/src/test/java/jenkins/plugins/logstash/persistence/BuildDataTest.java @@ -76,7 +76,6 @@ public class BuildDataTest { @Before public void before() throws Exception { - PowerMockito.mockStatic(LogstashConfiguration.class); when(LogstashConfiguration.getInstance()).thenAnswer(invocationOnMock -> logstashConfiguration); when(logstashConfiguration.getDateFormatter()).thenCallRealMethod(); @@ -127,8 +126,7 @@ public void after() throws Exception { verifyNoMoreInteractions(mockRootProject); } - private void verifyMocks() throws Exception - { + private void verifyMocks() throws Exception { verify(mockProject).getName(); verify(mockProject).getFullName(); @@ -360,8 +358,7 @@ public Void answer(InvocationOnMock invocation) throws Throwable { } @Test - public void toJsonSuccess() throws Exception - { + public void toJsonSuccess() throws Exception { when(mockBuild.getId()).thenReturn("TEST_JOB_123"); when(mockBuild.getUrl()).thenReturn("http://localhost:8080/jenkins/jobs/PROJECT_NAME/123"); @@ -378,8 +375,7 @@ public void toJsonSuccess() throws Exception } @Test - public void fullName() throws Exception - { + public void fullName() throws Exception { when(mockBuild.getId()).thenReturn("TEST_JOB_123"); when(mockBuild.getUrl()).thenReturn("http://localhost:8080/jenkins/jobs/PROJECT_NAME/123"); @@ -392,8 +388,7 @@ public void fullName() throws Exception } @Test - public void rootProjectFullName() throws Exception - { + public void rootProjectFullName() throws Exception { when(mockBuild.getId()).thenReturn("TEST_JOB_123"); when(mockBuild.getUrl()).thenReturn("http://localhost:8080/jenkins/jobs/PROJECT_NAME/123"); diff --git a/src/test/java/jenkins/plugins/logstash/persistence/MemoryDao.java b/src/test/java/jenkins/plugins/logstash/persistence/MemoryDao.java index 1917186e..25cf00cd 100644 --- a/src/test/java/jenkins/plugins/logstash/persistence/MemoryDao.java +++ b/src/test/java/jenkins/plugins/logstash/persistence/MemoryDao.java @@ -7,30 +7,26 @@ import jenkins.plugins.logstash.persistence.AbstractLogstashIndexerDao; import net.sf.json.JSONObject; -public class MemoryDao extends AbstractLogstashIndexerDao -{ +public class MemoryDao extends AbstractLogstashIndexerDao { + final List output = new ArrayList<>(); - public MemoryDao() - { + public MemoryDao() { super(); } @Override - public void push(String data) throws IOException - { + public void push(String data) throws IOException { JSONObject json = JSONObject.fromObject(data); output.add(json); } - public List getOutput() - { + public List getOutput() { return output; } @Override - public String getDescription() - { + public String getDescription() { return "test"; } }