From ad4ca18b85622423a0a6062aa0d92600aa8d75e3 Mon Sep 17 00:00:00 2001 From: "anatoly.ivanov" Date: Mon, 1 Apr 2019 17:01:52 +0300 Subject: [PATCH 01/26] Feature #52059. Merge branch 'rm52059-3.2' into release-3.2 (cherry picked from commit 418eb87bc6917a36f6df10baeb4eb6bca75dd257) Change-Id: Ied60a885b7010f26c9a6d300a26cbf8fedacd2dd --- .../Sailfish-JS-report/src/components/ReportLayout.tsx | 2 +- .../Sailfish-JS-report/src/components/TestCaseCard.tsx | 8 ++++---- FrontEnd/Sailfish-JS-report/src/styles/layout.scss | 4 ++++ FrontEnd/Sailfish-JS-report/src/styles/report.scss | 2 +- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/FrontEnd/Sailfish-JS-report/src/components/ReportLayout.tsx b/FrontEnd/Sailfish-JS-report/src/components/ReportLayout.tsx index f081363a..42bc40a3 100644 --- a/FrontEnd/Sailfish-JS-report/src/components/ReportLayout.tsx +++ b/FrontEnd/Sailfish-JS-report/src/components/ReportLayout.tsx @@ -120,7 +120,7 @@ const ReportLayoutBase = ({ report, onTestCaseSelect }: ReportLayoutProps) => { onTestCaseSelect(metadata.jsonpFileName)}/> + handleClick={metadata => onTestCaseSelect(metadata.jsonpFileName)}/> )) } diff --git a/FrontEnd/Sailfish-JS-report/src/components/TestCaseCard.tsx b/FrontEnd/Sailfish-JS-report/src/components/TestCaseCard.tsx index afe01630..3f36766c 100644 --- a/FrontEnd/Sailfish-JS-report/src/components/TestCaseCard.tsx +++ b/FrontEnd/Sailfish-JS-report/src/components/TestCaseCard.tsx @@ -22,10 +22,10 @@ import '../styles/report.scss'; interface TestCaseCardProps { metadata: ReportMetadata; index: number; - selectHandler: (metadata: ReportMetadata) => any; + handleClick: (metadata: ReportMetadata) => any; } -const TestCaseCard = ({ metadata, selectHandler, index }: TestCaseCardProps) => { +const TestCaseCard = ({ metadata, handleClick, index }: TestCaseCardProps) => { const elapsedTime = getSecondsPeriod(metadata.startTime, metadata.finishTime); @@ -38,12 +38,12 @@ const TestCaseCard = ({ metadata, selectHandler, index }: TestCaseCardProps) =>
{ - // preventing select handling when user just selecting some text on card + // Don't trigger 'click' event when user selects text if (window.getSelection().type == 'Range') { return; } - selectHandler(metadata) + handleClick(metadata) }}>
{index}
diff --git a/FrontEnd/Sailfish-JS-report/src/styles/layout.scss b/FrontEnd/Sailfish-JS-report/src/styles/layout.scss index b37ea24a..aac5cee6 100644 --- a/FrontEnd/Sailfish-JS-report/src/styles/layout.scss +++ b/FrontEnd/Sailfish-JS-report/src/styles/layout.scss @@ -85,6 +85,7 @@ width: 20px; background-image: url(../../resources/icons/checkpoint.svg); background-size: 100%; + background-repeat: no-repeat; } &-title, &-count { @@ -129,6 +130,7 @@ width: 20px; background-image: url(../../resources/icons/rejected-icon.svg); background-size: 100%; + background-repeat: no-repeat; } &-title, &-count { @@ -192,6 +194,7 @@ width: 20px; background-image: url(../../resources/icons/admin-icon.svg); background-size: 100%; + background-repeat: no-repeat; filter: opacity(0.5); &.active { @@ -204,6 +207,7 @@ display: flex; flex-direction: row; align-items: center; + background-repeat: no-repeat; padding: 7px 7px 10px 7px; // disabled diff --git a/FrontEnd/Sailfish-JS-report/src/styles/report.scss b/FrontEnd/Sailfish-JS-report/src/styles/report.scss index b6afbf4b..3e5e483d 100644 --- a/FrontEnd/Sailfish-JS-report/src/styles/report.scss +++ b/FrontEnd/Sailfish-JS-report/src/styles/report.scss @@ -139,7 +139,7 @@ .list { height: 100%; - padding: 0 15px; + padding: 0 5px 0 15px; .item { padding: 3px; From 3289479beefccaab317f4e3f9aac432f8ece0869 Mon Sep 17 00:00:00 2001 From: "ivan.druzhinin" Date: Tue, 2 Apr 2019 16:32:36 +0300 Subject: [PATCH 02/26] [RM] Support #52518. AMLConverterVisitor > corrected namespace for quickfix messages (cherry picked from commit 27bfcacce67f2067c45755da4ecc389ba3e3250c) Change-Id: I9d3c69dfba3f6b84f8edb79fcc51f40871cf86b5 --- .../com/exactpro/sf/aml/visitors/AMLConverterVisitor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java index 70018478..794dc73f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java @@ -27,7 +27,6 @@ import java.util.Map; import java.util.Set; -import com.exactpro.sf.aml.reader.struct.ExecutionMode; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -50,6 +49,7 @@ import com.exactpro.sf.aml.generator.matrix.Value; import com.exactpro.sf.aml.reader.struct.AMLBlock; import com.exactpro.sf.aml.reader.struct.AMLElement; +import com.exactpro.sf.aml.reader.struct.ExecutionMode; import com.exactpro.sf.aml.scriptutil.MessageCount; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.configuration.suri.SailfishURI; @@ -203,7 +203,7 @@ public void visit(AMLElement element) throws AMLException { // hack to support old namespaces for FIX messages if(cellValue.startsWith("quickfix.fix")) { - cellValue = "com.exactpro." + cellValue; + cellValue = "com.exactpro.sf." + cellValue; } if(actionURI == null && element.containsCell(Column.Reference)) { From 551e08f2c690b1b075369dcbd6f0d0aa55016643 Mon Sep 17 00:00:00 2001 From: "ivan.druzhinin" Date: Tue, 2 Apr 2019 14:10:47 +0300 Subject: [PATCH 03/26] [RM] Feature #53824. Add default services to all existing and newly created environments (cherry picked from commit 2f3cbcee2c816f278b638d4e5b7e432aea804be5) Change-Id: Iba9445cbed412023ce11e39297a6b705aa6b5cfc --- .../sf/scriptrunner/IConnectionManager.java | 17 +++++ .../impl/DefaultConnectionManager.java | 62 ++++++++++++++++++- .../services/PluginServiceLoader.java | 20 +----- 3 files changed, 78 insertions(+), 21 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java index 7771f624..07669f9d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java @@ -28,6 +28,23 @@ public interface IConnectionManager extends IDisposable { + /** + * Adds default service. Default service is a service which will be added to all existing and newly created environments. + * Already existing services on environments will not be replaced. + * @param serviceDescription description of a service to add (environment will be ignored) + * @param exceptionListener exception listener + * @return + */ + void addDefaultService(ServiceDescription serviceDescription, IServiceNotifyListener exceptionListener); + + /** + * Removes default service. Services already added to environments will not be removed + * @param serviceName name of a service to remove (without environment) + * @param exceptionListener exception listener + * @return + */ + void removeDefaultService(String serviceName, IServiceNotifyListener exceptionListener); + Future addService(ServiceDescription serviceDescription, IServiceNotifyListener exceptionListener); Future initService(ServiceName serviceName, IServiceNotifyListener exceptionListener); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java index de45ed49..1feecdf9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java @@ -102,10 +102,11 @@ public final class DefaultConnectionManager implements IConnectionManager { private final ReadWriteLock lock; - /** + /** * Operations with this collections should be synchronized */ private final Set usedServices; + private final Map defaultServices; public DefaultConnectionManager( final IServiceFactory staticServiceFactory, @@ -136,7 +137,9 @@ public DefaultConnectionManager( this.usedServices = new HashSet<>(); - ServiceName serviceName = null; + this.defaultServices = new HashMap<>(); + + ServiceName serviceName = null; for (ServiceDescription serviceDescription : this.storage.getServiceDescriptions()) { serviceName = new ServiceName(serviceDescription.getEnvironment(), serviceDescription.getName()); IService service = staticServiceFactory.createService(serviceDescription.getType()); @@ -202,7 +205,54 @@ public void dispose() { } } - @Override + @Override + public void addDefaultService(ServiceDescription serviceDescription, IServiceNotifyListener exceptionListener) { + serviceDescription = serviceDescription.clone(); + String serviceName = serviceDescription.getName(); + + try { + lock.writeLock().lock(); + + if(defaultServices.putIfAbsent(serviceName, serviceDescription) != null) { + throw new StorageException("Default service already exists: " + serviceName); + } + + for(String environment : envStorage.list()) { + if(services.containsKey(new ServiceName(environment, serviceName))) { + continue; + } + + ServiceDescription clonedDescription = serviceDescription.clone(); + clonedDescription.setEnvironment(environment); + + addServiceWithoutNewThread(clonedDescription, exceptionListener); + } + } catch(Exception e) { + defaultServices.remove(serviceName); + exceptionNotify(exceptionListener, e); + throw new ServiceException(e.getMessage(), e); + } finally { + lock.writeLock().unlock(); + } + } + + @Override + public void removeDefaultService(String serviceName, IServiceNotifyListener exceptionListener) { + try { + lock.writeLock().lock(); + + if(defaultServices.remove(serviceName) == null) { + throw new StorageException("Default service does not exist: " + serviceName); + } + } catch(Exception e) { + exceptionNotify(exceptionListener, e); + throw new ServiceException(e.getMessage(), e); + } finally { + lock.writeLock().unlock(); + } + } + + @Override public Future addService(final ServiceDescription serviceDescription, final IServiceNotifyListener notifyListener) { return serviceExecutor.submit(() -> addServiceWithoutNewThread(serviceDescription.clone(), notifyListener)); } @@ -599,6 +649,12 @@ public void run() { envStorage.add(envName); EnvironmentEvent event = new ChangeEnvironmentEvent(envName, "Environment was added", ChangeEnvironmentEvent.Status.ADDED); environmentMonitor.onEvent(event); + + for(ServiceDescription serviceDescription : defaultServices.values()) { + serviceDescription = serviceDescription.clone(); + serviceDescription.setEnvironment(envName); + addServiceWithoutNewThread(serviceDescription, notifyListener); + } } catch (Exception e) { exceptionNotify(notifyListener, e); throw new StorageException(e.getMessage(), e); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/services/PluginServiceLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/services/PluginServiceLoader.java index bfe58e98..8d70b106 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/services/PluginServiceLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/services/PluginServiceLoader.java @@ -1,7 +1,6 @@ package com.exactpro.sf.scriptrunner.services; import static org.apache.commons.io.FilenameUtils.getExtension; -import static org.apache.commons.lang3.ArrayUtils.contains; import java.io.File; import java.io.FileInputStream; @@ -12,7 +11,6 @@ import java.util.List; import java.util.Set; -import com.exactpro.sf.common.services.ServiceName; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.scriptrunner.IConnectionManager; import com.exactpro.sf.services.ServiceDescription; @@ -59,25 +57,11 @@ public void load(IConnectionManager connectionManager, ServiceMarshalManager mar throw new EPSCommonException("Failed to load service descriptions. Errors:" + System.lineSeparator() + String.join(System.lineSeparator(), errors)); } - List environments = connectionManager.getEnvironmentList(); - for(ServiceDescription description : descriptions) { - ServiceName serviceName = description.getServiceName(); - - if(contains(connectionManager.getServiceNames(), serviceName)) { - continue; - } - - String environment = serviceName.getEnvironment(); - - if(!serviceName.isDefault() && !environments.contains(environment)) { - connectionManager.addEnvironment(environment, null); - } - try { - connectionManager.addService(description, null).get(); + connectionManager.addDefaultService(description, null); } catch(Throwable t) { - throw new EPSCommonException("Failed to add service: " + description.getServiceName(), t); + throw new EPSCommonException("Failed to add default service: " + description.getName(), t); } } } From 0b6cbb5f84aa1534ed2bee7f9da5a04c0d90b2cc Mon Sep 17 00:00:00 2001 From: "oleg.legkov" Date: Fri, 15 Mar 2019 11:39:19 +0300 Subject: [PATCH 04/26] [RM] Feature #52483. [Feature] Add feature, which can get and format current date/time to target timezone (cherry picked from commit 4d599b87c670f6f9c25ce5c84e0ba49d95d2db07) Change-Id: I38d9c61bcea703b52a01394f174b1f277a6c1634 --- .../com/exactpro/sf/util/DateTimeUtility.java | 5 + .../com/exactpro/sf/actions/DateUtil.java | 195 +++++++++- .../com/exactpro/sf/actions/TestDateUtil.java | 347 ++++++++++++++++++ 3 files changed, 542 insertions(+), 5 deletions(-) diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java index 2590f080..92129298 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java @@ -37,6 +37,11 @@ public class DateTimeUtility { public static final LocalTime MIN_TIME = LocalTime.MIN; public static final LocalDateTime MIN_DATE_TIME = LocalDateTime.of(MIN_DATE, MIN_TIME); + public static ZonedDateTime toZonedDateTime(long millisecond) { + Instant instant = Instant.ofEpochMilli(millisecond); + return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); + } + public static ZonedDateTime toZonedDateTime(TemporalAccessor temporalAccessor) { int year = getOrDefault(temporalAccessor, ChronoField.YEAR, MIN_DATE.getYear()); int month = getOrDefault(temporalAccessor, ChronoField.MONTH_OF_YEAR, 1); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java index 9c78c8c4..9a64a5c8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java @@ -16,6 +16,8 @@ package com.exactpro.sf.actions; +import static com.exactpro.sf.util.DateTimeUtility.toZonedDateTime; + import java.util.List; import java.util.Objects; @@ -184,6 +186,12 @@ public LocalTime getTime(String modifyPattern) { return toTime(getDateTime(modifyPattern)); } + @Description("Returns current time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{getTimeByZoneId(modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalTime getTimeByZoneId(String modifyPattern, String timeZoneId) { + return toTime(getDateTimeByZoneId(modifyPattern, timeZoneId)); + } + @Description("Returns current date in UTC time zone
Example: #{getDate()}") @UtilityMethod public LocalDate getDate() { @@ -196,6 +204,12 @@ public LocalDate getDate(String modifyPattern) { return toDate(getDateTime(modifyPattern)); } + @Description("Returns current date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{getDateByZoneId(modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDate getDateByZoneId(String modifyPattern, String timeZoneId) { + return toDate(getDateTimeByZoneId(modifyPattern, timeZoneId)); + } + @Description("Returns current date time in UTC time zone
Example: #{getDateTime()}") @UtilityMethod public final LocalDateTime getDateTime() { @@ -216,15 +230,39 @@ public final LocalDateTime getDateTime(String modifyPattern) { @UtilityMethod public final LocalDateTime getDateTime(String modifyPattern, boolean skipWeekends) { LocalDateTime nowDate = DateTimeUtility.nowLocalDateTime(); - LocalDateTime modifiedDate = modifyTemporal(nowDate, modifyPattern); + return modifyDateTime(nowDate, modifyPattern, skipWeekends); + } + + @Description("Returns current date time in UTC time zone modified by pattern after applying time zone offset (DST aware).
" + + "If modified date time is on weekend and skipWeekends is true then the next working day in direction of modification will be returned" + + MODIFY_HELP + + "Example: #{getDateTimeByZoneId(modifyPattern, skipWeekends, timeZoneId)}" + ) + @UtilityMethod + public final LocalDateTime getDateTimeByZoneId(String modifyPattern, boolean skipWeekends, String timeZoneId) { + ZoneId zoneId = ZoneId.of(timeZoneId); + LocalDateTime nowDate = LocalDateTime.now(zoneId); + nowDate = modifyDateTime(nowDate, modifyPattern, skipWeekends); + return ZonedDateTime.of(nowDate, zoneId).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); + } + + @Description("Returns provided datetime in UTC time zone modified by pattern
" + + "If modified date time is on weekend and skipWeekends is true then the next working day in direction of modification will be returned" + + MODIFY_HELP + + "Example: #{modifyDateTime(dateTime, modifyPattern, skipWeekends)}" + ) + @UtilityMethod + public final LocalDateTime modifyDateTime(LocalDateTime dateTime, String modifyPattern, boolean skipWeekends){ + LocalDateTime modifiedDate = modifyTemporal(dateTime, modifyPattern); + if (skipWeekends) { DayOfWeek dayOfWeek = modifiedDate.getDayOfWeek(); - long currentMillis = DateTimeUtility.getMillisecond(nowDate); + long currentMillis = DateTimeUtility.getMillisecond(dateTime); long modifiedMillis = DateTimeUtility.getMillisecond(modifiedDate); - if (DayOfWeek.SATURDAY.equals(dayOfWeek)) { + if(DayOfWeek.SATURDAY.equals(dayOfWeek)) { int shift = modifiedMillis - currentMillis >= 0 ? 2 : -1; - return modifiedDate.plusDays(shift); - } else if (DayOfWeek.SUNDAY.equals(dayOfWeek)) { + return modifiedDate.plusDays(shift); + } else if(DayOfWeek.SUNDAY.equals(dayOfWeek)) { int shift = modifiedMillis - currentMillis >= 0 ? 1 : -2; return modifiedDate.plusDays(shift); } @@ -276,6 +314,15 @@ public LocalTime toTime(long epochMillis, String modifyPattern) { return toTime(toDateTime(epochMillis, modifyPattern)); } + @Description("Converts epoch milliseconds to time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toTimeByZoneId(epochMillis, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalTime toTimeByZoneId(long epochMillis, String modifyPattern, String timeZoneId) { + ZonedDateTime time = DateTimeUtility.toZonedDateTime(epochMillis).withZoneSameInstant(ZoneId.of(timeZoneId)); + + time = modifyTemporal(time, modifyPattern); + return toTime(DateTimeUtility.toLocalDateTime(time)); + } + @Description("Converts string using format pattern to time in UTC time zone." + FORMAT_HELP + "Example: #{toTime(source, formatPattern)}") @UtilityMethod public LocalTime toTime(String source, String formatPattern) { @@ -288,6 +335,13 @@ public LocalTime toTime(String source, String formatPattern, String modifyPatter return toTime(toDateTime(source, formatPattern, modifyPattern)); } + @Description("Converts string using format pattern to time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalTime toTimeByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(source, formatPattern); + return toTimeByZoneId(time, modifyPattern, timeZoneId); + } + @Description("Converts date time to time in UTC time zone
Example: #{toTime(dateTime)}") @UtilityMethod public LocalTime toTime(LocalDateTime dateTime) { @@ -300,6 +354,12 @@ public LocalTime toTime(LocalDateTime dateTime, String modifyPattern) { return toTime(modifyDateTime(dateTime, modifyPattern)); } + @Description("Converts date time to time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalTime toTimeByZoneId(LocalDateTime dateTime, String modifyPattern, String timeZoneId) { + return toTime(modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)); + } + @Description("Converts epoch milliseconds to date in UTC time zone
Example: #{toDate(epochMillis)}") @UtilityMethod public LocalDate toDate(long epochMillis) { @@ -312,6 +372,13 @@ public LocalDate toDate(long epochMillis, String modifyPattern) { return toDate(toDateTime(epochMillis, modifyPattern)); } + @Description("Converts epoch milliseconds to date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateByZoneId(epochMillis, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDate toDateByZoneId(long epochMillis, String modifyPattern, String timeZoneId) { + return toDate(toDateTimeByZoneId(epochMillis, modifyPattern, timeZoneId)); + } + + @Description("Converts string using format pattern to date in UTC time zone." + FORMAT_HELP + "Example: #{toDate(source, formatPattern)}") @UtilityMethod public LocalDate toDate(String source, String formatPattern) { @@ -324,6 +391,13 @@ public LocalDate toDate(String source, String formatPattern, String modifyPatter return toDate(toDateTime(source, formatPattern, modifyPattern)); } + @Description("Converts string using format pattern to date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDate toDateByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(source, formatPattern); + return toDateByZoneId(time, modifyPattern, timeZoneId); + } + @Description("Converts date time to date in UTC time zone
Example: #{toDate(dateTime)}") @UtilityMethod public LocalDate toDate(LocalDateTime dateTime) { @@ -336,6 +410,12 @@ public LocalDate toDate(LocalDateTime dateTime, String modifyPattern) { return toDate(modifyDateTime(dateTime, modifyPattern)); } + @Description("Converts date time to date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateByZoneId(dateTime, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDate toDateByZoneId(LocalDateTime dateTime, String modifyPattern, String timeZoneId) { + return toDate(modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)); + } + @Description("Converts epoch milliseconds to date time in UTC time zone
Example: #{toDateTime(epochMillis)}") @UtilityMethod public LocalDateTime toDateTime(long epochMillis) { @@ -348,6 +428,14 @@ public LocalDateTime toDateTime(long epochMillis, String modifyPattern) { return modifyDateTime(toDateTime(epochMillis), modifyPattern); } + @Description("Converts epoch milliseconds to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(epochMillis, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime toDateTimeByZoneId(long epochMillis, String modifyPattern, String timeZoneId) { + ZonedDateTime time = toZonedDateTime(epochMillis).withZoneSameInstant(ZoneId.of(timeZoneId)); + time = modifyTemporal(time, modifyPattern); + return DateTimeUtility.toLocalDateTime(time); + } + @Description("Converts string using automatic format pattern detection to date time in UTC time zone
" + "One of the following date/time pattern is defined:" + "
" @@ -434,6 +522,13 @@ public LocalDateTime toDateTime(String source, String formatPattern, String modi return modifyDateTime(toDateTime(source, formatPattern), modifyPattern); } + @Description("Converts string using format pattern to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime toDateTimeByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(source, formatPattern); + return modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); + } + @Description("Converts time to date time in UTC time zone
Example: #{toDateTime(time)}") @UtilityMethod public LocalDateTime toDateTime(LocalTime time) { @@ -446,6 +541,12 @@ public LocalDateTime toDateTime(LocalTime time, String modifyPattern) { return modifyDateTime(toDateTime(time), modifyPattern); } + @Description("Converts time to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(time, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime toDateTimeByZoneId(LocalTime time, String modifyPattern, String timeZoneId) { + return modifyDateTimeByZoneId(toDateTime(time), modifyPattern, timeZoneId); + } + @Description("Converts date to date time in UTC time zone
Example: #{toDateTime(date)}") @UtilityMethod public LocalDateTime toDateTime(LocalDate date) { @@ -458,6 +559,13 @@ public LocalDateTime toDateTime(LocalDate date, String modifyPattern) { return modifyDateTime(toDateTime(date), modifyPattern); } + @Description("Converts date to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(date, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime toDateTimeByZoneId(LocalDate date, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(date); + return modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); + } + @Description("Formats time in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatTime(time, formatPattern)}") @UtilityMethod public String formatTime(LocalTime time, String formatPattern) { @@ -470,6 +578,14 @@ public String formatTime(LocalTime time, String formatPattern, String modifyPatt return formatDateTime(toDateTime(time), formatPattern, modifyPattern); } + @Description("Formats time in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatTimeByZoneId(time, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public String formatTimeByZoneId(LocalTime time, String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime localDateTime = toDateTime(time); + localDateTime = modifyDateTimeByZoneId(localDateTime, modifyPattern, timeZoneId); + return formatDateTime(localDateTime, formatPattern); + } + @Description("Formats date in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatDate(date, formatPattern)}") @UtilityMethod public String formatDate(LocalDate date, String formatPattern) { @@ -482,6 +598,14 @@ public String formatDate(LocalDate date, String formatPattern, String modifyPatt return formatDateTime(toDateTime(date), formatPattern, modifyPattern); } + @Description("Formats date in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateByZoneId(date, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public String formatDateByZoneId(LocalDate date, String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(date); + time = modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); + return formatDateTime(time, formatPattern); + } + @Description("Formats date time in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatDateTime(dateTime, formatPattern)}") @UtilityMethod public String formatDateTime(LocalDateTime dateTime, String formatPattern) { @@ -494,6 +618,13 @@ public String formatDateTime(LocalDateTime dateTime, String formatPattern, Strin return formatTemporal(modifyDateTime(dateTime, modifyPattern), formatPattern); } + @Description("Formats date time in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTimeByZoneId(dateTime, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public String formatDateTimeByZoneId(LocalDateTime dateTime, String formatPattern, String modifyPattern, String timeZoneId) { + dateTime = modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId); + return formatDateTime(dateTime, formatPattern); + } + @Description("Merges date and time into date time in UTC time zone
Example: #{mergeDateTime(date, time)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDate date, LocalTime time) { @@ -506,6 +637,13 @@ public LocalDateTime mergeDateTime(LocalDate date, LocalTime time, String modify return modifyDateTime(mergeDateTime(date, time), modifyPattern); } + @Description("Merges date and time into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(date, time, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime mergeDateTimeByZoneId(LocalDate date, LocalTime time, String modifyPattern, String timeZoneId) { + LocalDateTime localDateTime = mergeDateTime(date, time); + return modifyDateTimeByZoneId(localDateTime, modifyPattern, timeZoneId); + } + @Description("Merges date and date time (only time is used) into date time in UTC time zone
Example: #{mergeDateTime(date, dateTime)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDate date, LocalDateTime dateTime) { @@ -518,6 +656,12 @@ public LocalDateTime mergeDateTime(LocalDate date, LocalDateTime dateTime, Strin return mergeDateTime(date, toTime(dateTime), modifyPattern); } + @Description("Merges date and date time (only time is used) into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(date, dateTime, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime mergeDateTimeByZoneId(LocalDate date, LocalDateTime dateTime, String modifyPattern, String timeZoneId) { + return mergeDateTimeByZoneId(date, dateTime.toLocalTime(), modifyPattern, timeZoneId); + } + @Description("Merges date time (only date is used) and time into date time in UTC time zone
Example: #{mergeDateTime(dateTime, time)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDateTime dateTime, LocalTime time) { @@ -530,6 +674,12 @@ public LocalDateTime mergeDateTime(LocalDateTime dateTime, LocalTime time, Strin return mergeDateTime(toDate(dateTime), time, modifyPattern); } + @Description("Merges date time (only date is used) and time into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(dateTime, time, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime mergeDateTimeByZoneId(LocalDateTime dateTime, LocalTime time, String modifyPattern, String timeZoneId) { + return mergeDateTimeByZoneId(dateTime.toLocalDate(), time, modifyPattern, timeZoneId); + } + @Description("Merges date time (only date is used) and date time (only time is used) into date time in UTC time zone
Example: #{mergeDateTime(firstDateTime, secondDateTime)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDateTime firstDateTime, LocalDateTime secondDateTime) { @@ -542,6 +692,12 @@ public LocalDateTime mergeDateTime(LocalDateTime firstDateTime, LocalDateTime se return mergeDateTime(toDate(firstDateTime), toTime(secondDateTime), modifyPattern); } + @Description("Merges date time (only date is used) and date time (only time is used) into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(firstDateTime, secondDateTime, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDateTime mergeDateTimeByZoneId(LocalDateTime firstDateTime, LocalDateTime secondDateTime, String modifyPattern, String timeZoneId) { + return mergeDateTimeByZoneId(firstDateTime.toLocalDate(), secondDateTime.toLocalTime(), modifyPattern, timeZoneId); + } + @Description("Formats current date time in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatDateTime(formatPattern)}") @UtilityMethod public String formatDateTime(String formatPattern) { @@ -554,24 +710,53 @@ public String formatDateTime(String formatPattern, String modifyPattern) { return formatDateTime(getDateTime(), formatPattern, modifyPattern); } + @Description("Formats current date time in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTimeByZoneId(formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public String formatDateTimeByZoneId(String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime time = getDateTime(); + time = modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); + return formatDateTime(time, formatPattern); + } + @Description("Modifies date time string using format and modify patterns." + FORMAT_HELP + MODIFY_HELP + "Example; #{modifyDateTime(source, formatPattern, modifyPattern)}") @UtilityMethod public String modifyDateTime(String source, String formatPattern, String modifyPattern) { return formatDateTime(toDateTime(source, formatPattern, modifyPattern), formatPattern); } + @Description("Modifies date time string using format and modify patterns after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example; #{modifyDateTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @UtilityMethod + public String modifyDateTimeByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(source); + time = modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); + return formatDateTime(time, formatPattern); + } + @Description("Modifies time in UTC time zone by pattern." + MODIFY_HELP + "Example: #{modifyTime(time, modifyPattern)}") @UtilityMethod public LocalTime modifyTime(LocalTime time, String modifyPattern) { return toTime(toDateTime(time, modifyPattern)); } + @Description("Modifies time in UTC time zone by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyTimeByZoneId(time, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalTime modifyTimeByZoneId(LocalTime time, String modifyPattern, String timeZoneId) { + return toTime(modifyDateTimeByZoneId(toDateTime(time), modifyPattern, timeZoneId)); + } + @Description("Modifies date in UTC time zone by pattern." + MODIFY_HELP + "Example: #{modifyDate(date, modifyPattern)}") @UtilityMethod public LocalDate modifyDate(LocalDate date, String modifyPattern) { return toDate(toDateTime(date, modifyPattern)); } + @Description("Modifies date in UTC time zone by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyDateByZoneId(date, modifyPattern, timeZoneId)}") + @UtilityMethod + public LocalDate modifyDateByZoneId(LocalDate date, String modifyPattern, String timeZoneId) { + LocalDateTime time = toDateTime(date); + return toDate(modifyDateTimeByZoneId(time, modifyPattern, timeZoneId)); + } + @Description("Modifies date time in UTC time zone by pattern." + MODIFY_HELP + "Example: #{modifyDateTime(dateTime, modifyPattern)}") @UtilityMethod public LocalDateTime modifyDateTime(LocalDateTime dateTime, String modifyPattern) { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java index d62c6e96..93fe2bb2 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java @@ -50,6 +50,353 @@ public void clean() { this.dateUtil = new DateUtil(); } + @Test + public void testGetTimeByZoneId(){ + LocalTime calculatedTime = dateUtil.getTimeByZoneId("h=12:m=30:s=10:ns=123456789", "+03:01"); + LocalTime awaitingTime = LocalTime.of(9, 29, 10, 123456789); + Assert.assertEquals(awaitingTime, calculatedTime); + } + + @Test + public void testGetDateByZoneId(){ + LocalDate calculatedDate = dateUtil.getDateByZoneId("Y=2019:M=3:D=13:h+0:m+0:s+0:ns+0", "+03:01"); + LocalDate awaitingDate = LocalDate.of(2019, 3, 13); + Assert.assertEquals(awaitingDate, calculatedDate); + } + + @Test + public void testModifyDateTime(){ + LocalDateTime awaitingResult = LocalDateTime.of(2019, 3, 25, 8, 59, 0, 0); + LocalDateTime awaitingResult2 = LocalDateTime.of(2019, 3, 23, 8, 59, 0, 0); + LocalDateTime nowDate = LocalDateTime.of(2019, 3, 18, 12, 0, 0, 0); + LocalDateTime result = ZonedDateTime.of(nowDate, ZoneId.of("+03:01")).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); + LocalDateTime result2 = ZonedDateTime.of(nowDate, ZoneId.of("+03:01")).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); + result = dateUtil.modifyDateTime(result, "D+5", true); + result2 = dateUtil.modifyDateTime(result2, "D+5", false); + + Assert.assertEquals(awaitingResult, result); + Assert.assertEquals(awaitingResult2, result2); + } + + @Test + public void testToTimeByZoneId(){ + long time1 = 1552313123000L; //2019/03/11 14:05:23.000 + long time2 = 1554041123000L; //2019/03/31 14:05:23.000 + long time3 = 1572098723000L; //2019/10/26 14:05:23.000 + long time4 = 1572185123000L; //2019/10/27 14:05:23.000 + + LocalTime awaitingTime = LocalTime.of(14, 5, 23); + + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId(time1,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId(time2,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId(time3,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId(time4,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + } + + @Test + public void testToTimeByZoneId2(){ + LocalTime awaitingTime = LocalTime.of(14, 5, 23); + + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId("20190311-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId("20190331-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId("20191026-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime.equals(dateUtil.toTimeByZoneId("20191027-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + + } + + @Test + public void testToTimeByZoneId3(){ + LocalTime awaitingTime = LocalTime.of(14, 5, 23, 0); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertEquals(awaitingTime, dateUtil.toTimeByZoneId(localDateTime1, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime, dateUtil.toTimeByZoneId(localDateTime2, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime, dateUtil.toTimeByZoneId(localDateTime3, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime, dateUtil.toTimeByZoneId(localDateTime4, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + } + + @Test + public void testToDateByZoneId(){ + long time1 = 1552313123000L; //2019/03/11 14:05:23.000 + long time2 = 1554041123000L; //2019/03/31 14:05:23.000 + long time3 = 1572098723000L; //2019/10/26 14:05:23.000 + long time4 = 1572185123000L; //2019/10/27 14:05:23.000 + + LocalDate awaitingTime1 = LocalDate.of(2019, 3, 11); + LocalDate awaitingTime2 = LocalDate.of(2019, 3, 31); + LocalDate awaitingTime3 = LocalDate.of(2019, 10, 26); + LocalDate awaitingTime4 = LocalDate.of(2019, 10, 27); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.toDateByZoneId(time1,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.toDateByZoneId(time2,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.toDateByZoneId(time3,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.toDateByZoneId(time4,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + } + + @Test + public void testToDateByZoneId2(){ + LocalDate awaitingTime1 = LocalDate.of(2019, 3, 11); + LocalDate awaitingTime2 = LocalDate.of(2019, 3, 31); + LocalDate awaitingTime3 = LocalDate.of(2019, 10, 26); + LocalDate awaitingTime4 = LocalDate.of(2019, 10, 27); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.toDateByZoneId("20190311-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.toDateByZoneId("20190331-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.toDateByZoneId("20191026-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.toDateByZoneId("20191027-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + } + + @Test + public void testToDateByZoneId3(){ + LocalDate awaitingTime1 = LocalDate.of(2019, 3, 11); + LocalDate awaitingTime2 = LocalDate.of(2019, 3, 31); + LocalDate awaitingTime3 = LocalDate.of(2019, 10, 26); + LocalDate awaitingTime4 = LocalDate.of(2019, 10, 27); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertEquals(awaitingTime1, dateUtil.toDateByZoneId(localDateTime1, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime2, dateUtil.toDateByZoneId(localDateTime2, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime3, dateUtil.toDateByZoneId(localDateTime3, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime4, dateUtil.toDateByZoneId(localDateTime4, "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + } + + @Test + public void testToDateTimeByZoneId(){ + long time1 = 1552313123000L; //2019/03/11 14:05:23.000 + long time2 = 1554041123000L; //2019/03/31 14:05:23.000 + long time3 = 1572098723000L; //2019/10/26 14:05:23.000 + long time4 = 1572185123000L; //2019/10/27 14:05:23.000 + + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.toDateTimeByZoneId(time1,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.toDateTimeByZoneId(time2,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.toDateTimeByZoneId(time3,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.toDateTimeByZoneId(time4,"Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + } + + @Test + public void testToDateTimeByZoneId2(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.toDateTimeByZoneId("20190311-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.toDateTimeByZoneId("20190331-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.toDateTimeByZoneId("20191026-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.toDateTimeByZoneId("20191027-14:05:23.507","yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns=0", "Europe/London"))); + } + + @Test + public void testToDateTimeByZoneId3(){ + LocalDateTime awaitingTime = LocalDateTime.of(1970, 1, 1, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertEquals(awaitingTime, dateUtil.toDateTimeByZoneId(localDateTime1.toLocalTime(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime, dateUtil.toDateTimeByZoneId(localDateTime2.toLocalTime(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime, dateUtil.toDateTimeByZoneId(localDateTime3.toLocalTime(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime, dateUtil.toDateTimeByZoneId(localDateTime4.toLocalTime(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + } + + @Test + public void testToDateTimeByZoneId4(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 0, 0, 0); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 4, 1, 0, 0, 0); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10,26, 0, 0, 0); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10,28, 0, 0, 0); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3,11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 4,1, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10,26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10,28, 14, 5, 23, 0); + + Assert.assertEquals(awaitingTime1, dateUtil.toDateTimeByZoneId(localDateTime1.toLocalDate(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime2, dateUtil.toDateTimeByZoneId(localDateTime2.toLocalDate(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime3, dateUtil.toDateTimeByZoneId(localDateTime3.toLocalDate(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + Assert.assertEquals(awaitingTime4, dateUtil.toDateTimeByZoneId(localDateTime4.toLocalDate(), "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London")); + } + + @Test + public void testFormatTimeByZoneId(){ + String resultTime = "19700101-14:05:23.000"; + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3,11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 4,1, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10,26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10,28, 14, 5, 23, 0); + + Assert.assertTrue(resultTime.equals(dateUtil.formatTimeByZoneId(localDateTime1.toLocalTime(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(resultTime.equals(dateUtil.formatTimeByZoneId(localDateTime2.toLocalTime(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(resultTime.equals(dateUtil.formatTimeByZoneId(localDateTime3.toLocalTime(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(resultTime.equals(dateUtil.formatTimeByZoneId(localDateTime4.toLocalTime(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + } + + @Test + public void testFormatDateByZoneId(){ + String resultTime1 = "20190311-00:00:00.000"; + String resultTime2 = "20190401-00:00:00.000"; + String resultTime3 = "20191026-00:00:00.000"; + String resultTime4 = "20191028-00:00:00.000"; + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3,11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 4,1, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10,26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10,28, 14, 5, 23, 0); + + Assert.assertTrue(resultTime1.equals(dateUtil.formatDateByZoneId(localDateTime1.toLocalDate(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(resultTime2.equals(dateUtil.formatDateByZoneId(localDateTime2.toLocalDate(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(resultTime3.equals(dateUtil.formatDateByZoneId(localDateTime3.toLocalDate(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + Assert.assertTrue(resultTime4.equals(dateUtil.formatDateByZoneId(localDateTime4.toLocalDate(), "yyyyMMdd-HH:mm:ss.SSS", "Y+0:M+0:D+0:h+0:m+0:s+0:ns+0", "Europe/London"))); + } + + @Test + public void testFormatDateTimeByZoneId(){ + LocalDateTime localDateTime1 = LocalDateTime.of(2019,3, 11, 14, 5, 23, 0); // before summer time start | 2019-03-11T14:05:23 2019-03-11T14:05:23Z[Europe/London] 2019-03-11T14:05:23+03:00[Europe/Moscow] + LocalDateTime localDateTime2 = LocalDateTime.of(2019,3, 31, 14, 5, 23, 0); // start of summer time | 2019-03-31T14:05:23 2019-03-31T14:05:23+01:00[Europe/London] 2019-03-31T14:05:23+03:00[Europe/Moscow] + LocalDateTime localDateTime3 = LocalDateTime.of(2019,10, 26, 14, 5, 23, 0); // before summer time end | 2019-10-26T14:05:23 2019-10-26T14:05:23+01:00[Europe/London] 2019-10-26T14:05:23+03:00[Europe/Moscow] + LocalDateTime localDateTime4 = LocalDateTime.of(2019,10, 27, 14, 5, 23, 0); // end of summer time | 2019-10-27T14:05:23 2019-10-27T14:05:23Z[Europe/London] 2019-10-27T14:05:23+03:00[Europe/Moscow] + + Assert.assertEquals("20190311-14:05:23.000", dateUtil.formatDateTimeByZoneId(localDateTime1, "yyyyMMdd-HH:mm:ss.SSS", "h+0", "Europe/London")); + Assert.assertEquals("20190331-14:05:23.000", dateUtil.formatDateTimeByZoneId(localDateTime2, "yyyyMMdd-HH:mm:ss.SSS", "h+0", "Europe/London")); + Assert.assertEquals("20191026-14:05:23.000", dateUtil.formatDateTimeByZoneId(localDateTime3, "yyyyMMdd-HH:mm:ss.SSS", "h+0", "Europe/London")); + Assert.assertEquals("20191027-14:05:23.000", dateUtil.formatDateTimeByZoneId(localDateTime4, "yyyyMMdd-HH:mm:ss.SSS", "h+0", "Europe/London")); + } + + @Test + public void testMergeDateTimeByZoneId(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.mergeDateTimeByZoneId(localDateTime1.toLocalDate(), localDateTime1.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.mergeDateTimeByZoneId(localDateTime2.toLocalDate(), localDateTime2.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.mergeDateTimeByZoneId(localDateTime3.toLocalDate(), localDateTime3.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.mergeDateTimeByZoneId(localDateTime4.toLocalDate(), localDateTime4.toLocalTime(), "h+0", "Europe/London"))); + } + + @Test + public void testMergeDateTimeByZoneId2(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.mergeDateTimeByZoneId(localDateTime1.toLocalDate(), localDateTime1, "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.mergeDateTimeByZoneId(localDateTime2.toLocalDate(), localDateTime2, "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.mergeDateTimeByZoneId(localDateTime3.toLocalDate(), localDateTime3, "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.mergeDateTimeByZoneId(localDateTime4.toLocalDate(), localDateTime4, "h+0", "Europe/London"))); + } + + @Test + public void testMergeDateTimeByZoneId3(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.mergeDateTimeByZoneId(localDateTime1, localDateTime1.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.mergeDateTimeByZoneId(localDateTime2, localDateTime2.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.mergeDateTimeByZoneId(localDateTime3, localDateTime3.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.mergeDateTimeByZoneId(localDateTime4, localDateTime4.toLocalTime(), "h+0", "Europe/London"))); + } + + @Test + public void testMergeDateTimeByZoneId4(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertTrue(awaitingTime1.equals(dateUtil.mergeDateTimeByZoneId(localDateTime1, localDateTime1, "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.equals(dateUtil.mergeDateTimeByZoneId(localDateTime2, localDateTime2, "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.equals(dateUtil.mergeDateTimeByZoneId(localDateTime3, localDateTime3, "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.equals(dateUtil.mergeDateTimeByZoneId(localDateTime4, localDateTime4, "h+0", "Europe/London"))); + } + + @Test + public void testFormatDateTimeByZoneId2(){ + String resultTime = "20190314-09:51:44.000"; + Assert.assertTrue(resultTime.equals(dateUtil.formatDateTimeByZoneId("yyyyMMdd-HH:mm:ss.SSS", "D=14:h=9:m=51:s=44:ms=0", "Europe/London"))); + } + + @Test + public void testModifyDateTimeByZoneId(){ + Assert.assertTrue("20190311-14:05:23".equals(dateUtil.modifyDateTimeByZoneId("2019-03-11 14:05:23.000", "yyyyMMdd-HH:mm:ss", "h+0", "Europe/London"))); + Assert.assertTrue("20190331-14:05:23".equals(dateUtil.modifyDateTimeByZoneId("2019-03-31 14:05:23.000", "yyyyMMdd-HH:mm:ss", "h+0", "Europe/London"))); + Assert.assertTrue("20191026-14:05:23".equals(dateUtil.modifyDateTimeByZoneId("2019-10-26 14:05:23.000", "yyyyMMdd-HH:mm:ss", "h+0", "Europe/London"))); + Assert.assertTrue("20191027-14:05:23".equals(dateUtil.modifyDateTimeByZoneId("2019-10-27 14:05:23.000", "yyyyMMdd-HH:mm:ss", "h+0", "Europe/London"))); + } + + @Test + public void testModifyTimeByZoneId(){ + LocalDateTime awaitingTime = LocalDateTime.of(1970, 1, 1, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertTrue(awaitingTime.toLocalTime().equals(dateUtil.modifyTimeByZoneId(localDateTime1.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime.toLocalTime().equals(dateUtil.modifyTimeByZoneId(localDateTime2.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime.toLocalTime().equals(dateUtil.modifyTimeByZoneId(localDateTime3.toLocalTime(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime.toLocalTime().equals(dateUtil.modifyTimeByZoneId(localDateTime4.toLocalTime(), "h+0", "Europe/London"))); + } + + @Test + public void testModifyDateByZoneId(){ + LocalDateTime awaitingTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23); + LocalDateTime awaitingTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23); + LocalDateTime awaitingTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23); + LocalDateTime awaitingTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23); + + LocalDateTime localDateTime1 = LocalDateTime.of(2019, 3, 11, 14, 5, 23, 0); + LocalDateTime localDateTime2 = LocalDateTime.of(2019, 3, 31, 14, 5, 23, 0); + LocalDateTime localDateTime3 = LocalDateTime.of(2019, 10, 26, 14, 5, 23, 0); + LocalDateTime localDateTime4 = LocalDateTime.of(2019, 10, 27, 14, 5, 23, 0); + + Assert.assertTrue(awaitingTime1.toLocalDate().equals(dateUtil.modifyDateByZoneId(localDateTime1.toLocalDate(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime2.toLocalDate().equals(dateUtil.modifyDateByZoneId(localDateTime2.toLocalDate(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime3.toLocalDate().equals(dateUtil.modifyDateByZoneId(localDateTime3.toLocalDate(), "h+0", "Europe/London"))); + Assert.assertTrue(awaitingTime4.toLocalDate().equals(dateUtil.modifyDateByZoneId(localDateTime4.toLocalDate(), "h+0", "Europe/London"))); + } + @Test public void dateDiffTest() { From 197bf35d1d8e070ca70c09079e0b584ab6b102e0 Mon Sep 17 00:00:00 2001 From: "oleg.legkov" Date: Tue, 26 Mar 2019 13:00:50 +0300 Subject: [PATCH 05/26] [RMA] Support #44867. Documentation > DateUtil (cherry picked from commit aa742ba60a7fb8f2cad82dfefd0791b9c6ba6a61) Change-Id: Iac637e918296912003c721942a504e000e6e06bb --- .../com/exactpro/sf/actions/DateUtil.java | 160 +++++++++--------- 1 file changed, 80 insertions(+), 80 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java index 9a64a5c8..4a0c200d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java @@ -174,55 +174,55 @@ public class DateUtil extends AbstractCaller { "The maximum supported range is from +18:00 to -18:00 inclusive.

" + "For example, +03:30
"; - @Description("Returns current time in UTC time zone
Example: #{getTime()}") + @Description("Returns the current time in the UTC time zone
Example: #{getTime()}") @UtilityMethod public LocalTime getTime() { return DateTimeUtility.nowLocalTime(); } - @Description("Returns current time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{getTime(modifyPattern)}") + @Description("Returns the current time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{getTime(modifyPattern)}") @UtilityMethod public LocalTime getTime(String modifyPattern) { return toTime(getDateTime(modifyPattern)); } - @Description("Returns current time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{getTimeByZoneId(modifyPattern, timeZoneId)}") + @Description("Returns the current time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{getTimeByZoneId(modifyPattern, timeZoneId)}") @UtilityMethod public LocalTime getTimeByZoneId(String modifyPattern, String timeZoneId) { return toTime(getDateTimeByZoneId(modifyPattern, timeZoneId)); } - @Description("Returns current date in UTC time zone
Example: #{getDate()}") + @Description("Returns the current date in the UTC time zone
Example: #{getDate()}") @UtilityMethod public LocalDate getDate() { return DateTimeUtility.nowLocalDate(); } - @Description("Returns current date in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{getDate(modifyPattern)}") + @Description("Returns the current date in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{getDate(modifyPattern)}") @UtilityMethod public LocalDate getDate(String modifyPattern) { return toDate(getDateTime(modifyPattern)); } - @Description("Returns current date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{getDateByZoneId(modifyPattern, timeZoneId)}") + @Description("Returns the current date in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{getDateByZoneId(modifyPattern, timeZoneId)}") @UtilityMethod public LocalDate getDateByZoneId(String modifyPattern, String timeZoneId) { return toDate(getDateTimeByZoneId(modifyPattern, timeZoneId)); } - @Description("Returns current date time in UTC time zone
Example: #{getDateTime()}") + @Description("Returns the current date/time in the UTC time zone
Example: #{getDateTime()}") @UtilityMethod public final LocalDateTime getDateTime() { return DateTimeUtility.nowLocalDateTime(); } - @Description("Returns current date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{getDateTime(modifyPattern)}") + @Description("Returns the current date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{getDateTime(modifyPattern)}") @UtilityMethod public final LocalDateTime getDateTime(String modifyPattern) { return modifyDateTime(getDateTime(), modifyPattern); } - @Description("Returns current date time in UTC time zone modified by pattern
" + @Description("Returns the current date/time in the UTC time zone modified according to a pattern
" + "If modified date time is on weekend and skipWeekends is true then the next working in direction of modification will be returned" + MODIFY_HELP + "Example: #{getDateTime(modifyPattern, skipWeekends)}" @@ -233,7 +233,7 @@ public final LocalDateTime getDateTime(String modifyPattern, boolean skipWeekend return modifyDateTime(nowDate, modifyPattern, skipWeekends); } - @Description("Returns current date time in UTC time zone modified by pattern after applying time zone offset (DST aware).
" + @Description("Returns the current date/time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware).
" + "If modified date time is on weekend and skipWeekends is true then the next working day in direction of modification will be returned" + MODIFY_HELP + "Example: #{getDateTimeByZoneId(modifyPattern, skipWeekends, timeZoneId)}" @@ -246,7 +246,7 @@ public final LocalDateTime getDateTimeByZoneId(String modifyPattern, boolean ski return ZonedDateTime.of(nowDate, zoneId).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); } - @Description("Returns provided datetime in UTC time zone modified by pattern
" + @Description("Returns provided datetime in the UTC time zone modified according to a pattern
" + "If modified date time is on weekend and skipWeekends is true then the next working day in direction of modification will be returned" + MODIFY_HELP + "Example: #{modifyDateTime(dateTime, modifyPattern, skipWeekends)}" @@ -276,25 +276,25 @@ public final LocalDateTime getDateTimeByZoneId(String modifyPattern, String time return DateTimeUtility.toLocalDateTime(modifyTemporal(DateTimeUtility.nowZonedDateTime(timeZoneId), modifyPattern)); } - @Description("Returns current date time in UTC time zone modified by pattern (weekend days are skipped during modification)." + MODIFY_HELP + "Example: #{getBusinessDateTime(modifyPattern)}") + @Description("Returns the current date/time in the UTC time zone modified according to a pattern (weekends are skipped during modification)." + MODIFY_HELP + "Example: #{getBusinessDateTime(modifyPattern)}") @UtilityMethod public final LocalDateTime getBusinessDateTime(String modifyPattern) { return modifyBusinessDateTime(getDateTime(), modifyPattern); } - @Description("Returns current date time in UTC time zone modified by pattern after applying time zone offset (DST aware). Weekend days are skipped during modification." + MODIFY_HELP + "Example: #{getBusinessDateTimeByZoneId(modifyPattern, timeZoneId)}") + @Description("Returns the current date/time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware). weekends are skipped during modification." + MODIFY_HELP + "Example: #{getBusinessDateTimeByZoneId(modifyPattern, timeZoneId)}") @UtilityMethod public final LocalDateTime getBusinessDateTimeByZoneId(String modifyPattern, String timeZoneId) { return modifyBusinessDateTimeByZoneId(getDateTime(), modifyPattern, timeZoneId); } - @Description("Modifies provided date time in UTC time zone modified by pattern (weekend days are skipped during modification)" + MODIFY_HELP + "Usage: #{modifyBusinessDateTime(dateTime, modifyPattern)}") + @Description("Modifies provided date time in the UTC time zone modified according to a pattern (weekends are skipped during modification)" + MODIFY_HELP + "Usage: #{modifyBusinessDateTime(dateTime, modifyPattern)}") @UtilityMethod public final LocalDateTime modifyBusinessDateTime(LocalDateTime dateTime, String modifyPattern) { return getBusinessDateTime(dateTime, modifyDateTime(dateTime, modifyPattern)); } - @Description("Modifies provided date time in UTC time zone modified by pattern after applying time zone offset (DST aware). Weekend days are skipped during modification." + MODIFY_HELP + "Usage: #{modifyBusinessDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") + @Description("Modifies provided date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware). weekends are skipped during modification." + MODIFY_HELP + "Usage: #{modifyBusinessDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") @UtilityMethod public final LocalDateTime modifyBusinessDateTimeByZoneId(LocalDateTime dateTime, String modifyPattern, String timeZoneId) { LocalDateTime originalConverted = ZonedDateTime.of(dateTime, ZoneOffset.UTC).withZoneSameInstant(ZoneId.of(timeZoneId)).toLocalDateTime(); @@ -302,19 +302,19 @@ public final LocalDateTime modifyBusinessDateTimeByZoneId(LocalDateTime dateTime return ZonedDateTime.of(targetTimezoneZoneResult, ZoneId.of(timeZoneId)).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); } - @Description("Converts epoch milliseconds to time in UTC time zone
Example: #{toTime(epochMillis)}") + @Description("Converts epoch milliseconds to time in the UTC time zone
Example: #{toTime(epochMillis)}") @UtilityMethod public LocalTime toTime(long epochMillis) { return DateTimeUtility.toLocalTime(epochMillis); } - @Description("Converts epoch milliseconds to time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toTime(epochMillis, modifyPattern)}") + @Description("Converts epoch milliseconds to time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toTime(epochMillis, modifyPattern)}") @UtilityMethod public LocalTime toTime(long epochMillis, String modifyPattern) { return toTime(toDateTime(epochMillis, modifyPattern)); } - @Description("Converts epoch milliseconds to time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toTimeByZoneId(epochMillis, modifyPattern, timeZoneId)}") + @Description("Converts epoch milliseconds to time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toTimeByZoneId(epochMillis, modifyPattern, timeZoneId)}") @UtilityMethod public LocalTime toTimeByZoneId(long epochMillis, String modifyPattern, String timeZoneId) { ZonedDateTime time = DateTimeUtility.toZonedDateTime(epochMillis).withZoneSameInstant(ZoneId.of(timeZoneId)); @@ -323,112 +323,112 @@ public LocalTime toTimeByZoneId(long epochMillis, String modifyPattern, String t return toTime(DateTimeUtility.toLocalDateTime(time)); } - @Description("Converts string using format pattern to time in UTC time zone." + FORMAT_HELP + "Example: #{toTime(source, formatPattern)}") + @Description("Converts a string using format pattern to time in the UTC time zone." + FORMAT_HELP + "Example: #{toTime(source, formatPattern)}") @UtilityMethod public LocalTime toTime(String source, String formatPattern) { return toTime(toDateTime(source, formatPattern)); } - @Description("Converts string using format pattern to time in UTC time zone modified by pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{toTime(source, formatPattern, modifyPattern)}") + @Description("Converts a string using format pattern to time in the UTC time zone modified according to a pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{toTime(source, formatPattern, modifyPattern)}") @UtilityMethod public LocalTime toTime(String source, String formatPattern, String modifyPattern) { return toTime(toDateTime(source, formatPattern, modifyPattern)); } - @Description("Converts string using format pattern to time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @Description("Converts a string using format pattern to time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public LocalTime toTimeByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(source, formatPattern); return toTimeByZoneId(time, modifyPattern, timeZoneId); } - @Description("Converts date time to time in UTC time zone
Example: #{toTime(dateTime)}") + @Description("Converts the date/time to time in the UTC time zone
Example: #{toTime(dateTime)}") @UtilityMethod public LocalTime toTime(LocalDateTime dateTime) { return DateTimeUtility.toLocalTime(dateTime); } - @Description("Converts date time to time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toTime(dateTime, modifyPattern)}") + @Description("Converts the date/time to time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toTime(dateTime, modifyPattern)}") @UtilityMethod public LocalTime toTime(LocalDateTime dateTime, String modifyPattern) { return toTime(modifyDateTime(dateTime, modifyPattern)); } - @Description("Converts date time to time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") + @Description("Converts the date/time to time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") @UtilityMethod public LocalTime toTimeByZoneId(LocalDateTime dateTime, String modifyPattern, String timeZoneId) { return toTime(modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)); } - @Description("Converts epoch milliseconds to date in UTC time zone
Example: #{toDate(epochMillis)}") + @Description("Converts epoch milliseconds to date in the UTC time zone
Example: #{toDate(epochMillis)}") @UtilityMethod public LocalDate toDate(long epochMillis) { return DateTimeUtility.toLocalDate(epochMillis); } - @Description("Converts epoch milliseconds to date in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toDate(epochMillis, modifyPattern)}") + @Description("Converts epoch milliseconds to date in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toDate(epochMillis, modifyPattern)}") @UtilityMethod public LocalDate toDate(long epochMillis, String modifyPattern) { return toDate(toDateTime(epochMillis, modifyPattern)); } - @Description("Converts epoch milliseconds to date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateByZoneId(epochMillis, modifyPattern, timeZoneId)}") + @Description("Converts epoch milliseconds to date in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateByZoneId(epochMillis, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDate toDateByZoneId(long epochMillis, String modifyPattern, String timeZoneId) { return toDate(toDateTimeByZoneId(epochMillis, modifyPattern, timeZoneId)); } - @Description("Converts string using format pattern to date in UTC time zone." + FORMAT_HELP + "Example: #{toDate(source, formatPattern)}") + @Description("Converts a string using format pattern to date in the UTC time zone." + FORMAT_HELP + "Example: #{toDate(source, formatPattern)}") @UtilityMethod public LocalDate toDate(String source, String formatPattern) { return toDate(toDateTime(source, formatPattern)); } - @Description("Converts string using format pattern to date in UTC time zone modified by pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDate(source, formatPattern, modifyPattern)}") + @Description("Converts a string using format pattern to date in the UTC time zone modified according to a pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDate(source, formatPattern, modifyPattern)}") @UtilityMethod public LocalDate toDate(String source, String formatPattern, String modifyPattern) { return toDate(toDateTime(source, formatPattern, modifyPattern)); } - @Description("Converts string using format pattern to date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @Description("Converts a string using format pattern to date in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDate toDateByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(source, formatPattern); return toDateByZoneId(time, modifyPattern, timeZoneId); } - @Description("Converts date time to date in UTC time zone
Example: #{toDate(dateTime)}") + @Description("Converts date/time to date in the UTC time zone
Example: #{toDate(dateTime)}") @UtilityMethod public LocalDate toDate(LocalDateTime dateTime) { return DateTimeUtility.toLocalDate(dateTime); } - @Description("Converts date time to date in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toDate(dateTime, modifyPattern)}") + @Description("Converts date/time to date in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toDate(dateTime, modifyPattern)}") @UtilityMethod public LocalDate toDate(LocalDateTime dateTime, String modifyPattern) { return toDate(modifyDateTime(dateTime, modifyPattern)); } - @Description("Converts date time to date in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateByZoneId(dateTime, modifyPattern, timeZoneId)}") + @Description("Converts date/time to date in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateByZoneId(dateTime, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDate toDateByZoneId(LocalDateTime dateTime, String modifyPattern, String timeZoneId) { return toDate(modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)); } - @Description("Converts epoch milliseconds to date time in UTC time zone
Example: #{toDateTime(epochMillis)}") + @Description("Converts epoch milliseconds to date/time in the UTC time zone
Example: #{toDateTime(epochMillis)}") @UtilityMethod public LocalDateTime toDateTime(long epochMillis) { return DateTimeUtility.toLocalDateTime(epochMillis); } - @Description("Converts epoch milliseconds to date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toDateTime(epochMillis, modifyPattern)}") + @Description("Converts epoch milliseconds to date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toDateTime(epochMillis, modifyPattern)}") @UtilityMethod public LocalDateTime toDateTime(long epochMillis, String modifyPattern) { return modifyDateTime(toDateTime(epochMillis), modifyPattern); } - @Description("Converts epoch milliseconds to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(epochMillis, modifyPattern, timeZoneId)}") + @Description("Converts epoch milliseconds to date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(epochMillis, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime toDateTimeByZoneId(long epochMillis, String modifyPattern, String timeZoneId) { ZonedDateTime time = toZonedDateTime(epochMillis).withZoneSameInstant(ZoneId.of(timeZoneId)); @@ -436,7 +436,7 @@ public LocalDateTime toDateTimeByZoneId(long epochMillis, String modifyPattern, return DateTimeUtility.toLocalDateTime(time); } - @Description("Converts string using automatic format pattern detection to date time in UTC time zone
" + @Description("Converts a string using automatic format pattern detection to date/time in the UTC time zone
" + "One of the following date/time pattern is defined:" + "
" + " " @@ -503,7 +503,7 @@ public LocalDateTime toDateTime(String source) { } } - @Description("Converts string using format pattern to date time in UTC time zone." + FORMAT_HELP + "Example: #{toDateTime(source, formatPattern)}") + @Description("Converts a string using format pattern to date/time in the UTC time zone." + FORMAT_HELP + "Example: #{toDateTime(source, formatPattern)}") @UtilityMethod public LocalDateTime toDateTime(String source, String formatPattern) { @@ -516,69 +516,69 @@ public LocalDateTime toDateTime(String source, String formatPattern) { return DateTimeUtility.toLocalDateTime(DateTimeUtility.createFormatter(formatPattern).parse(source)); } - @Description("Converts string using format pattern to date time in UTC time zone modified by pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateTime(source, formatPattern, modifyPattern)}") + @Description("Converts a string using format pattern to date/time in the UTC time zone modified according to a pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateTime(source, formatPattern, modifyPattern)}") @UtilityMethod public LocalDateTime toDateTime(String source, String formatPattern, String modifyPattern) { return modifyDateTime(toDateTime(source, formatPattern), modifyPattern); } - @Description("Converts string using format pattern to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @Description("Converts a string using format pattern to date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{toDateTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime toDateTimeByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(source, formatPattern); return modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); } - @Description("Converts time to date time in UTC time zone
Example: #{toDateTime(time)}") + @Description("Converts time to date time in the UTC time zone
Example: #{toDateTime(time)}") @UtilityMethod public LocalDateTime toDateTime(LocalTime time) { return DateTimeUtility.toLocalDateTime(time); } - @Description("Converts time to date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toDateTime(time, modifyPattern)}") + @Description("Converts time to date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toDateTime(time, modifyPattern)}") @UtilityMethod public LocalDateTime toDateTime(LocalTime time, String modifyPattern) { return modifyDateTime(toDateTime(time), modifyPattern); } - @Description("Converts time to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(time, modifyPattern, timeZoneId)}") + @Description("Converts time to date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(time, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime toDateTimeByZoneId(LocalTime time, String modifyPattern, String timeZoneId) { return modifyDateTimeByZoneId(toDateTime(time), modifyPattern, timeZoneId); } - @Description("Converts date to date time in UTC time zone
Example: #{toDateTime(date)}") + @Description("Converts date to date/time in the UTC time zone
Example: #{toDateTime(date)}") @UtilityMethod public LocalDateTime toDateTime(LocalDate date) { return DateTimeUtility.toLocalDateTime(date); } - @Description("Converts date to date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{toDateTime(date, modifyPattern)}") + @Description("Converts date to date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{toDateTime(date, modifyPattern)}") @UtilityMethod public LocalDateTime toDateTime(LocalDate date, String modifyPattern) { return modifyDateTime(toDateTime(date), modifyPattern); } - @Description("Converts date to date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(date, modifyPattern, timeZoneId)}") + @Description("Converts date to date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{toDateTimeByZoneId(date, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime toDateTimeByZoneId(LocalDate date, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(date); return modifyDateTimeByZoneId(time, modifyPattern, timeZoneId); } - @Description("Formats time in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatTime(time, formatPattern)}") + @Description("Formats time in the UTC time zone into a string using format pattern." + FORMAT_HELP + "Example: #{formatTime(time, formatPattern)}") @UtilityMethod public String formatTime(LocalTime time, String formatPattern) { return formatDateTime(toDateTime(time), formatPattern); } - @Description("Formats time in UTC time zone modified by pattern into string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatTime(time, formatPattern, modifyPattern)}") + @Description("Formats time in the UTC time zone modified according to a pattern into a string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatTime(time, formatPattern, modifyPattern)}") @UtilityMethod public String formatTime(LocalTime time, String formatPattern, String modifyPattern) { return formatDateTime(toDateTime(time), formatPattern, modifyPattern); } - @Description("Formats time in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatTimeByZoneId(time, formatPattern, modifyPattern, timeZoneId)}") + @Description("Formats time in the UTC time zone modified according to a pattern into a string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatTimeByZoneId(time, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public String formatTimeByZoneId(LocalTime time, String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime localDateTime = toDateTime(time); @@ -586,19 +586,19 @@ public String formatTimeByZoneId(LocalTime time, String formatPattern, String mo return formatDateTime(localDateTime, formatPattern); } - @Description("Formats date in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatDate(date, formatPattern)}") + @Description("Formats date in the UTC time zone into a string using format pattern." + FORMAT_HELP + "Example: #{formatDate(date, formatPattern)}") @UtilityMethod public String formatDate(LocalDate date, String formatPattern) { return formatDateTime(toDateTime(date), formatPattern); } - @Description("Formats date in UTC time zone modified by pattern into string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDate(date, formatPattern, modifyPattern)}") + @Description("Formats date in the UTC time zone modified according to a pattern into a string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDate(date, formatPattern, modifyPattern)}") @UtilityMethod public String formatDate(LocalDate date, String formatPattern, String modifyPattern) { return formatDateTime(toDateTime(date), formatPattern, modifyPattern); } - @Description("Formats date in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateByZoneId(date, formatPattern, modifyPattern, timeZoneId)}") + @Description("Formats date in the UTC time zone modified according to a pattern into a string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateByZoneId(date, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public String formatDateByZoneId(LocalDate date, String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(date); @@ -606,111 +606,111 @@ public String formatDateByZoneId(LocalDate date, String formatPattern, String mo return formatDateTime(time, formatPattern); } - @Description("Formats date time in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatDateTime(dateTime, formatPattern)}") + @Description("Formats date/time in the UTC time zone into a string using format pattern." + FORMAT_HELP + "Example: #{formatDateTime(dateTime, formatPattern)}") @UtilityMethod public String formatDateTime(LocalDateTime dateTime, String formatPattern) { return formatTemporal(dateTime, formatPattern); } - @Description("Formats date time in UTC time zone modified by pattern into string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTime(dateTime, formatPattern, modifyPattern)}") + @Description("Formats date time in the UTC time zone modified according to a pattern into a string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTime(dateTime, formatPattern, modifyPattern)}") @UtilityMethod public String formatDateTime(LocalDateTime dateTime, String formatPattern, String modifyPattern) { return formatTemporal(modifyDateTime(dateTime, modifyPattern), formatPattern); } - @Description("Formats date time in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTimeByZoneId(dateTime, formatPattern, modifyPattern, timeZoneId)}") + @Description("Formats date time in the UTC time zone modified according to a pattern into a string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTimeByZoneId(dateTime, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public String formatDateTimeByZoneId(LocalDateTime dateTime, String formatPattern, String modifyPattern, String timeZoneId) { dateTime = modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId); return formatDateTime(dateTime, formatPattern); } - @Description("Merges date and time into date time in UTC time zone
Example: #{mergeDateTime(date, time)}") + @Description("Merges date and time into date/time in the UTC time zone
Example: #{mergeDateTime(date, time)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDate date, LocalTime time) { return DateTimeUtility.toLocalDateTime(date, time); } - @Description("Merges date and time into date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{mergeDateTime(date, time, modifyPattern)}") + @Description("Merges date and time into date time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{mergeDateTime(date, time, modifyPattern)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDate date, LocalTime time, String modifyPattern) { return modifyDateTime(mergeDateTime(date, time), modifyPattern); } - @Description("Merges date and time into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(date, time, modifyPattern, timeZoneId)}") + @Description("Merges date and time into date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(date, time, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime mergeDateTimeByZoneId(LocalDate date, LocalTime time, String modifyPattern, String timeZoneId) { LocalDateTime localDateTime = mergeDateTime(date, time); return modifyDateTimeByZoneId(localDateTime, modifyPattern, timeZoneId); } - @Description("Merges date and date time (only time is used) into date time in UTC time zone
Example: #{mergeDateTime(date, dateTime)}") + @Description("Merges date and date/time (only time is used) into date/time in the UTC time zone
Example: #{mergeDateTime(date, dateTime)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDate date, LocalDateTime dateTime) { return mergeDateTime(date, toTime(dateTime)); } - @Description("Merges date and date time (only time is used) into date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{mergeDateTime(date, dateTime, modifyPattern)}") + @Description("Merges date and date/time (only time is used) into date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{mergeDateTime(date, dateTime, modifyPattern)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDate date, LocalDateTime dateTime, String modifyPattern) { return mergeDateTime(date, toTime(dateTime), modifyPattern); } - @Description("Merges date and date time (only time is used) into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(date, dateTime, modifyPattern, timeZoneId)}") + @Description("Merges date and date time (only time is used) into date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(date, dateTime, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime mergeDateTimeByZoneId(LocalDate date, LocalDateTime dateTime, String modifyPattern, String timeZoneId) { return mergeDateTimeByZoneId(date, dateTime.toLocalTime(), modifyPattern, timeZoneId); } - @Description("Merges date time (only date is used) and time into date time in UTC time zone
Example: #{mergeDateTime(dateTime, time)}") + @Description("Merges date/time (only date is used) and time into date/time in the UTC time zone
Example: #{mergeDateTime(dateTime, time)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDateTime dateTime, LocalTime time) { return mergeDateTime(toDate(dateTime), time); } - @Description("Merges date time (only date is used) and time into date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{mergeDateTime(dateTime, time, modifyPattern)}") + @Description("Merges date/time (only date is used) and time into date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{mergeDateTime(dateTime, time, modifyPattern)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDateTime dateTime, LocalTime time, String modifyPattern) { return mergeDateTime(toDate(dateTime), time, modifyPattern); } - @Description("Merges date time (only date is used) and time into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(dateTime, time, modifyPattern, timeZoneId)}") + @Description("Merges date time (only date is used) and time into date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(dateTime, time, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime mergeDateTimeByZoneId(LocalDateTime dateTime, LocalTime time, String modifyPattern, String timeZoneId) { return mergeDateTimeByZoneId(dateTime.toLocalDate(), time, modifyPattern, timeZoneId); } - @Description("Merges date time (only date is used) and date time (only time is used) into date time in UTC time zone
Example: #{mergeDateTime(firstDateTime, secondDateTime)}") + @Description("Merges date/time (only date is used) and date/time (only time is used) into date/time in the UTC time zone
Example: #{mergeDateTime(firstDateTime, secondDateTime)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDateTime firstDateTime, LocalDateTime secondDateTime) { return mergeDateTime(toDate(firstDateTime), toTime(secondDateTime)); } - @Description("Merges date time (only date is used) and date time (only time is used) into date time in UTC time zone modified by pattern." + MODIFY_HELP + "Example: #{mergeDateTime(firstDateTime, secondDateTime, modifyPattern)}") + @Description("Merges date/time (only date is used) and date/time (only time is used) into date/time in the UTC time zone modified according to a pattern." + MODIFY_HELP + "Example: #{mergeDateTime(firstDateTime, secondDateTime, modifyPattern)}") @UtilityMethod public LocalDateTime mergeDateTime(LocalDateTime firstDateTime, LocalDateTime secondDateTime, String modifyPattern) { return mergeDateTime(toDate(firstDateTime), toTime(secondDateTime), modifyPattern); } - @Description("Merges date time (only date is used) and date time (only time is used) into date time in UTC time zone modified by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(firstDateTime, secondDateTime, modifyPattern, timeZoneId)}") + @Description("Merges date time (only date is used) and date time (only time is used) into date time in the UTC time zone modified according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{mergeDateTimeByZoneId(firstDateTime, secondDateTime, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime mergeDateTimeByZoneId(LocalDateTime firstDateTime, LocalDateTime secondDateTime, String modifyPattern, String timeZoneId) { return mergeDateTimeByZoneId(firstDateTime.toLocalDate(), secondDateTime.toLocalTime(), modifyPattern, timeZoneId); } - @Description("Formats current date time in UTC time zone into string using format pattern." + FORMAT_HELP + "Example: #{formatDateTime(formatPattern)}") + @Description("Formats the current date/time in the UTC time zone into a string using format pattern." + FORMAT_HELP + "Example: #{formatDateTime(formatPattern)}") @UtilityMethod public String formatDateTime(String formatPattern) { return formatDateTime(getDateTime(), formatPattern); } - @Description("Formats current date time in UTC time zone modified by pattern into string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTime(formatPattern, modifyPattern)}") + @Description("Formats the current date/time in the UTC time zone modified according to a pattern into a string using format pattern." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTime(formatPattern, modifyPattern)}") @UtilityMethod public String formatDateTime(String formatPattern, String modifyPattern) { return formatDateTime(getDateTime(), formatPattern, modifyPattern); } - @Description("Formats current date time in UTC time zone modified by pattern into string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTimeByZoneId(formatPattern, modifyPattern, timeZoneId)}") + @Description("Formats the current date time in the UTC time zone modified according to a pattern into a string using format pattern after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example: #{formatDateTimeByZoneId(formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public String formatDateTimeByZoneId(String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime time = getDateTime(); @@ -718,13 +718,13 @@ public String formatDateTimeByZoneId(String formatPattern, String modifyPattern, return formatDateTime(time, formatPattern); } - @Description("Modifies date time string using format and modify patterns." + FORMAT_HELP + MODIFY_HELP + "Example; #{modifyDateTime(source, formatPattern, modifyPattern)}") + @Description("Modifies a date/time string using format and modify patterns." + FORMAT_HELP + MODIFY_HELP + "Example; #{modifyDateTime(source, formatPattern, modifyPattern)}") @UtilityMethod public String modifyDateTime(String source, String formatPattern, String modifyPattern) { return formatDateTime(toDateTime(source, formatPattern, modifyPattern), formatPattern); } - @Description("Modifies date time string using format and modify patterns after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example; #{modifyDateTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") + @Description("Modifies a date/time string using format and modify patterns after applying time zone offset (DST aware)." + FORMAT_HELP + MODIFY_HELP + "Example; #{modifyDateTimeByZoneId(source, formatPattern, modifyPattern, timeZoneId)}") @UtilityMethod public String modifyDateTimeByZoneId(String source, String formatPattern, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(source); @@ -732,38 +732,38 @@ public String modifyDateTimeByZoneId(String source, String formatPattern, String return formatDateTime(time, formatPattern); } - @Description("Modifies time in UTC time zone by pattern." + MODIFY_HELP + "Example: #{modifyTime(time, modifyPattern)}") + @Description("Modifies time in the UTC time zone according to a pattern." + MODIFY_HELP + "Example: #{modifyTime(time, modifyPattern)}") @UtilityMethod public LocalTime modifyTime(LocalTime time, String modifyPattern) { return toTime(toDateTime(time, modifyPattern)); } - @Description("Modifies time in UTC time zone by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyTimeByZoneId(time, modifyPattern, timeZoneId)}") + @Description("Modifies time in the UTC time zone according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyTimeByZoneId(time, modifyPattern, timeZoneId)}") @UtilityMethod public LocalTime modifyTimeByZoneId(LocalTime time, String modifyPattern, String timeZoneId) { return toTime(modifyDateTimeByZoneId(toDateTime(time), modifyPattern, timeZoneId)); } - @Description("Modifies date in UTC time zone by pattern." + MODIFY_HELP + "Example: #{modifyDate(date, modifyPattern)}") + @Description("Modifies date in the UTC time zone according to a pattern." + MODIFY_HELP + "Example: #{modifyDate(date, modifyPattern)}") @UtilityMethod public LocalDate modifyDate(LocalDate date, String modifyPattern) { return toDate(toDateTime(date, modifyPattern)); } - @Description("Modifies date in UTC time zone by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyDateByZoneId(date, modifyPattern, timeZoneId)}") + @Description("Modifies date in the UTC time zone according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyDateByZoneId(date, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDate modifyDateByZoneId(LocalDate date, String modifyPattern, String timeZoneId) { LocalDateTime time = toDateTime(date); return toDate(modifyDateTimeByZoneId(time, modifyPattern, timeZoneId)); } - @Description("Modifies date time in UTC time zone by pattern." + MODIFY_HELP + "Example: #{modifyDateTime(dateTime, modifyPattern)}") + @Description("Modifies date/time in the UTC time zone according to a pattern." + MODIFY_HELP + "Example: #{modifyDateTime(dateTime, modifyPattern)}") @UtilityMethod public LocalDateTime modifyDateTime(LocalDateTime dateTime, String modifyPattern) { return modifyTemporal(dateTime, modifyPattern); } - @Description("Modifies date time in UTC time zone by pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") + @Description("Modifies date/time in the UTC time zone according to a pattern after applying time zone offset (DST aware)." + MODIFY_HELP + "Example: #{modifyDateTimeByZoneId(dateTime, modifyPattern, timeZoneId)}") @UtilityMethod public LocalDateTime modifyDateTimeByZoneId(LocalDateTime dateTime, String modifyPattern, String timeZoneId) { LocalDateTime convertedToTargetZone = ZonedDateTime.of(dateTime, ZoneOffset.UTC) @@ -772,7 +772,7 @@ public LocalDateTime modifyDateTimeByZoneId(LocalDateTime dateTime, String modif .withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); } - @Description("Returns difference between minuend and subtrahend date time in specified date component
" + @Description("Returns the difference between minuend and subtrahend date/time in specified date component
" + "The following date components are defined:" + DATE_TIME_COMPONENTS_TABLE + "Example: #{diffDateTime(minuend, subtrahend, dateComponent)}") @@ -789,7 +789,7 @@ public long diffDateTime(LocalDateTime minuend, LocalDateTime subtrahend, String } } - @Description("Returns difference between ISO string minuend and subtrahend date time in specified date component
" + @Description("Returns the difference between an ISO string minuend and subtrahend date/time in a specified date component
" + "The following date components are defined:" + DATE_TIME_COMPONENTS_TABLE + "Example: #{diffDateTimeISO(minuend, subtrahend, dateComponent)}") From b4f51fd3146e8fcb12562cd3051cef5e1d9b40a3 Mon Sep 17 00:00:00 2001 From: "oleg.legkov" Date: Tue, 26 Mar 2019 13:20:06 +0300 Subject: [PATCH 06/26] [RMA] Support #44876. Documentation > NTGMatrixUtil (cherry picked from commit c8ba74897510879a4525eb3e61947639d1b072a1) Change-Id: I2297d69e5acd5df760a840730d4a7731305b9389 --- .../exactpro/sf/actions/NTGMatrixUtil.java | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/BackEnd/Service/service-ntg/src/main/java/com/exactpro/sf/actions/NTGMatrixUtil.java b/BackEnd/Service/service-ntg/src/main/java/com/exactpro/sf/actions/NTGMatrixUtil.java index dd6dddb0..ccffca7a 100644 --- a/BackEnd/Service/service-ntg/src/main/java/com/exactpro/sf/actions/NTGMatrixUtil.java +++ b/BackEnd/Service/service-ntg/src/main/java/com/exactpro/sf/actions/NTGMatrixUtil.java @@ -40,10 +40,10 @@ public class NTGMatrixUtil extends AbstractCaller { private static final Logger logger = LoggerFactory.getLogger(NTGMatrixUtil.class); /** - * Generate unique ClOrID for new order. + * Generates a unique ClOrID for the new order. * @return */ - @Description("Generate unique ClOrdID for new order
" + @Description("Generates a unique ClOrdID for the new order
" + " Example:" + "#{ShortClOrdID(\"test\")}
" + " will return:
" @@ -59,10 +59,10 @@ public final String ShortClOrdID(final String userKey) } /** - * Generate unique ClOrID for new order. + * Generates a unique ClOrdID for the new order. * @return */ - @Description("Generate unique ClOrdID for new order
" + @Description("Generates a unique ClOrdID for the new order
" + "Example:
" + "#{ClOrdID()}
" + "will return:
" @@ -76,12 +76,12 @@ public final String ClOrdID() } /** - * Generate unique ClOrID for new order. + * Generates a unique ClOrID for the new order. * @param length * @return */ @Description( - "Generate unique ClOrID for new order.
" + "Generates a unique ClOrID for the new order.
" ) @UtilityMethod public final String ClOrdID(int length) @@ -105,7 +105,7 @@ public final String TransactTime() return NTGUtility.getTransactTime(); } - @Description("Transact Time - return time in GMT time zone
" + @Description("Transact Time - return time in the GMT time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "#{TransactTime(\"Y+2:M-6:D=4:h+1:m-2:s=39\")}
" @@ -119,7 +119,7 @@ public LocalDateTime TransactTime(String dateFormat) return DateUtil.modifyLocalDateTime(dateFormat); } - @Description("Return current date in GMT time zone in format: yyyyMMdd hh:mm:ss.SSS
" + @Description("Returns the current date in the GMT time zone in the format: yyyyMMdd hh:mm:ss.SSS
" + "Example:
" + "#{EntryTime()}
" + "will return:
" @@ -135,7 +135,7 @@ public final String EntryTime() * * @return formatted date time one day apart from current */ - @Description("Return expire date time one day in future from the current date.
" + @Description("Returns the expiry DateTime in the format: 'current date + 1 day'.
" + "Example:
" + "#{ExpireDateTime()}
" + "will return:
" @@ -151,7 +151,7 @@ public final int ExpireDateTime() * * @return formatted date time */ - @Description("Return expire date time.
" + @Description("Returns the expiry DateTime.
" + DateUtil.MODIFY_HELP) @UtilityMethod public final int ExpireDateTime(String dateFormat) @@ -164,16 +164,16 @@ public final int ExpireDateTime(String dateFormat) * * @return formatted date time */ - @Description("Return expire date time.
" + @Description("Returns the expiry DateTime.
" + " Example:
" + " For the 25 Mar 2010, 08:00:00" + " where input date parameter #{getDate(\"Y+2:m-1:D=4\")}" + " this method will return the following:
" + " 1330833600
" + " All fields are optional. If you do not specify any fields" - + " than current time will be returned." - + " All specified date modification operations will be applied" - + " in the same order as they present in input string.
") + + " then the current time will be returned." + + " All the specified date modification operations will be applied" + + " in the same order as they are presented in the input string.
") @UtilityMethod public final int ExpireDateTime(LocalDateTime date) { @@ -185,8 +185,8 @@ public final int ExpireDateTime(LocalDateTime date) * * @return formatted date time */ - @Description("Return expire date time as specified in input values.
" - + "Function parameters is year, month, day, hour, minute, second
" + @Description("Returns the expiry DateTime as specified in the input values.
" + + "Function parameters are year, month, day, hour, minute, second
" + "Example:
" + "#{ExpireDateTime(2013,8,6,18,25,31)}
" + "will return:
" @@ -212,9 +212,9 @@ public final int ExpireDateTime(int year, int month, int day, int hour, int minu * @throws Exception */ @Description("Same as ExpireDateTimePOSIX
" - + " Return expire date in GMT time zone time according with input parameters.
" - + " First parameter is one of the values: SECOND , MINUTE, HOUR, DAY, MONTH, YEAR.
" - + " Second parameter is integer amount of time. Absence of the sign sybmol is evaluated as positive number.
" + + " Returns the expiry DateTime in the GMT time zone time according to the input parameters.
" + + " The first parameter is one of the values: SECOND , MINUTE, HOUR, DAY, MONTH, YEAR.
" + + " The second parameter is an integer amount of time. The absence of the sign symbol is evaluated as a positive number.
" + " Example:
" + " #{ExpireDateTime(\"MINUTE\", \"5\")}
" + " will return:
" @@ -231,9 +231,9 @@ public final int ExpireDateTime(String datePart, String value) throws Exception // return dateTime; } - @Description(" Return expire date time in GMT time zone according with input parameters.
" - + " First parameter is one of the values: SECOND , MINUTE, HOUR, DAY, MONTH, YEAR.
" - + " Second parameter is integer amount of time. Absence of the sign sybmol is evaluated as positive number.
" + @Description(" Returns the expiry DateTime in the GMT time zone according to the input parameters.
" + + " The first parameter is one of the values: SECOND , MINUTE, HOUR, DAY, MONTH, YEAR.
" + + " The second parameter is an integer amount of time. The absence of the sign symbol is evaluated as a positive number.
" + " Example:
" + " #{ExpireDateTimePOSIX(\"MINUTE\", \"5\")}
" + " will return:
" From f7948a82de19d31266de9608cb5525725cc6614f Mon Sep 17 00:00:00 2001 From: "oleg.legkov" Date: Tue, 26 Mar 2019 16:49:28 +0300 Subject: [PATCH 07/26] [RMA] Support #44874. Documentation > FIXMatrixUtil (cherry picked from commit ddde7c4da7ad5e818cbc3b9c5c4ce0fbbd952fea) Change-Id: I9e7f7a46f3700148922d376d92adc46bdea08dbb --- .../exactpro/sf/actions/FIXMatrixUtil.java | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java index 6e5da1cc..992e458b 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java @@ -75,7 +75,7 @@ public class FIXMatrixUtil extends AbstractCaller { private static final DateTimeFormatter FIX_DATE_TIME_FORMATTER_MS = DateTimeUtility.createFormatter(FIX_DATE_TIME_FORMAT_MS); private static final DateTimeFormatter FIX_DATE_TIME_FORMATTER_NS = DateTimeUtility.createFormatter(FIX_DATE_TIME_FORMAT_NS); - @Description("Transact Time - return time in GMT time zone
" + @Description("Transact Time - returns the time in the GMT time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "#{TransactTime(\"Y+2:m-6:D=4:h+1:M-2:s=39\")}
" @@ -89,7 +89,7 @@ public LocalDateTime TransactTime(String dateFormat) return DateUtil.modifyLocalDateTime(dateFormat); } - @Description("ExpireTime function accept three parameters: Time Shifting Patterns related current time, Date and Time Format Patterns and Date and TimeZone." + @Description("ExpireTime function accepts three parameters: Time Shifting Patterns in reference to the current time, Date and Time Format Patterns and Date and TimeZone." + DateUtil.FORMAT_HELP + DateUtil.MODIFY_HELP + "

Example:

" @@ -104,7 +104,7 @@ public final String ExpireTime(String dateFormat, String format, String timeZone return DateUtil.formatDateTime(dateFormat, format, timeZone); } - @Description(" Expire Time - return time in GMT time zone
" + @Description(" Expire Time - returns the time in the GMT time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "
" @@ -121,10 +121,10 @@ public final String ExpireTime(String dateFormat) return DateUtil.modifyZonedDateTime(dateFormat).format(FIX_DATE_TIME_FORMATTER); } - @Description(" Expire Time - return time in GMT time zone in format " + FIX_DATE_TIME_FORMAT + "
" + @Description(" Expire Time - returns the time in the GMT time zone in the format " + FIX_DATE_TIME_FORMAT + "
" + " Example:
" + " For the 10 Nov 2015, 13:00:00" - + " where input date parameter #{getDate(\"h=16:m=23:s=0\")}" + + " with input date parameter #{getDate(\"h=16:m=23:s=0\")}" + " this method will return the following:
" + " 20151110-16:23:00
" ) @@ -134,8 +134,8 @@ public final String ExpireTime(LocalDateTime date) return DateTimeUtility.nowZonedDateTime().format(FIX_DATE_TIME_FORMATTER); } - @Description("Calculates checksum of FIX message. " - +"Message contains | delimiter.
" + @Description("Calculates the checksum of FIX message. " + +"The message contains the default | delimiter.
" +"Example:
" +"For this message '8=FIX.4.4|9=122|35=D|34=215|49=CLIENT12|52=20100225-19:41:57.316|56=B|1=Marcel|11=13346|21=1|40=2|44=5|54=1|59=0|60=20100225-19:39:52.020|'
" +"checksum is 072" @@ -153,8 +153,9 @@ public String calculateChecksum(String msg){ return formatter.format(checksum & 0xFF); } - @Description("Calculates checksum of FIX message. " - +"Message contains delimiter specified in delimiter arg.
" + @Description("Calculates the checksum of FIX message. " + +"Msg - the message for which checksum needs to be calculated;
" + +"Delimiter - the separator of the message fields;
" +"Example:
" +"For this message '8=FIX.4.4|9=122|35=D|34=215|49=CLIENT12|52=20100225-19:41:57.316|56=B|1=Marcel|11=13346|21=1|40=2|44=5|54=1|59=0|60=20100225-19:39:52.020|'
" +"exec calculateChecksum(msg,'|') return checksum is 072" @@ -172,7 +173,7 @@ public String calculateChecksum(String msg, char delimiter) { return formatter.format(checksum & 0xFF); } - @Description(" Expire Time - return time in GMT time zone
" + @Description(" Expire Time - returns the time in the GMT time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "#{ExpireTime(\"Y+2:M-6:D=4:h+1:m-2:s=39\")}
" @@ -186,7 +187,7 @@ public final String ExpireTimeMS(String dateFormat) return DateUtil.modifyZonedDateTime(dateFormat).format(FIX_DATE_TIME_FORMATTER_MS); } - @Description(" Expire Time - return time in GMT time zone
" + @Description(" Expire Time - returns the time in the GMT time zone
" + DateUtil.MODIFY_HELP + "#{ExpireTime(\"Y+2:M-6:D=4:h+1:m-2:s=39:mc=123456\")}
" + "default format : yyyyMMdd-HH:mm:ss.000000" @@ -198,7 +199,7 @@ public final String ExpireTimeMC(String dateFormat) { return result.substring(0, FIX_DATE_TIME_FORMAT_NS.length() - 3); } - @Description(" Expire Time - return time in GMT time zone
" + @Description(" Expire Time - returns the time in the GMT time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "#{ExpireTime(\"Y+2:M-6:D=4:h+1:m-2:s=39:ns=123456789\")}
" @@ -212,8 +213,8 @@ public final String ExpireTimeNS(String dateFormat) { return result.substring(0, FIX_DATE_TIME_FORMAT_NS.length() - 3); } - @Description("Expire Date - return time in GMT time zone
" - + " Format date to FIX date format." + @Description("Expire Date - returns the time in the GMT time zone
" + + " Formats the date to the FIX date format." + DateUtil.MODIFY_HELP + "Example:
" + "#{ExpireDate(\"Y+2:M-6:D=4\")}
" @@ -226,7 +227,7 @@ public final String ExpireDate(String dateFormat) { } - @Description(" Expire Time - return time in UTC time zone
" + @Description(" Expire Time - returns the time in the UTC time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "
" @@ -243,7 +244,7 @@ public final String ExpireTimeUTC(String dateFormat) return ExpireTime(dateFormat); } - @Description(" Expire Time - return time in GMT time zone
" + @Description(" Expire Time - returns the time in the GMT time zone
" + DateUtil.MODIFY_HELP + "Example:
" + "#{ExpireTime(\"Y+2:M-6:D=4:h+1:m-2:s=39:ms=123\")}
" @@ -257,8 +258,8 @@ public final String ExpireTimeMSUTC(String dateFormat) return ExpireTimeMS(dateFormat); // BaseExpireTime(dateFormat, FIX_DATE_TIME_FORMAT_MS, DateUtil.GMT_TIME_ZONE.getID(), DateUtil.UTC_TIME_ZONE.getID()); } - @Description("Expire Date - return time in GMT time zone
" - + " Format date to FIX date format." + @Description("Expire Date - returns the time in the GMT time zone
" + + " Formats the date to the FIX date format." + DateUtil.MODIFY_HELP + "Example:
" + "#{ExpireDate(\"Y+2:M-6:D=4\")}
" @@ -299,7 +300,7 @@ public final String ClOrdID() * @return */ @Description( - "Generate unique ClOrID for new order.
" + "Generates a unique ClOrID for a new order.
" ) @UtilityMethod public final String ClOrdID(int length) @@ -307,14 +308,14 @@ public final String ClOrdID(int length) return FixUtil.generateClorIDSpecLng(length); } - @Description("Mark field as excluded.
" - + "This method excludes auto generated field from message when use in sendDirty action.") + @Description("Marks a field as excluded.
" + + "This method excludes the auto generated field from the message when used in the “sendDirty” action.") @UtilityMethod public Object ExcludeField() { return FieldConst.EXCLUDED_FIELD; } - @Description("Convert Side field from ITCH to FIX format") + @Description("Converts Side field from ITCH to FIX format") @UtilityMethod public char ITCHSideToFIXSide(Short side) { @@ -344,7 +345,7 @@ public Integer UnwrapSeqNum(String seqNum) } @UtilityMethod - @Description("Return the MsgSeqNum from the Text field
" + "Usage: #{extractMsgSeqNum(\"text\")}
") + @Description("Returns the MsgSeqNum from the Text field
" + "Usage: #{extractMsgSeqNum(\"text\")}
") public int extractMsgSeqNum(String text) { try { return extractSeqNum(text); From 09597bde19a07c7f27713a04f2e207222b4c0bec Mon Sep 17 00:00:00 2001 From: "anatoly.ivanov" Date: Thu, 4 Apr 2019 16:03:34 +0300 Subject: [PATCH 08/26] Bug #54769. sailfish-core: html report npm libs import is fixed. (cherry picked from commit d685a039357efbc24c203f6bfb5365fcccdfb1d6) Change-Id: Ib9bb77d8d5486ed23707f0c8bb7a01903debdc68 --- BackEnd/Core/sailfish-core/build.gradle | 82 ++++++++++++------------- 1 file changed, 40 insertions(+), 42 deletions(-) diff --git a/BackEnd/Core/sailfish-core/build.gradle b/BackEnd/Core/sailfish-core/build.gradle index d24f0cb4..95917173 100644 --- a/BackEnd/Core/sailfish-core/build.gradle +++ b/BackEnd/Core/sailfish-core/build.gradle @@ -30,7 +30,8 @@ ext { htmlResourcesGenDir = file("${genResDir}/com/exactpro/sf/scriptrunner/impl/htmlreport") htmlResourcesMainDir = file("${mainResDir}/com/exactpro/sf/scriptrunner/impl/htmlreport") templatesDir = file("${mainDir}/templates") - jqueryUiResourcesDir = file("${htmlResourcesProvidedDir}/resources") + jqueryResourcesTargetDir = file("${htmlResourcesProvidedDir}/resources") + npmInstallDir = file("${buildDir}/npm/") } archivesBaseName = 'sailfish-core' @@ -131,40 +132,35 @@ dependencies { runtimeOnly 'commons-collections:commons-collections:3.2.2' // for commons-configuration testRuntime 'org.apache.derby:derby:10.14.2.0' +} - clientDependencies { - npm { - 'jquery'('~3.3.1'){ - include 'jquery.min.js' - eachFile { - it.path = "../" + it.name //remove remove jquery folder - } - } - 'components-jqueryui'('1.12.1') { - include 'jquery-ui.min.js', '**/ui-icons_222222_256x240.png' - include 'themes/base/jquery-ui.min.css' - eachFile { - it.path = '../' + it.name //remove remove subfolders folder - } - } + clientDependencies { + npm { + 'jquery'('~3.3.1'){ + include 'jquery.min.js' + } + 'components-jqueryui'('1.12.1') { + include 'jquery-ui.min.js' + include '**/ui-darkness/images/ui-icons_222222_256x240.png' + include 'themes/base/jquery-ui.min.css' } - installDir = jqueryUiResourcesDir } + + installDir = npmInstallDir } task createDir { + doLast { - genJavaDir.mkdirs() - genResDir.mkdirs() + genJavaDir.mkdirs() + genResDir.mkdirs() htmlResourcesGenDir.mkdirs() - jqueryUiResourcesDir.mkdirs() - } + jqueryResourcesTargetDir.mkdirs() + } } -clientInstall.dependsOn("createDir") - task generateJavaFromXsd (dependsOn: 'createDir') { inputs.file file("${dataMessageDir}/datamessage.xsd") @@ -302,13 +298,32 @@ task generateService_Dictionaries{ } } +task copyNpmResources (type: Copy) { + dependsOn(clientInstall) + + from (npmInstallDir) { + eachFile { + it.relativePath = new RelativePath(true, it.relativePath.lastName) + } + } + into jqueryResourcesTargetDir + + includeEmptyDirs = false +} + +task unpackJsReportData (type: Copy) { + dependsOn.add("copyNpmResources") + + from { configurations.js_report.collect { zipTree(it) } } + into htmlResourcesProvidedDir +} // FIXME: update gradle-plugin for delayed write support ( e.g. doLast{} ) // FIXME: extract file enumeration logic into 'local plugin' task writeReportResourceContents() { - dependsOn.add('copyJsReportData') + dependsOn.add('unpackJsReportData') - doLast{ + doLast { String contents = Stream.concat( fileTree(htmlResourcesMainDir).getFiles().stream() .map { f -> htmlResourcesMainDir.toPath().relativize(f.toPath()) }, @@ -325,19 +340,12 @@ task writeReportResourceContents() { } } -task copyJsReportData (type: Copy) { - into htmlResourcesProvidedDir - - from { configurations.js_report.collect { zipTree(it) } } -} - compileJava { dependsOn.add("generateJavaFromXsd") dependsOn.add("jamonGenerate") dependsOn.add("generateTest_aml_Dictionaries") dependsOn.add("generateService_Dictionaries") dependsOn.add('generateVersionClass') - dependsOn.add('clientInstall') dependsOn.add("writeReportResourceContents") } @@ -345,8 +353,6 @@ test { systemProperties "basedir": "${projectDir}" jvmArgs '-XX:MaxPermSize=256m' - - } artifacts { @@ -375,14 +381,6 @@ checkCompatibility { versionFile = File.createTempFile("${getTemporaryDir()}",'VERSION') } -clientInstall { - doLast { - jqueryUiResourcesDir.eachDir { //remove empty dirs - it.deleteDir() - } - } -} - //Functions TODO: move to parent def configureGenerateSailfishMessage(files, inputs, outputs) { files.each { dict -> From bcad78309123dbc291cd9d64fd48af40c2274193 Mon Sep 17 00:00:00 2001 From: "anatoly.ivanov" Date: Fri, 5 Apr 2019 14:00:47 +0300 Subject: [PATCH 09/26] Feature #52483. TestdateUtil: testFormatDateTimeByZoneId2 is removed (cherry picked from commit 962f8c625cbb3bb4ffc27c54457a58dfdfbea8df) Change-Id: If3807224b4348c8c9a79e4cd55c4e1e73b33813f --- .../src/test/java/com/exactpro/sf/actions/TestDateUtil.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java index 93fe2bb2..a3877fca 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java @@ -350,12 +350,6 @@ public void testMergeDateTimeByZoneId4(){ Assert.assertTrue(awaitingTime4.equals(dateUtil.mergeDateTimeByZoneId(localDateTime4, localDateTime4, "h+0", "Europe/London"))); } - @Test - public void testFormatDateTimeByZoneId2(){ - String resultTime = "20190314-09:51:44.000"; - Assert.assertTrue(resultTime.equals(dateUtil.formatDateTimeByZoneId("yyyyMMdd-HH:mm:ss.SSS", "D=14:h=9:m=51:s=44:ms=0", "Europe/London"))); - } - @Test public void testModifyDateTimeByZoneId(){ Assert.assertTrue("20190311-14:05:23".equals(dateUtil.modifyDateTimeByZoneId("2019-03-11 14:05:23.000", "yyyyMMdd-HH:mm:ss", "h+0", "Europe/London"))); From 88c1ff8708ec024521acb8e69edf897351dc2b88 Mon Sep 17 00:00:00 2001 From: "ivan.druzhinin" Date: Tue, 9 Apr 2019 15:43:30 +0300 Subject: [PATCH 10/26] [RM] Feature #52976. GUI > Environment tab > Service parameters dialog > Limit width of "Final value" column (cherry picked from commit 64bd2b7a13771f3a11492e1e7a8728a1428a3280) Change-Id: Ieda23f119e5d82b13403ef2519c34855527189fc --- FrontEnd/SailfishFrontEnd/WebContent/environment.xhtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FrontEnd/SailfishFrontEnd/WebContent/environment.xhtml b/FrontEnd/SailfishFrontEnd/WebContent/environment.xhtml index eeda3733..cdec6001 100644 --- a/FrontEnd/SailfishFrontEnd/WebContent/environment.xhtml +++ b/FrontEnd/SailfishFrontEnd/WebContent/environment.xhtml @@ -362,7 +362,7 @@ - + From b17fc80886781cbd70949baf932a43bdbc1a2401 Mon Sep 17 00:00:00 2001 From: "ivan.druzhinin" Date: Wed, 10 Apr 2019 13:13:05 +0300 Subject: [PATCH 11/26] [RM] Feature #54719. GUI > Test Scripts > show selected variable set for matrix run alongside environment, range and AML (cherry picked from commit 95767213bd22edecb5f6af98c5bf52c31173e267) Change-Id: Ifbf71fbd6fe83bf9a24f6479aa56eb7aeb479842 --- .../sf/scriptrunner/ScriptContext.java | 8 +++- .../resources/sf/css/scriptruns.css | 6 +++ .../ScriptrunEventHTMLBuilder.java | 38 +++++++++++++++++-- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java index 71fe13a9..971a5b51 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java @@ -70,6 +70,7 @@ public class ScriptContext private long scriptStartTime; private String testCaseName; private final String environmentName; + private final String environmentVariableSet; private IScriptConfig scriptConfig; private final IActionManager actionManager; private final IUtilityManager utilityManager; @@ -107,6 +108,7 @@ public ScriptContext(ISFContext context, IScriptProgress scriptProgress, IScript this.dataManager = context.getDataManager(); this.pluginClassLoaders = context.getPluginClassLoaders(); this.environmentName = environmentName; + this.environmentVariableSet = context.getConnectionManager().getEnvironmentVariableSet(environmentName); reset(); } @@ -244,7 +246,11 @@ public String getEnvironmentName() { return environmentName; } - public IScriptReport getReport() { + public String getEnvironmentVariableSet() { + return environmentVariableSet; + } + + public IScriptReport getReport() { return report; } diff --git a/FrontEnd/SailfishFrontEnd/WebContent/resources/sf/css/scriptruns.css b/FrontEnd/SailfishFrontEnd/WebContent/resources/sf/css/scriptruns.css index 783d6452..cb8a0fbc 100644 --- a/FrontEnd/SailfishFrontEnd/WebContent/resources/sf/css/scriptruns.css +++ b/FrontEnd/SailfishFrontEnd/WebContent/resources/sf/css/scriptruns.css @@ -499,6 +499,12 @@ margin-left: 15px; } +.eps-result-environment-variable-set { + display: inline-block; + width: auto; + margin-left: 15px; +} + .eps-result-report-link { display: inline-block; margin-top: 15px; diff --git a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/scriptrunner/ScriptrunEventHTMLBuilder.java b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/scriptrunner/ScriptrunEventHTMLBuilder.java index 577216c1..915c7952 100644 --- a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/scriptrunner/ScriptrunEventHTMLBuilder.java +++ b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/scriptrunner/ScriptrunEventHTMLBuilder.java @@ -18,21 +18,21 @@ import static org.apache.commons.text.StringEscapeUtils.escapeHtml4; import java.lang.reflect.InvocationTargetException; +import java.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.format.DateTimeFormatter; -import com.exactpro.sf.common.util.ErrorUtil; -import com.exactpro.sf.common.util.StringUtil; import com.exactpro.sf.aml.AMLException; import com.exactpro.sf.aml.generator.AggregateAlert; import com.exactpro.sf.aml.generator.AlertCollector; import com.exactpro.sf.aml.generator.AlertType; import com.exactpro.sf.center.ISFContext; import com.exactpro.sf.center.impl.GuiVersion; +import com.exactpro.sf.common.util.ErrorUtil; +import com.exactpro.sf.common.util.StringUtil; import com.exactpro.sf.configuration.workspace.FolderType; import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; import com.exactpro.sf.scriptrunner.EnvironmentSettings; @@ -42,8 +42,8 @@ import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptState; import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptStatus; import com.exactpro.sf.scriptrunner.ZipReport; -import com.exactpro.sf.util.DateTimeUtility; import com.exactpro.sf.testwebgui.servlets.ReportServlet; +import com.exactpro.sf.util.DateTimeUtility; public class ScriptrunEventHTMLBuilder { @@ -316,6 +316,7 @@ public static String getEmptyMessage() { private static String buildExecuted(TestScriptDescription descr, ISFContext context) { String environmentName = descr.getContext().getEnvironmentName(); + String environmentVariableSet = descr.getContext().getEnvironmentVariableSet(); String language = Objects.toString(descr.getLanguageURI(), ""); String range = descr.getRange() == null || descr.getRange().length() == 0 ? "∞" : descr.getRange(); String autoStart = descr.getAutoStart() ? "(A)" : ""; @@ -339,6 +340,10 @@ private static String buildExecuted(TestScriptDescription descr, ISFContext cont sb.append("
" + environmentName + " " + autoStart + "
"); sb.append("
" + language + "
"); sb.append("
" + range + "
"); + + if(environmentVariableSet != null) { + sb.append("
" + environmentVariableSet + "
"); + } sb.append(""); sb.append(""); @@ -366,6 +371,7 @@ private static String buildExecuted(TestScriptDescription descr, ISFContext cont private static String buildCanceled(TestScriptDescription descr) { String environmentName = descr.getContext().getEnvironmentName(); + String environmentVariableSet = descr.getContext().getEnvironmentVariableSet(); String language = Objects.toString(descr.getLanguageURI(), ""); String range = descr.getRange() == null || descr.getRange().length() == 0 ? "∞" : descr.getRange(); String autoStart = descr.getAutoStart() ? "(A)" : ""; @@ -389,6 +395,10 @@ private static String buildCanceled(TestScriptDescription descr) { sb.append("
" + environmentName + " " + autoStart + "
"); sb.append("
" + language + "
"); sb.append("
" + range + "
"); + + if(environmentVariableSet != null) { + sb.append("
" + environmentVariableSet + "
"); + } sb.append(""); sb.append(""); @@ -408,6 +418,7 @@ private static String buildCanceled(TestScriptDescription descr) { private static String buildFailed(TestScriptDescription descr, ISFContext context) { String environmentName = descr.getContext().getEnvironmentName(); + String environmentVariableSet = descr.getContext().getEnvironmentVariableSet(); String language = Objects.toString(descr.getLanguageURI(), ""); String range = descr.getRange() == null || descr.getRange().length() == 0 ? "∞" : descr.getRange(); String autoStart = descr.getAutoStart() ? "(A)" : ""; @@ -431,6 +442,10 @@ private static String buildFailed(TestScriptDescription descr, ISFContext contex sb.append("
" + environmentName + " " + autoStart + "
"); sb.append("
" + language + "
"); sb.append("
" + range + "
"); + + if(environmentVariableSet != null) { + sb.append("
" + environmentVariableSet + "
"); + } sb.append(""); sb.append(""); @@ -454,6 +469,7 @@ private static String buildFailed(TestScriptDescription descr, ISFContext contex private static String buildInProgress(TestScriptDescription descr, ISFContext context) { String environmentName = descr.getContext().getEnvironmentName(); + String environmentVariableSet = descr.getContext().getEnvironmentVariableSet(); String language = Objects.toString(descr.getLanguageURI(), ""); String range = descr.getRange() == null || descr.getRange().isEmpty() ? "∞" : descr.getRange(); String autoStart = descr.getAutoStart() ? "(A)" : ""; @@ -494,6 +510,10 @@ private static String buildInProgress(TestScriptDescription descr, ISFContext co sb.append("
" + environmentName + " " + autoStart + "
"); sb.append("
" + language + "
"); sb.append("
" + range + "
"); + + if(environmentVariableSet != null) { + sb.append("
" + environmentVariableSet + "
"); + } sb.append(""); sb.append(""); @@ -550,6 +570,7 @@ private static String formatPauseScriptLink(long id) { private static String buildPending(TestScriptDescription descr, ISFContext context) { String environmentName = descr.getContext().getEnvironmentName(); + String environmentVariableSet = descr.getContext().getEnvironmentVariableSet(); String language = Objects.toString(descr.getLanguageURI(), ""); String autoStart = descr.getAutoStart() ? "(A)" : ""; @@ -588,6 +609,10 @@ private static String buildPending(TestScriptDescription descr, ISFContext conte sb.append("
"); sb.append("
" + environmentName + " " + autoStart + "
"); sb.append("
" + language + "
"); + + if(environmentVariableSet != null) { + sb.append("
" + environmentVariableSet + "
"); + } sb.append("
"); sb.append(""); @@ -624,6 +649,7 @@ private static String buildPending(TestScriptDescription descr, ISFContext conte private static String buildPaused(TestScriptDescription descr, ISFContext context) { String environmentName = descr.getContext().getEnvironmentName(); + String environmentVariableSet = descr.getContext().getEnvironmentVariableSet(); String language = Objects.toString(descr.getLanguageURI(), ""); String autoStart = descr.getAutoStart() ? "(A)" : ""; @@ -662,6 +688,10 @@ private static String buildPaused(TestScriptDescription descr, ISFContext contex sb.append("
"); sb.append("
" + environmentName + " " + autoStart + "
"); sb.append("
" + language + "
"); + + if(environmentVariableSet != null) { + sb.append("
" + environmentVariableSet + "
"); + } sb.append("
"); sb.append(""); From b12d4cac7c2a222596b5ed5ae221f9a5bc9d3380 Mon Sep 17 00:00:00 2001 From: "oleg.smirnov" Date: Mon, 25 Mar 2019 17:12:38 +0300 Subject: [PATCH 12/26] [RM] Feature #53805. Ability to move backup files to another folder has been added * Backups for all logs file except all.log have been turned off (cherry picked from commit 2f9e60bff66041e779becc6d0fbe1468af03ad9c) Change-Id: Icf36ff634ee48cf5bec2974d77a0a83a97035a77 --- .../logging/DailyMaxRollingFileAppender.java | 89 ++++++++++++++----- .../WebContent/cfg/log.properties | 19 ++-- 2 files changed, 78 insertions(+), 30 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java index 8b694691..6b4560fc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java @@ -39,11 +39,15 @@ import java.util.Locale; import java.util.TimeZone; +import org.apache.commons.io.FileUtils; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + /** * DailyMaxRollingFileAppender extends {@link FileAppender} so that the * underlying file is rolled over at a user chosen frequency. @@ -182,6 +186,11 @@ public class DailyMaxRollingFileAppender extends FileAppender { */ private String scheduledFilename; + /** + * The folder where old files will stored + */ + private String rollingFilesFolder; + /** * The next time we estimate a rollover should occur. */ @@ -248,6 +257,22 @@ public int getMaxBackupIndex() { return maxBackupIndex; } + /** + * Returns the value of the OldFilesFolder option. + * @return + */ + public String getRollingFilesFolder() { + return rollingFilesFolder; + } + + /** + * Sets folder where old files will be stored + * @param rollingFilesFolder folder for backup files. If it's empty then backup files won't be moved + */ + public void setRollingFilesFolder(String rollingFilesFolder) { + this.rollingFilesFolder = rollingFilesFolder; + } + @Override public void activateOptions() { super.activateOptions(); @@ -261,7 +286,7 @@ public void activateOptions() { printPeriodicity(type); rpc.setType(type); File file = new File(fileName); - scheduledFilename = fileName + sdf.format(new Date(file.lastModified())); + scheduledFilename = getScheduledFilename(new Date(file.lastModified())); } else { LogLog.error("Either File or DatePattern options are not set for appender [" + name + "]."); } @@ -270,7 +295,7 @@ public void activateOptions() { void printPeriodicity(int type) { switch (type) { case TOP_OF_MINUTE: - LogLog.debug("Appender [[+name+]] to be rolled every minute."); + LogLog.debug("Appender [" + name + "] to be rolled every minute."); break; case TOP_OF_HOUR: LogLog.debug("Appender [" + name + "] to be rolled on top of every hour."); @@ -288,7 +313,7 @@ void printPeriodicity(int type) { LogLog.debug("Appender [" + name + "] to be rolled at start of every month."); break; default: - LogLog.warn("Unknown periodicity for appender [[+name+]]."); + LogLog.warn("Unknown periodicity for appender [" + name + "]."); } } @@ -335,7 +360,7 @@ void rollOver() throws IOException { return; } - String datedFilename = fileName + sdf.format(now); + String datedFilename = getScheduledFilename(now); // It is too early to roll over because we are still within the // bounds of the current interval. Rollover will occur once the // next interval is reached. @@ -346,31 +371,44 @@ void rollOver() throws IOException { // close current file, and rename it to datedFilename this.closeFile(); - File target = new File(scheduledFilename); - if (target.exists()) { - target.delete(); - } - File file = new File(fileName); - boolean result = file.renameTo(target); - if (result) { - LogLog.debug(fileName + " -> " + scheduledFilename); + // If maxBackups <= 0, then there is no file renaming to be done. + if (maxBackupIndex > 0) { + File target = new File(scheduledFilename); + if (target.exists()) { + target.delete(); + } + + boolean result = file.renameTo(target); + if (result) { + LogLog.debug(fileName + " -> " + scheduledFilename); + + if (isNotEmpty(rollingFilesFolder)) { + LogLog.debug("Move " + scheduledFilename + " to " + rollingFilesFolder); + File destFile = new File(rollingFilesFolder, target.getName()); + FileUtils.moveFile(target, destFile); + } - // If maxBackups <= 0, then there is no file renaming to be done. - if (maxBackupIndex > 0) { // Delete the oldest file, to keep Windows happy. - file = new File(fileName + dateBefore()); + if (isEmpty(rollingFilesFolder)) { + file = new File(fileName + dateBefore()); + } else { + file = new File(rollingFilesFolder, file.getName() + dateBefore()); + } if (file.exists()) file.delete(); // this function invocation has been added to original file deleteOldFiles(); - + } else { + LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "]."); } } else { - LogLog.error("Failed to rename [[+fileName+]] to [[+scheduledFilename+]]."); + if (!file.delete()) { + LogLog.error("Can't delete current file: " + fileName); + } } try { @@ -386,7 +424,13 @@ void rollOver() throws IOException { // this function has been added to original file private void deleteOldFiles() { File file = new File(fileName); - File parent = file.getParentFile(); + + File parent; + if (isEmpty(rollingFilesFolder)) { + parent = file.getParentFile(); + } else { + parent = new File(rollingFilesFolder); + } String simpleFileName = file.getName(); File[] nestedFiles = parent.listFiles(); @@ -400,8 +444,7 @@ private void deleteOldFiles() { && elemSimpleName.length() == (datePattern.length() - 2 + simpleFileName.length())) { SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); - String dateSuffix = elemSimpleName.substring( - elemSimpleName.length() - datePattern.length() + 2, elemSimpleName.length()); + String dateSuffix = elemSimpleName.substring(elemSimpleName.length() - datePattern.length() + 2); try { Date elemDate = dateFormat.parse(dateSuffix); if(oldestTimeInMillis > elemDate.getTime()) { @@ -451,10 +494,14 @@ protected void subAppend(LoggingEvent event) { super.subAppend(event); } + private String getScheduledFilename(Date date) { + return fileName + sdf.format(date); + } + /* * DEBUG */ - public static void main(String args[]) { + public static void main(String[] args) { DailyMaxRollingFileAppender dmrfa = new DailyMaxRollingFileAppender(); dmrfa.setDatePattern("'.'yyyy-MM-dd-HH-mm"); diff --git a/FrontEnd/SailfishFrontEnd/WebContent/cfg/log.properties b/FrontEnd/SailfishFrontEnd/WebContent/cfg/log.properties index 29e8ccf0..23d3b2f8 100644 --- a/FrontEnd/SailfishFrontEnd/WebContent/cfg/log.properties +++ b/FrontEnd/SailfishFrontEnd/WebContent/cfg/log.properties @@ -2,13 +2,14 @@ log4j.rootLogger=INFO, ALLFILEAPP log4j.appender.ALLFILEAPP=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.ALLFILEAPP.File=${sf.log.dir}/all.log log4j.appender.ALLFILEAPP.DatePattern='.'yyyy-MM-dd +log4j.appender.ALLFILEAPP.RollingFilesFolder=${sf.log.dir}/old log4j.appender.ALLFILEAPP.MaxBackupIndex=3 log4j.appender.ALLFILEAPP.layout=org.apache.log4j.PatternLayout log4j.appender.ALLFILEAPP.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.LOGFILE=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.LOGFILE.File=${sf.log.dir}/sailfish.log log4j.appender.LOGFILE.DatePattern='.'yyyy-MM-dd -log4j.appender.LOGFILE.MaxBackupIndex=3 +log4j.appender.LOGFILE.MaxBackupIndex=0 log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n @@ -16,7 +17,7 @@ log4j.appender.ERRFILE=com.exactpro.sf.common.logging.DailyMaxRollingFileAppende log4j.appender.ERRFILE.Threshold=ERROR log4j.appender.ERRFILE.File=${sf.log.dir}/sailfish.err log4j.appender.ERRFILE.DatePattern='.'yyyy-MM-dd -log4j.appender.ERRFILE.MaxBackupIndex=3 +log4j.appender.ERRFILE.MaxBackupIndex=0 log4j.appender.ERRFILE.Append=true log4j.appender.ERRFILE.layout=org.apache.log4j.PatternLayout log4j.appender.ERRFILE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n @@ -32,49 +33,49 @@ log4j.appender.CON.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [% log4j.appender.SCRIPTRUNFILE=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.SCRIPTRUNFILE.File=${sf.log.dir}/scriptrunner.log log4j.appender.SCRIPTRUNFILE.DatePattern='.'yyyy-MM-dd -log4j.appender.SCRIPTRUNFILE.MaxBackupIndex=3 +log4j.appender.SCRIPTRUNFILE.MaxBackupIndex=0 log4j.appender.SCRIPTRUNFILE.Append=true log4j.appender.SCRIPTRUNFILE.layout=org.apache.log4j.PatternLayout log4j.appender.SCRIPTRUNFILE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.WEBSERVFILE=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.WEBSERVFILE.File=${sf.log.dir}/webserver.log log4j.appender.WEBSERVFILE.DatePattern='.'yyyy-MM-dd -log4j.appender.WEBSERVFILE.MaxBackupIndex=3 +log4j.appender.WEBSERVFILE.MaxBackupIndex=0 log4j.appender.WEBSERVFILE.Append=true log4j.appender.WEBSERVFILE.layout=org.apache.log4j.PatternLayout log4j.appender.WEBSERVFILE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.HIBERNATE=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.HIBERNATE.File=${sf.log.dir}/hibernate.log log4j.appender.HIBERNATE.DatePattern='.'yyyy-MM-dd -log4j.appender.HIBERNATE.MaxBackupIndex=3 +log4j.appender.HIBERNATE.MaxBackupIndex=0 log4j.appender.HIBERNATE.Append=true log4j.appender.HIBERNATE.layout=org.apache.log4j.PatternLayout log4j.appender.HIBERNATE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.HIBERNATESQL=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.HIBERNATESQL.File=${sf.log.dir}/hibernateSQL.log log4j.appender.HIBERNATESQL.DatePattern='.'yyyy-MM-dd -log4j.appender.HIBERNATESQL.MaxBackupIndex=3 +log4j.appender.HIBERNATESQL.MaxBackupIndex=0 log4j.appender.HIBERNATESQL.Append=true log4j.appender.HIBERNATESQL.layout=org.apache.log4j.PatternLayout log4j.appender.HIBERNATESQL.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.PROFILER=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.PROFILER.File=${sf.log.dir}/profiler.log log4j.appender.PROFILER.DatePattern='.'yyyy-MM-dd -log4j.appender.PROFILER.MaxBackupIndex=3 +log4j.appender.PROFILER.MaxBackupIndex=0 log4j.appender.PROFILER.Append=true log4j.appender.PROFILER.layout=org.apache.log4j.PatternLayout log4j.appender.PROFILER.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.WEBGUI=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.WEBGUI.File=${sf.log.dir}/webgui.log log4j.appender.WEBGUI.DatePattern='.'yyyy-MM-dd -log4j.appender.WEBGUI.MaxBackupIndex=3 +log4j.appender.WEBGUI.MaxBackupIndex=0 log4j.appender.WEBGUI.Append=false log4j.appender.WEBGUI.layout=org.apache.log4j.PatternLayout log4j.appender.WEBGUI.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n log4j.appender.STATISTICS=com.exactpro.sf.common.logging.DailyMaxRollingFileAppender log4j.appender.STATISTICS.File=${sf.log.dir}/statistics.log log4j.appender.STATISTICS.DatePattern='.'yyyy-MM-dd -log4j.appender.STATISTICS.MaxBackupIndex=3 +log4j.appender.STATISTICS.MaxBackupIndex=0 log4j.appender.STATISTICS.layout=org.apache.log4j.PatternLayout log4j.appender.STATISTICS.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-6p [%-15t] %c - %m%n From 459664493c8e22952e88252307adcee37e844574 Mon Sep 17 00:00:00 2001 From: "nikita.smirnov" Date: Thu, 12 Apr 2018 17:07:25 +0300 Subject: [PATCH 13/26] Bug #48814. Logging > Execute automatic reloading log.properties from workspce (cherry picked from commit 8eb36c0e5d8792002ac208d8cdd9274b6e55c66d) Change-Id: I355912c87d89bbdbbf7695678e6c4fb2cc7faafc --- .../exactpro/sf/center/impl/PluginLoader.java | 2 +- .../sf/testwebgui/SFWebApplication.java | 2 +- .../servlets/CustomPropertyConfigurator.java | 75 ++++++++++++++----- .../testwebgui/servlets/SFContextServlet.java | 5 +- 4 files changed, 61 insertions(+), 23 deletions(-) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java index f2b83e47..514793c9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java @@ -64,6 +64,7 @@ public class PluginLoader { private static final Logger logger = LoggerFactory.getLogger(PluginLoader.class); private final Logger userEventsLogger = LoggerFactory.getLogger("USER_EVENTS_LOG"); + public static final String LOG4J_PROPERTIES_FILE_NAME = "log.properties"; public static final String CUSTOM_DICTIONARIES_XML = "custom_dictionaries.xml"; public static final String VERSION_FILE_NAME = "VERSION"; @@ -74,7 +75,6 @@ public class PluginLoader { protected static final String VALIDATORS_XML_FILE_NAME = "validators.xml"; protected static final String ADAPTERS_XML_FILE_NAME = "adapters.xml"; protected static final String DATA_XML_FILE_NAME = "data.xml"; - protected static final String LOG4J_PROPERTIES_FILE_NAME = "log.properties"; protected static final String SERVICES_FOLDER_NAME = "services"; private final IWorkspaceDispatcher wd; diff --git a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/SFWebApplication.java b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/SFWebApplication.java index 522ad6a9..3c6d9bb1 100644 --- a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/SFWebApplication.java +++ b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/SFWebApplication.java @@ -61,7 +61,7 @@ public static SFWebApplication getInstance() { return instance; } - public void init(String logFilePath, ISFContext context) { + public void init(ISFContext context) { logger.debug("init() invoked"); diff --git a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/CustomPropertyConfigurator.java b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/CustomPropertyConfigurator.java index 550bda28..f8e52f1f 100644 --- a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/CustomPropertyConfigurator.java +++ b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/CustomPropertyConfigurator.java @@ -15,9 +15,18 @@ ******************************************************************************/ package com.exactpro.sf.testwebgui.servlets; +import java.io.File; +import java.io.FileNotFoundException; + import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.FileWatchdog; +import org.apache.log4j.helpers.LogLog; + +import com.exactpro.sf.center.impl.PluginLoader; +import com.exactpro.sf.configuration.workspace.FolderType; +import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; +import com.exactpro.sf.configuration.workspace.WorkspaceSecurityException; /** * PropertyConfigurator is able to stopWatch to clean up its threads @@ -26,9 +35,8 @@ public class CustomPropertyConfigurator extends PropertyConfigurator { private static CustomPropertyWatchdog pdog; - public static void configureAndWatch(String configFileName) { - pdog = new CustomPropertyWatchdog(configFileName); - pdog.setDelay(FileWatchdog.DEFAULT_DELAY); + public static void configureAndWatch(IWorkspaceDispatcher workspaceDispatcher) { + pdog = new CustomPropertyWatchdog(workspaceDispatcher); pdog.start(); } @@ -36,33 +44,64 @@ public static void stopWatch() { pdog.interrupt(); } + private static class CustomPropertyWatchdog extends Thread { - private static class CustomPropertyWatchdog extends FileWatchdog { - - private volatile boolean customInterrupted = false; - - public CustomPropertyWatchdog(String configFileName) { - super(configFileName); - } + private final IWorkspaceDispatcher workspaceDispatcher; + /** + * The delay to observe between every check. By default set @ + * {@link FileWatchdog#DEFAULT_DELAY}. + */ + protected volatile long delay = 1000;//FileWatchdog.DEFAULT_DELAY; - @Override - protected void doOnChange() { - new PropertyConfigurator().doConfigure(filename, - LogManager.getLoggerRepository()); + private long lastModif = 0; + private boolean warnedAlready = false; + private boolean interrupted = false; + public CustomPropertyWatchdog(IWorkspaceDispatcher workspaceDispatcher) { + super("CustomPropertyWatchdog"); + setDaemon(true); + this.workspaceDispatcher = workspaceDispatcher; + checkAndConfigure(); } @Override public void run() { - while(!customInterrupted) { + while (!interrupted) { try { Thread.sleep(delay); - } catch(InterruptedException e) { - customInterrupted = true; + checkAndConfigure(); + } catch (InterruptedException e) { + interrupted = true; return; } - checkAndConfigure(); } } + + protected void checkAndConfigure() { + try { + File file = workspaceDispatcher.getFile(FolderType.CFG, PluginLoader.LOG4J_PROPERTIES_FILE_NAME); + long l = file.lastModified(); + if (l > lastModif) { + lastModif = l; + doOnChange(file); + warnedAlready = false; + } + } catch (SecurityException | WorkspaceSecurityException e) { + LogLog.warn("Was not allowed to read check file existance, file:[" + + PluginLoader.LOG4J_PROPERTIES_FILE_NAME + "].", e); + interrupted = true; + } catch (FileNotFoundException e) { + if (!warnedAlready) { + LogLog.debug("[" + PluginLoader.LOG4J_PROPERTIES_FILE_NAME + "] does not exist.", e); + warnedAlready = true; + } + } + } + + protected void doOnChange(File file) { + new PropertyConfigurator().doConfigure(file.getAbsolutePath(), + LogManager.getLoggerRepository()); + + } } } diff --git a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/SFContextServlet.java b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/SFContextServlet.java index 5fda22f6..5bd097e8 100644 --- a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/SFContextServlet.java +++ b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/servlets/SFContextServlet.java @@ -330,8 +330,7 @@ public void init(ServletConfig config) throws ServletException { File sfLogDir = wd.createFolder(FolderType.LOGS, ""); System.setProperty("sf.log.dir", sfLogDir.getAbsolutePath()); - File fullLogConfig = wd.getFile(FolderType.CFG, "log.properties"); - CustomPropertyConfigurator.configureAndWatch(fullLogConfig.getAbsolutePath()); + CustomPropertyConfigurator.configureAndWatch(wd); if (logger.isInfoEnabled()) { logger.info("Sailfish {}", new CoreVersion()); @@ -384,7 +383,7 @@ protected Transformer createTransformer() throws TransformerException { } // ---------- Global singleton init - SFWebApplication.getInstance().init(fullLogConfig.getAbsolutePath(), sfLocalContext); + SFWebApplication.getInstance().init(sfLocalContext); FacesContext.getCurrentInstance() .getExternalContext() From 610902663a76ee85a8cb406ce54df1a17a40343c Mon Sep 17 00:00:00 2001 From: "ivan.smetanin" Date: Mon, 8 Apr 2019 18:41:42 +0400 Subject: [PATCH 14/26] [RM] Feature #54674. optimized stats per tags query. (cherry picked from commit 58e81796c65b6dcc112abd3661329a70c20fb7c4) Change-Id: I421bd0cc04453aec8e9e68f00196fa13428fea76 --- .../embedded/statistics/StatisticsUtils.java | 7 +- .../storage/AbstractTagGroupQueryBuilder.java | 253 ++++++++++++++++++ .../storage/MySqlTagGroupQueryBuilder.java | 29 ++ .../storage/NativeDbOperations.java | 215 ++++----------- .../statistics/storage/NativeQueryUtil.java | 54 ++++ .../storage/PostgresTagGroupQueryBuilder.java | 29 ++ .../storage/StatisticsReportingStorage.java | 41 ++- .../pg/migration/V3.4__matrixruns_indexes.sql | 2 + 8 files changed, 456 insertions(+), 174 deletions(-) create mode 100644 BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AbstractTagGroupQueryBuilder.java create mode 100644 BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/MySqlTagGroupQueryBuilder.java create mode 100644 BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeQueryUtil.java create mode 100644 BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/PostgresTagGroupQueryBuilder.java create mode 100644 BackEnd/Core/sailfish-core/src/main/resources/com/exactpro/sf/statistics/storage/pg/migration/V3.4__matrixruns_indexes.sql diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java index 124819ad..7c58d108 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java @@ -117,12 +117,7 @@ public static List generateTagGroupReportResults(Statistic List dimensions, TagGroupReportParameters params) { setDimensionParameters(dimensions, params); - List results = new ArrayList<>(); - for(int i =0; i < dimensions.size(); i++) { - params.setLoadForLevel(i); - results.add(statisticsService.getReportingStorage().generateTagGroupReport(params)); - } - return results; + return statisticsService.getReportingStorage().generateTagGroupReport(params, dimensions); } public static void writeTagGroupReportToCsv(OutputStream outputStream, List results) throws IOException { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AbstractTagGroupQueryBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AbstractTagGroupQueryBuilder.java new file mode 100644 index 00000000..9c1cdffd --- /dev/null +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AbstractTagGroupQueryBuilder.java @@ -0,0 +1,253 @@ +/****************************************************************************** + * Copyright (c) 2009-2019, Exactpro Systems LLC + * www.exactpro.com + * Build Software to Test Software + * + * All rights reserved. + * This is unpublished, licensed software, confidential and proprietary + * information which is the property of Exactpro Systems LLC or its licensors. + ******************************************************************************/ +package com.exactpro.sf.embedded.statistics.storage; + +import com.exactpro.sf.embedded.statistics.entities.SfInstance; +import com.exactpro.sf.scriptrunner.StatusType; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.text.StringSubstitutor; +import org.hibernate.type.BigDecimalType; +import org.hibernate.type.IntegerType; +import org.hibernate.type.LongType; +import org.hibernate.type.Type; + +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static com.exactpro.sf.embedded.statistics.storage.NativeQueryUtil.TAG_GROUP_TEMP_TABLE; + +public abstract class AbstractTagGroupQueryBuilder implements Cloneable { + + public static final Map FIELD_NAMES_AND_TYPES = new ImmutableMap.Builder() + .put("total_exec_time", LongType.INSTANCE) + .put("total_tcs", LongType.INSTANCE) + .put("passed_tcs", LongType.INSTANCE) + .put("conditionally_passed_tcs", LongType.INSTANCE) + .put("failed_tcs", LongType.INSTANCE) + .put("passed_percent", BigDecimalType.INSTANCE) + .put("conditionally_passed_percent", BigDecimalType.INSTANCE) + .put("failed_percent", BigDecimalType.INSTANCE) + .put("total_matrixruns", IntegerType.INSTANCE) + .put("failed_matrices", IntegerType.INSTANCE) + .build(); + + private static final ThreadLocal TIMESTAMP_FORMAT = ThreadLocal.withInitial( + () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); + + private static final String MAIN_QUERY_PATTERN = + " SELECT " + + " ${dimensions} " + + " sum(CASE WHEN TCR.rank = 1 THEN ${totalTimeField} ELSE 0 END) AS total_exec_time, " + + " count(DISTINCT TCR.id) AS total_tcs, " + + " sum(CASE WHEN TCR.status = ${passed} THEN 1 ELSE 0 END) AS passed_tcs, " + + " sum(CASE WHEN TCR.status = ${conditionallyPassed} THEN 1 ELSE 0 END) AS conditionally_passed_tcs, " + + " sum(CASE WHEN TCR.status = ${failed} THEN 1 ELSE 0 END) AS failed_tcs, " + + " CASE WHEN (count(TCR.id) <> 0) THEN (sum(CASE WHEN TCR.status = ${passed} THEN 1.0 ELSE 0.0 END) / count(DISTINCT TCR.id) * 100) ELSE 0.0 END AS passed_percent, " + + " CASE WHEN (count(TCR.id) <> 0) THEN (sum(CASE WHEN TCR.status = ${conditionallyPassed} THEN 1.0 ELSE 0.0 END) / count(distinct TCR.id) * 100) ELSE 0.0 END AS conditionally_passed_percent, " + + " CASE WHEN (count(TCR.id) <> 0) THEN (sum(CASE WHEN TCR.status = ${failed} THEN 1.0 ELSE 0.0 END) / count(DISTINCT TCR.id) * 100) ELSE 0.0 END AS failed_percent, " + + " count(DISTINCT MR.id) AS total_matrixruns, " + + " sum(CASE WHEN MR.failReason IS NULL THEN 0 ELSE 1 END) as failed_matrices " + + " FROM (" + + " SELECT " + + " ${nestedResultIds}, " + + " ${nestedDimensions}" + + " FROM ${tempTable}" + + " ${nestedJoinTables}" + + " GROUP BY ${nestedGroupFields}" + + " HAVING COUNT(DISTINCT(${tempTable}.group_id))= ${groupCount}" + + " ) as filtered " + + " ${joinTables} " + + " ${where} " + + "GROUP BY ${groupFields} " + + "ORDER BY ${orderFields}"; + + private static final String NESTED_MATRIX_RUN_IDS = TAG_GROUP_TEMP_TABLE + ".mr_id as mr_id"; + private static final String NESTED_TESTCASE_RUN_IDS = TAG_GROUP_TEMP_TABLE + ".tcr_id as tcr_id"; + private static final String NESTED_ALL_RUN_IDS = + " CASE WHEN " + TAG_GROUP_TEMP_TABLE + ".mr_id IS NULL THEN TCR.matrix_run_id ELSE " + + TAG_GROUP_TEMP_TABLE +".mr_id END as mr_id," + + " TCR.id as tcr_id"; + + private static final String NESTED_JOIN_TABLES = "LEFT JOIN sttestcaseruns AS TCR ON " + TAG_GROUP_TEMP_TABLE + + ".mr_id = TCR.matrix_run_id or "+ TAG_GROUP_TEMP_TABLE + ".tcr_id = TCR.id"; + + private static final String JOIN_TABLES_FOR_MATRIX_RUN_IDS = + " JOIN stmatrixruns MR ON filtered.mr_id = MR.id" + + " LEFT JOIN sttestcaseruns TCR ON MR.id = TCR.matrix_run_id"; + + private static final String JOIN_TABLES_FOR_TESTCASE_RUN_IDS = + " JOIN sttestcaseruns TCR ON TCR.id = filtered.tcr_id" + + " JOIN stmatrixruns MR ON MR.id = TCR.matrix_run_id"; + + private static final String JOIN_TABLES_FOR_ALL_RUN_IDS = + " JOIN stmatrixruns MR ON filtered.mr_id = MR.id" + + " LEFT JOIN sttestcaseruns TCR ON filtered.tcr_id = TCR.id"; + + private JoinType joinType = JoinType.TEST_CASE_AND_MATRIX_RUN_TAGS; + + private String dimensions; + private String nestedDimensions; + private String groupFields; + private String orderFields; + private String groupCount; + private Date from; + private Date to; + private List sfInstances; + + protected abstract String getTotalTimeField(); + protected abstract String formatTimestamp(String value); + public abstract AbstractTagGroupQueryBuilder clone(); + + public AbstractTagGroupQueryBuilder setJoinType(JoinType joinType) { + this.joinType = joinType; + return this; + } + + public AbstractTagGroupQueryBuilder setDimensions(String dimensions) { + this.dimensions = dimensions; + return this; + } + + public AbstractTagGroupQueryBuilder setNestedDimensions(String nestedDimensions) { + this.nestedDimensions = nestedDimensions; + return this; + } + + public AbstractTagGroupQueryBuilder setGroupFields(String groupFields) { + this.groupFields = groupFields; + return this; + } + + public AbstractTagGroupQueryBuilder setOrderFields(String orderFields) { + this.orderFields = orderFields; + return this; + } + + public AbstractTagGroupQueryBuilder setGroupCount(String groupCount) { + this.groupCount = groupCount; + return this; + } + + public AbstractTagGroupQueryBuilder setFrom(Date from) { + this.from = from; + return this; + } + + public AbstractTagGroupQueryBuilder setTo(Date to) { + this.to = to; + return this; + } + + public AbstractTagGroupQueryBuilder setSfInstances(List sfInstances) { + this.sfInstances = sfInstances; + return this; + } + + public String build() { + Map variables = new HashMap<>(); + variables.put("tempTable", TAG_GROUP_TEMP_TABLE); + variables.put("dimensions", dimensions); + variables.put("passed", String.valueOf(StatusType.PASSED.getId())); + variables.put("conditionallyPassed", String.valueOf(StatusType.CONDITIONALLY_PASSED.getId())); + variables.put("failed", String.valueOf(StatusType.FAILED.getId())); + variables.put("nestedDimensions", nestedDimensions); + variables.put("totalTimeField", getTotalTimeField()); + variables.put("nestedResultIds", joinType.nestedResultFields); + variables.put("nestedJoinTables", joinType.nestedJoinTables); + variables.put("nestedGroupFields", joinType.nestedGroupFields); + variables.put("joinTables", joinType.resultJoinTables); + variables.put("where", buildWhereClause()); + variables.put("groupCount", groupCount); + variables.put("groupFields", groupFields); + variables.put("orderFields", orderFields); + return new StringSubstitutor(variables).replace(MAIN_QUERY_PATTERN); + } + + protected void cloneTo(AbstractTagGroupQueryBuilder clone) { + clone.setDimensions(dimensions); + clone.setNestedDimensions(nestedDimensions); + clone.setGroupFields(groupFields); + clone.setOrderFields(orderFields); + clone.setGroupCount(groupCount); + clone.setJoinType(joinType); + if (sfInstances != null) { + clone.setSfInstances(Collections.unmodifiableList(sfInstances)); + } + if (from != null) { + clone.setFrom(new Date(from.getTime())); + } + if (to != null) { + clone.setTo(new Date(to.getTime())); + } + } + + private String buildWhereClause() { + StringBuilder whereBuilder = new StringBuilder(); + if (this.from != null) { + addTimestamp(whereBuilder, from, "starttime", ">="); + } + if (this.to != null) { + addTimestamp(whereBuilder, to, "finishtime", "<="); + } + if (CollectionUtils.isNotEmpty(sfInstances)) { + String sfIds = sfInstances.stream() + .map(sfInstance -> String.valueOf(sfInstance.getId())) + .collect(Collectors.joining(",")); + appendWhereAnd(whereBuilder); + whereBuilder.append("MR.sf_id IN (") + .append(sfIds) + .append(") "); + } + return whereBuilder.toString(); + } + + private void addTimestamp(StringBuilder whereBuilder, Date timestamp, String fieldName, String operation) { + appendWhereAnd(whereBuilder); + String value = TIMESTAMP_FORMAT.get().format(timestamp); + whereBuilder.append("MR.") + .append(fieldName) + .append(" ") + .append(operation) + .append(" ") + .append(formatTimestamp(value)); + } + + private void appendWhereAnd(StringBuilder whereBuilder) { + if (whereBuilder.length() == 0) { + whereBuilder.append(" WHERE "); + } else { + whereBuilder.append(" AND "); + } + } + + public enum JoinType { + TEST_CASE_RUN_TAGS (NESTED_TESTCASE_RUN_IDS, JOIN_TABLES_FOR_TESTCASE_RUN_IDS, "", "1"), + MATRIX_RUN_TAGS (NESTED_MATRIX_RUN_IDS, JOIN_TABLES_FOR_MATRIX_RUN_IDS, "", "1"), + TEST_CASE_AND_MATRIX_RUN_TAGS (NESTED_ALL_RUN_IDS, JOIN_TABLES_FOR_ALL_RUN_IDS, NESTED_JOIN_TABLES, "1,2"); + + private final String nestedResultFields; + private final String resultJoinTables; + private final String nestedJoinTables; + private final String nestedGroupFields; + + JoinType(String nestedResultFields, String resultJoinTables, String nestedJoinTables, String nestedGroupFields) { + this.nestedResultFields = nestedResultFields; + this.resultJoinTables = resultJoinTables; + this.nestedJoinTables = nestedJoinTables; + this.nestedGroupFields = nestedGroupFields; + } + } +} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/MySqlTagGroupQueryBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/MySqlTagGroupQueryBuilder.java new file mode 100644 index 00000000..6c7d19ba --- /dev/null +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/MySqlTagGroupQueryBuilder.java @@ -0,0 +1,29 @@ +/****************************************************************************** + * Copyright (c) 2009-2019, Exactpro Systems LLC + * www.exactpro.com + * Build Software to Test Software + * + * All rights reserved. + * This is unpublished, licensed software, confidential and proprietary + * information which is the property of Exactpro Systems LLC or its licensors. + ******************************************************************************/ +package com.exactpro.sf.embedded.statistics.storage; + +public class MySqlTagGroupQueryBuilder extends AbstractTagGroupQueryBuilder { + @Override + protected String getTotalTimeField() { + return "TIMESTAMPDIFF(SECOND, MR.startTime, MR.finishTime)"; + } + + @Override + protected String formatTimestamp(String value) { + return " '" + value + "' "; + } + + @Override + public MySqlTagGroupQueryBuilder clone() { + MySqlTagGroupQueryBuilder clone = new MySqlTagGroupQueryBuilder(); + cloneTo(clone); + return clone; + } +} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java index deba0ebc..49083a56 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java @@ -16,37 +16,37 @@ package com.exactpro.sf.embedded.statistics.storage; import java.math.BigDecimal; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Date; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; +import com.exactpro.sf.embedded.statistics.storage.AbstractTagGroupQueryBuilder.JoinType; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ObjectArrays; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.time.DurationFormatUtils; +import org.apache.commons.lang3.tuple.Pair; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; -import org.hibernate.type.BigDecimalType; import org.hibernate.type.BigIntegerType; import org.hibernate.type.IntegerType; -import org.hibernate.type.LongType; import org.hibernate.type.StringType; import org.hibernate.type.TimestampType; +import org.hibernate.type.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.exactpro.sf.embedded.statistics.configuration.DbmsType; import com.exactpro.sf.embedded.statistics.storage.reporting.TagGroupDimension; import com.exactpro.sf.embedded.statistics.storage.reporting.TagGroupReportParameters; import com.exactpro.sf.embedded.statistics.storage.reporting.TagGroupReportResult; import com.exactpro.sf.embedded.statistics.storage.reporting.TagGroupReportRow; import com.exactpro.sf.embedded.storage.HibernateStorageSettings; -import com.exactpro.sf.scriptrunner.StatusType; + +import static com.exactpro.sf.embedded.statistics.storage.NativeQueryUtil.*; public class NativeDbOperations { @@ -56,9 +56,6 @@ public class NativeDbOperations { private static final String DURATION_FORMAT = "HH:mm:ss"; - private static final ThreadLocal TIMESTAMP_FORMAT = ThreadLocal.withInitial( - () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); - private static final String FILTERED_NAME = "filtered"; private HibernateStorageSettings settings; @@ -67,18 +64,6 @@ public NativeDbOperations(HibernateStorageSettings settings) { this.settings = settings; } - private boolean isMysql() { - - return this.settings.getDbms().equals(DbmsType.MySql.getValue()); - - } - - private boolean isPostgreSql() { - - return this.settings.getDbms().equals(DbmsType.PostgreSQL.getValue()); - - } - private String toMysqlSet(Long[] ids) { StringBuilder sb = new StringBuilder(); @@ -123,7 +108,7 @@ public List executeTaggedComparisonQuery(Session session, Long[] first Long[] allTags = ImmutableSet.copyOf(ObjectArrays.concat(firstSetIds, secondSetIds, Long.class)) .toArray(new Long[0]); - if(isPostgreSql()) { + if(isPostgreSql(this.settings.getDbms())) { String queryString = String.format("SELECT * FROM tagged_sets_comparison(ARRAY %s, ARRAY %s, :fcount, ARRAY %s, :scount )", Arrays.toString(allTags), Arrays.toString(firstSetIds), Arrays.toString(secondSetIds)); @@ -135,7 +120,7 @@ public List executeTaggedComparisonQuery(Session session, Long[] first return query.list(); - } else if(isMysql()) { + } else if(isMysql(this.settings.getDbms())) { String queryString = String.format("call tagged_sets_comparison('%s', '%s', :fcount, '%s', :scount )", toMysqlSet(allTags), toMysqlSet(firstSetIds), toMysqlSet(secondSetIds)); @@ -204,12 +189,8 @@ public List executeTaggedComparisonQuery(Session session, Long[] first } - /*private String buildTagGroupSqlQuery(TagGroupReportParameters params) { - - }*/ - private String buildDimensionPostfix(TagGroupDimension dimension, int index) { - String delimiter = isPostgreSql() + String delimiter = isPostgreSql(this.settings.getDbms()) ? "\"" : "`"; return delimiter + dimension.getName() + DIMENSION_NAME_POSTFIX + index + delimiter; @@ -260,11 +241,9 @@ private String buildDimensionFilter(TagGroupReportParameters params, boolean isP sb.append("'").append(dimension.getName()).append("'"); } } else { - sb.append(" MAX(CASE WHEN (MG.id = ") - .append(dimension.getId()) - .append(") THEN MT.name ELSE CASE WHEN (TCG.id = ") + sb.append(" MAX(CASE WHEN (" + TAG_GROUP_TEMP_TABLE + ".group_id = ") .append(dimension.getId()) - .append(") THEN TCT.name ELSE NULL END END)"); + .append(") THEN " + TAG_GROUP_TEMP_TABLE + ".tag_name ELSE NULL END) "); } sb.append(" AS d").append(i); if (i < params.getLoadForLevel() ) { @@ -317,13 +296,13 @@ private List parseTagGroupResultSet(List rs, TagGro } @SuppressWarnings("unchecked") - public TagGroupReportResult generateTagGroupReport(Session session, TagGroupReportParameters params) { + public TagGroupReportResult generateTagGroupReport(Session session, TagGroupReportParameters params, + AbstractTagGroupQueryBuilder queryBuilder) { - boolean isPostgres = isPostgreSql(); + boolean isPostgres = isPostgreSql(this.settings.getDbms()); TagGroupReportResult result = new TagGroupReportResult(); - StringBuilder queryBuilder = new StringBuilder(); List groupingColumns = new ArrayList<>(); for(int i = 0; i<= params.getLoadForLevel(); i++) { @@ -332,145 +311,69 @@ public TagGroupReportResult generateTagGroupReport(Session session, TagGroupRepo } - // Build query - - queryBuilder.append("SELECT "); - boolean dimensionsExist = isDimensionsExist(params); + String groupingColumnsString = toMysqlSet(groupingColumns); - queryBuilder.append(dimensionsExist ? buildDimensionFilteredColumns(params) : buildDimensionTagsColumns(params)); - - String execTimeCalc; - - if(isPostgres) { + queryBuilder.setDimensions(dimensionsExist + ? buildDimensionFilteredColumns(params) + : buildDimensionTagsColumns(params)) + .setNestedDimensions(buildDimensionFilter(params, isPostgres)) + .setGroupCount(String.valueOf(params.getNumberOfGroups())) + .setGroupFields(groupingColumnsString) + .setOrderFields(groupingColumnsString) + .setFrom(params.getFrom()) + .setTo(params.getTo()) + .setSfInstances(params.getSelectedSfInstances()); - execTimeCalc = "CASE WHEN TCR.rank = 1 THEN extract ('epoch' from MR.finishTime - MR.startTime) ELSE 0 END"; + String stringQuery = queryBuilder.build(); - } else { // Mysql + logger.debug(stringQuery); - execTimeCalc = "CASE WHEN TCR.rank = 1 THEN TIMESTAMPDIFF(SECOND, MR.startTime, MR.finishTime) ELSE 0 END"; + SQLQuery query = session.createSQLQuery(stringQuery); - } - - queryBuilder.append("sum("); - - queryBuilder.append(execTimeCalc); - - queryBuilder.append(") AS total_exec_time, " + "count(DISTINCT TCR.id) AS total_tcs, " - + "sum(CASE WHEN TCR.status = " + StatusType.PASSED.getId() + " THEN 1 ELSE 0 END) AS passed_tcs, " - + "sum(CASE WHEN TCR.status = " + StatusType.CONDITIONALLY_PASSED.getId() + " THEN 1 ELSE 0 END) AS conditionally_passed_tcs, " - + "sum(CASE WHEN TCR.status = " + StatusType.FAILED.getId() + " THEN 1 ELSE 0 END) AS failed_tcs, " - - + "CASE WHEN (count(TCR.id) <> 0) THEN (sum(CASE WHEN TCR.status = " + StatusType.PASSED.getId() + " THEN 1.0 ELSE 0.0 END) / count(DISTINCT TCR.id) * 100) ELSE 0.0 END AS passed_percent, " - + "CASE WHEN (count(TCR.id) <> 0) THEN (sum(CASE WHEN TCR.status = " + StatusType.CONDITIONALLY_PASSED.getId() + " THEN 1.0 ELSE 0.0 END) / count(distinct TCR.id) * 100) ELSE 0.0 END AS conditionally_passed_percent, " - + "CASE WHEN (count(TCR.id) <> 0) THEN (sum(CASE WHEN TCR.status = " + StatusType.FAILED.getId() + " THEN 1.0 ELSE 0.0 END) / count(DISTINCT TCR.id) * 100) ELSE 0.0 END AS failed_percent, " - + "count(DISTINCT MR.id) AS total_matrixruns, " - + "sum(CASE WHEN MR.failReason IS NULL THEN 0 ELSE 1 END) as failed_matrices "); - - if (dimensionsExist) { - String tagIds = "(" + toMysqlSet(params.getTagIds()) + ")"; - queryBuilder.append(" FROM (SELECT MR.id as m_id, TCR.id as tc_id, ") - .append(buildDimensionFilter(params, isPostgres)) - .append(" FROM stmatrixruns MR ") - .append(" LEFT JOIN sttestcaseruns TCR ON MR.id = TCR.matrix_run_id") - .append(" LEFT JOIN stmrtags AS MRTS ON MRTS.mr_id = MR.id ") - .append(" LEFT JOIN sttcrtags AS TCRTS ON TCRTS.tcr_id = TCR.id ") - .append(" LEFT JOIN sttags AS MT ON MRTS.tag_id = MT.id ") - .append(" LEFT JOIN sttaggroups MG ON MT.group_id = MG.id ") - .append(" LEFT JOIN sttags AS TCT ON TCRTS.tag_id = TCT.id ") - .append(" LEFT JOIN sttaggroups TCG ON TCT.group_id = TCG.id ") - .append(" WHERE ( (MRTS.tag_id IN ") - .append(tagIds) - .append(" OR TCRTS.tag_id IN ") - .append(tagIds) - .append(") "); - - applyTimestampAndSfInstances(params, queryBuilder, "MR"); - - queryBuilder.append(") GROUP BY 1,2 ") - .append(" HAVING COUNT(DISTINCT(CASE WHEN TCRTS.tag_id IN ") - .append(tagIds) - .append(" THEN TCG.id ELSE NULL END)) + COUNT(DISTINCT(CASE WHEN MRTS.tag_id IN ") - .append(tagIds) - .append(" THEN MG.id ELSE NULL END)) = ") - .append(params.getNumberOfGroups()) - .append(") as filtered ") - .append(" JOIN stmatrixruns MR ON filtered.m_id = MR.id ") - .append(" LEFT JOIN sttestcaseruns TCR ON filtered.tc_id = TCR.id "); - } else { - queryBuilder.append(" FROM stmatrixruns MR ") - .append(" LEFT JOIN sttestcaseruns TCR ON MR.id = TCR.matrix_run_id "); + for(int i =0; i < groupingColumns.size(); i++) { + query.addScalar(buildDimensionPostfix(params.getDimensions().get(i), i), StringType.INSTANCE); } - queryBuilder.append(" GROUP BY " + toMysqlSet(groupingColumns)); - queryBuilder.append(" ORDER BY " + toMysqlSet(groupingColumns)); - - logger.info("{}", queryBuilder); - - SQLQuery query = session.createSQLQuery(queryBuilder.toString()); - - // set types - - for(int i =0; i < groupingColumns.size(); i++) { - query.addScalar(buildDimensionPostfix(params.getDimensions().get(i), i), StringType.INSTANCE); - } - query.addScalar("total_exec_time", LongType.INSTANCE); - query.addScalar("total_tcs", LongType.INSTANCE); - query.addScalar("passed_tcs", LongType.INSTANCE); - query.addScalar("conditionally_passed_tcs", LongType.INSTANCE); - query.addScalar("failed_tcs", LongType.INSTANCE); - query.addScalar("passed_percent", BigDecimalType.INSTANCE); - query.addScalar("conditionally_passed_percent", BigDecimalType.INSTANCE); - query.addScalar("failed_percent", BigDecimalType.INSTANCE); - query.addScalar("total_matrixruns", IntegerType.INSTANCE); - query.addScalar("failed_matrices", IntegerType.INSTANCE); - - // execute + for (Map.Entry fieldNameAndType : + AbstractTagGroupQueryBuilder.FIELD_NAMES_AND_TYPES.entrySet()) { + query.addScalar(fieldNameAndType.getKey(), fieldNameAndType.getValue()); + } - result.setRows( parseTagGroupResultSet(query.list(), params) ); + result.setRows( parseTagGroupResultSet(query.list(), params) ); - return result; + return result; } - private boolean isDimensionsExist(TagGroupReportParameters params) { - return CollectionUtils.isNotEmpty(params.getTagIds()); + public void createTagGroupTempTable(Session session, Collection tagIds) { + String query = DROP_TAG_GROUP_TEMP_TABLE; + SQLQuery sqlQuery = session.createSQLQuery(query); + sqlQuery.executeUpdate(); + + query = CREATE_TAG_GROUP_TEMP_TABLE.replace(":tagIds", + tagIds.stream() + .map(String::valueOf) + .collect(Collectors.joining(","))); + sqlQuery = session.createSQLQuery(query); + sqlQuery.executeUpdate(); } - private void applyTimestampAndSfInstances(TagGroupReportParameters parameters, - StringBuilder queryBuilder, String tableName) { - if (parameters.getFrom() != null) { - addTimestamp(queryBuilder, parameters.getFrom(), "starttime", ">="); + public JoinType recognizeJoinType(Session session) { + SQLQuery sqlQuery = session.createSQLQuery(NativeQueryUtil.CHECK_TESTCASE_TAGS_QUERY); + List list = sqlQuery.list(); + if (list == null || list.isEmpty()) { + return JoinType.MATRIX_RUN_TAGS; } - if (parameters.getTo() != null) { - addTimestamp(queryBuilder, parameters.getTo(), "finishtime", "<="); - } - if (CollectionUtils.isNotEmpty(parameters.getSelectedSfInstances())) { - String sfIds = toMysqlSet( - parameters.getSelectedSfInstances().stream() - .map(sfInstance -> sfInstance.getId()) - .collect(Collectors.toList()) - ); - queryBuilder.append(" AND ") - .append(tableName) - .append(".sf_id IN (") - .append(sfIds) - .append(") "); + sqlQuery = session.createSQLQuery(NativeQueryUtil.CHECK_MATRIX_TAGS_QUERY); + list = sqlQuery.list(); + if (list == null || list.isEmpty()) { + return JoinType.TEST_CASE_RUN_TAGS; } + return JoinType.TEST_CASE_AND_MATRIX_RUN_TAGS; } - private void addTimestamp(StringBuilder queryBuilder, Date timestamp, String fieldName, String operation) { - String value = TIMESTAMP_FORMAT.get().format(timestamp); - queryBuilder.append(" AND MR.") - .append(fieldName) - .append(" ") - .append(operation) - .append(" "); - if (isPostgreSql()) { - queryBuilder.append(" timestamp "); - } - queryBuilder.append(" '") - .append(value) - .append("' "); + private boolean isDimensionsExist(TagGroupReportParameters params) { + return CollectionUtils.isNotEmpty(params.getTagIds()); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeQueryUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeQueryUtil.java new file mode 100644 index 00000000..93a0e6c8 --- /dev/null +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeQueryUtil.java @@ -0,0 +1,54 @@ +/****************************************************************************** + * Copyright (c) 2009-2019, Exactpro Systems LLC + * www.exactpro.com + * Build Software to Test Software + * + * All rights reserved. + * This is unpublished, licensed software, confidential and proprietary + * information which is the property of Exactpro Systems LLC or its licensors. + ******************************************************************************/ +package com.exactpro.sf.embedded.statistics.storage; + +import com.exactpro.sf.embedded.statistics.configuration.DbmsType; + +public class NativeQueryUtil { + + public static final String TAG_GROUP_TEMP_TABLE = "mr_and_tcr_ids"; + + public static final String DROP_TAG_GROUP_TEMP_TABLE = + "DROP TABLE IF EXISTS " + TAG_GROUP_TEMP_TABLE + ";"; + + public static final String CREATE_TAG_GROUP_TEMP_TABLE = + "CREATE TEMPORARY TABLE " + TAG_GROUP_TEMP_TABLE + " AS " + + " SELECT " + + " T.id as tag_id, " + + " T.name as tag_name, " + + " G.id as group_id, " + + " MRT.mr_id as mr_id, " + + " TCRT.tcr_id as tcr_id " + + " FROM ( " + + " SELECT * " + + " FROM sttags " + + " WHERE sttags.id IN (:tagIds) " + + " ) AS T " + + " LEFT JOIN sttaggroups G ON T.group_id = G.id " + + " LEFT JOIN stmrtags AS MRT ON MRT.tag_id = T.id " + + " LEFT JOIN sttcrtags AS TCRT ON TCRT.tag_id = T.id;"; + + public static final String CHECK_TESTCASE_TAGS_QUERY = + "SELECT 1 FROM " + TAG_GROUP_TEMP_TABLE + + " WHERE " + TAG_GROUP_TEMP_TABLE + ".tcr_id IS NOT NULL LIMIT 1"; + + public static final String CHECK_MATRIX_TAGS_QUERY = + "SELECT 1 FROM " + TAG_GROUP_TEMP_TABLE + + " WHERE " + TAG_GROUP_TEMP_TABLE + ".mr_id IS NOT NULL LIMIT 1"; + + + public static boolean isMysql(String type) { + return DbmsType.MySql.getValue().equals(type); + } + + public static boolean isPostgreSql(String type) { + return DbmsType.PostgreSQL.getValue().equals(type); + } +} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/PostgresTagGroupQueryBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/PostgresTagGroupQueryBuilder.java new file mode 100644 index 00000000..39fc6bcb --- /dev/null +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/PostgresTagGroupQueryBuilder.java @@ -0,0 +1,29 @@ +/****************************************************************************** + * Copyright (c) 2009-2019, Exactpro Systems LLC + * www.exactpro.com + * Build Software to Test Software + * + * All rights reserved. + * This is unpublished, licensed software, confidential and proprietary + * information which is the property of Exactpro Systems LLC or its licensors. + ******************************************************************************/ +package com.exactpro.sf.embedded.statistics.storage; + +public class PostgresTagGroupQueryBuilder extends AbstractTagGroupQueryBuilder { + @Override + protected String getTotalTimeField() { + return "extract ('epoch' from MR.finishTime - MR.startTime)"; + } + + @Override + protected String formatTimestamp(String value) { + return " timestamp '" + value + "' "; + } + + @Override + public PostgresTagGroupQueryBuilder clone() { + PostgresTagGroupQueryBuilder clone = new PostgresTagGroupQueryBuilder(); + cloneTo(clone); + return clone; + } +} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java index 43b54835..5fb2ba6e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java @@ -26,10 +26,12 @@ import java.util.TreeMap; import java.util.function.BiConsumer; +import com.exactpro.sf.embedded.statistics.storage.reporting.TagGroupDimension; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.hibernate.Query; +import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; @@ -1426,27 +1428,41 @@ public TaggedComparisonResult generateTaggedSetsComparisonReport(TaggedSetsCompa } - public TagGroupReportResult generateTagGroupReport(TagGroupReportParameters params) { + public List generateTagGroupReport(TagGroupReportParameters params, List dimensions) { - Session session = null; + Session session = null; - NativeDbOperations nativeOps = new NativeDbOperations(settings); + NativeDbOperations nativeOps = new NativeDbOperations(settings); - try { + try { - session = this.sessionFactory.openSession(); + session = this.sessionFactory.openSession(); - return nativeOps.generateTagGroupReport(session, params); + AbstractTagGroupQueryBuilder queryBuilder = NativeQueryUtil.isMysql(settings.getDbms()) + ? new MySqlTagGroupQueryBuilder() + : new PostgresTagGroupQueryBuilder(); - } finally { + nativeOps.createTagGroupTempTable(session, params.getTagIds()); - if(session != null) { - session.close(); - } + queryBuilder.setJoinType(nativeOps.recognizeJoinType(session)); - } + List results = new ArrayList<>(); - } + for(int i = 0; i < dimensions.size(); i++) { + params.setLoadForLevel(i); + results.add(nativeOps.generateTagGroupReport(session, params, queryBuilder.clone())); + } + + return results; + } finally { + + if(session != null) { + session.close(); + } + + } + + } @SuppressWarnings("unchecked") public List generateAggregatedTaggedReport(AggregateReportParameters params) { @@ -1570,4 +1586,5 @@ private void loadAndAddTestCaseTags(Map rows) { } } } + } diff --git a/BackEnd/Core/sailfish-core/src/main/resources/com/exactpro/sf/statistics/storage/pg/migration/V3.4__matrixruns_indexes.sql b/BackEnd/Core/sailfish-core/src/main/resources/com/exactpro/sf/statistics/storage/pg/migration/V3.4__matrixruns_indexes.sql new file mode 100644 index 00000000..395fcb81 --- /dev/null +++ b/BackEnd/Core/sailfish-core/src/main/resources/com/exactpro/sf/statistics/storage/pg/migration/V3.4__matrixruns_indexes.sql @@ -0,0 +1,2 @@ +CREATE INDEX stmrtags_mr_id_idx ON stmrtags USING btree (mr_id); +CREATE INDEX stmrtags_tag_id_idx ON stmrtags USING btree (tag_id); \ No newline at end of file From 97cabc81366d764b6d67acda0b937ec8a63e4c16 Mon Sep 17 00:00:00 2001 From: "sergey.smirnov" Date: Wed, 27 Feb 2019 14:51:47 +0400 Subject: [PATCH 15/26] [RM] Support #54988. Include AML-3 into core distributive (cherry picked from commit 6fa6f2c1ab19b49a8d428077a0b289b24774625a) Change-Id: Ib88d2d0c94698d023bddbcc09144951e320782a8 --- .../exactpro/sf/center/impl/PluginLoader.java | 3 ++- .../sf/common/logging/CommonLoggers.java | 26 +++++++++++++++++++ .../languagemanager/LanguageManager.java | 11 ++++++++ .../sf/storage/impl/ObjectFlusher.java | 3 ++- .../src/main/workspace/cfg/actions.xml | 6 +++++ BackEnd/Plugin/plugin-generic/build.gradle | 2 -- FrontEnd/SailfishFrontEnd/build.gradle | 2 ++ .../notifications/chanel/SFWebHandler.java | 3 +++ .../testwebgui/scriptruns/MatrixHolder.java | 3 ++- 9 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/CommonLoggers.java diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java index 514793c9..85640d74 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java @@ -34,6 +34,7 @@ import java.util.ServiceLoader; import java.util.Set; +import com.exactpro.sf.common.logging.CommonLoggers; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.slf4j.Logger; @@ -62,7 +63,7 @@ public class PluginLoader { private static final Logger logger = LoggerFactory.getLogger(PluginLoader.class); - private final Logger userEventsLogger = LoggerFactory.getLogger("USER_EVENTS_LOG"); + private final Logger userEventsLogger = CommonLoggers.USER_EVENTS_LOGGER; public static final String LOG4J_PROPERTIES_FILE_NAME = "log.properties"; public static final String CUSTOM_DICTIONARIES_XML = "custom_dictionaries.xml"; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/CommonLoggers.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/CommonLoggers.java new file mode 100644 index 00000000..d519a302 --- /dev/null +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/CommonLoggers.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright 2009-2019 Exactpro (Exactpro Systems Limited) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ + +package com.exactpro.sf.common.logging; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CommonLoggers { + + public static final Logger USER_EVENTS_LOGGER = LoggerFactory.getLogger("USER_EVENTS_LOG"); + +} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java index 2bf7c1fb..f31c87d3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java @@ -22,6 +22,7 @@ import java.util.TreeMap; import com.exactpro.sf.center.IVersion; +import com.exactpro.sf.common.logging.CommonLoggers; import com.exactpro.sf.configuration.ILoadableManager; import com.exactpro.sf.configuration.ILoadableManagerContext; import com.exactpro.sf.configuration.suri.SailfishURI; @@ -29,11 +30,15 @@ import com.exactpro.sf.configuration.suri.SailfishURIRule; import com.exactpro.sf.configuration.suri.SailfishURIUtils; import com.exactpro.sf.scriptrunner.languagemanager.exceptions.LanguageManagerException; +import org.slf4j.Logger; public class LanguageManager implements ILoadableManager { public static final ILanguageFactory AUTO = new AutoLanguageFactory(); + private final Logger userEventsLogger = CommonLoggers.USER_EVENTS_LOGGER; + + @SuppressWarnings("serial") private final Map uriToFactory = new TreeMap() {{ put(AutoLanguageFactory.URI, AUTO); }}; @@ -46,8 +51,14 @@ public void load(ILoadableManagerContext context) { try { for (ILanguageFactory languageFactory : ServiceLoader.load(ILanguageFactory.class, classLoader)) { + if (languageFactory.getClass().getClassLoader() != classLoader) { + continue; + } + SailfishURI languageURI = new SailfishURI(version.getAlias(), null, languageFactory.getName()); uriToFactory.put(languageURI, languageFactory); + + userEventsLogger.info("Loaded {} languageFactory from {}", languageFactory.getName(), context.getVersion().getArtifactName()); } } catch(Exception e) { throw new LanguageManagerException("Failed to load language factories", e); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java index 399527b2..a64f2d54 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java @@ -15,6 +15,7 @@ ******************************************************************************/ package com.exactpro.sf.storage.impl; +import com.exactpro.sf.common.logging.CommonLoggers; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.storage.IObjectFlusher; import com.exactpro.sf.storage.IMeasurable; @@ -32,7 +33,7 @@ public class ObjectFlusher implements IObjectFlusher { private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); - private final static Logger USER_EVENTS_LOG = LoggerFactory.getLogger("USER_EVENTS_LOG"); + private final static Logger USER_EVENTS_LOG = CommonLoggers.USER_EVENTS_LOGGER; private static final long JOIN_TIMEOUT = 2000; diff --git a/BackEnd/Core/sailfish-core/src/main/workspace/cfg/actions.xml b/BackEnd/Core/sailfish-core/src/main/workspace/cfg/actions.xml index 6fe81c49..a608188c 100644 --- a/BackEnd/Core/sailfish-core/src/main/workspace/cfg/actions.xml +++ b/BackEnd/Core/sailfish-core/src/main/workspace/cfg/actions.xml @@ -17,6 +17,11 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> + + + + + @@ -33,4 +38,5 @@ + \ No newline at end of file diff --git a/BackEnd/Plugin/plugin-generic/build.gradle b/BackEnd/Plugin/plugin-generic/build.gradle index f049b24c..9d94aec9 100644 --- a/BackEnd/Plugin/plugin-generic/build.gradle +++ b/BackEnd/Plugin/plugin-generic/build.gradle @@ -9,14 +9,12 @@ dependencies { if (incremental_build) { compileOnly "com.exactpro.sf:sailfish-core:${artifactCoreVersion}" - compile "com.exactpro.sf:extension-aml-3:${artifactVersion}" compile "com.exactpro.sf:service-ntg:${artifactVersion}" compile "com.exactpro.sf:service-itch:${artifactVersion}" compile "com.exactpro.sf:service-fix:${artifactVersion}" compile "com.exactpro.sf:service-fast:${artifactVersion}" } else { compileOnly project(':BackEnd:Core:sailfish-core') - compile project(':BackEnd:Extension:extension-aml-3') compile project(':BackEnd:Service:service-ntg') compile project(':BackEnd:Service:service-itch') compile project(':BackEnd:Service:service-fix') diff --git a/FrontEnd/SailfishFrontEnd/build.gradle b/FrontEnd/SailfishFrontEnd/build.gradle index afb3508b..11eaa502 100644 --- a/FrontEnd/SailfishFrontEnd/build.gradle +++ b/FrontEnd/SailfishFrontEnd/build.gradle @@ -139,9 +139,11 @@ dependencies { if (incremental_build) { compile "com.exactpro.sf:sailfish-core:${artifactCoreVersion}" compile "com.exactpro.sf:sailfish-rest-api-client:${artifactCoreVersion}" + compile "com.exactpro.sf:extension-aml-3:${artifactCoreVersion}" } else { compile project(':BackEnd:Core:sailfish-core') compile project(':FrontEnd:Sailfish-REST-API-client') + compile project(':BackEnd:Extension:extension-aml-3') } diff --git a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/chanel/SFWebHandler.java b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/chanel/SFWebHandler.java index 469a1c90..1d66bd15 100644 --- a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/chanel/SFWebHandler.java +++ b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/notifications/chanel/SFWebHandler.java @@ -20,6 +20,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import com.exactprosystems.webchannels.messages.TestRequest; import org.apache.commons.lang3.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -172,6 +173,8 @@ public AbstractMessage onReceive(Object message, long seqnum) { } else if(message instanceof HeartBeat){ + } else if (message instanceof TestRequest) { + } else { throw new Exception("Handler " + this + " error. Incorrect incoming message " + message + " for channel " + channel); diff --git a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/scriptruns/MatrixHolder.java b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/scriptruns/MatrixHolder.java index f5402bc3..cdf153a0 100644 --- a/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/scriptruns/MatrixHolder.java +++ b/FrontEnd/SailfishFrontEnd/src/main/java/com/exactpro/sf/testwebgui/scriptruns/MatrixHolder.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import com.exactpro.sf.common.logging.CommonLoggers; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,7 +36,7 @@ public class MatrixHolder implements IMatrixListener { private static final Logger logger = LoggerFactory.getLogger(MatrixHolder.class); - public static final Logger USER_EVENTS_LOG = LoggerFactory.getLogger("USER_EVENTS_LOG"); + public static final Logger USER_EVENTS_LOG = CommonLoggers.USER_EVENTS_LOGGER; private final IWorkspaceDispatcher wd; private final IMatrixStorage matrixStorage; From 1157437c220389e525b5c2b6d25e6df0a2244072 Mon Sep 17 00:00:00 2001 From: "ivan.druzhinin" Date: Tue, 26 Mar 2019 11:55:33 +0300 Subject: [PATCH 16/26] [RM] Support #54477. Refactoring > Cleanup code using subset of "Java | Code style issues" IntelliJ IDEA inspections (cherry picked from commit 87bf20397cb9fac788d3e0f4707fe3f6997bbfd7) Change-Id: I12dd260bda1273b9f28049fe83534c183b455ac7 --- .../sf/common/impl/messages/BaseMessage.java | 13 +- .../impl/messages/DefaultMessageFactory.java | 7 +- .../sf/common/impl/messages/MapMessage.java | 232 +-- .../impl/messages/xml/XMLTransmitter.java | 10 +- .../xml/converter/ConverterVisitor.java | 15 +- .../xml/converter/XmlDictionaryUtils.java | 5 +- .../messages/DirtyMessageTraverser.java | 27 +- .../EmptyMessageStructureReaderHandler.java | 2 +- .../HumanMessageStructureVisitor.java | 7 +- .../sf/common/messages/IFieldInfo.java | 4 +- .../sf/common/messages/IHumanMessage.java | 2 +- .../exactpro/sf/common/messages/IMessage.java | 14 +- .../sf/common/messages/IMessageFactory.java | 8 +- .../messages/MessageStructureReader.java | 79 +- .../MessageStructureReaderHandlerImpl.java | 2 +- .../messages/MessageStructureWriter.java | 131 +- .../sf/common/messages/MessageTraverser.java | 31 +- .../sf/common/messages/MessageUtil.java | 125 +- .../sf/common/messages/MsgMetaData.java | 58 +- .../messages/ReorderFieldComparator.java | 6 +- .../messages/structures/StructureBuilder.java | 24 +- .../messages/structures/StructureType.java | 2 +- .../structures/impl/DictionaryStructure.java | 27 +- .../structures/impl/FieldStructure.java | 22 +- .../structures/impl/MessageStructure.java | 22 +- .../loaders/XmlDictionaryStructureLoader.java | 69 +- .../loaders/XsdDictionaryStructureLoader.java | 112 +- .../sf/common/services/ServiceInfo.java | 8 +- .../sf/common/services/ServiceName.java | 32 +- .../exactpro/sf/common/util/CodeGenUtils.java | 20 +- .../sf/common/util/CodeGenerator.java | 6 +- .../com/exactpro/sf/common/util/Pair.java | 10 +- .../exactpro/sf/common/util/StringUtil.java | 65 +- .../com/exactpro/sf/util/DateTimeUtility.java | 8 +- .../common/impl/messages/TestMapMessage.java | 3 +- .../sf/common/xml/ReadConfigTest.java | 10 +- .../com/exactpro/sf/util/EPSTestCase.java | 2 +- .../aml/scriptutil/LegReorderBenchmark.java | 4 +- .../MessageComparatorBenchmark.java | 4 +- .../com/exactpro/sf/actions/BugsUtils.java | 2 +- .../exactpro/sf/actions/CommonActions.java | 110 +- .../com/exactpro/sf/actions/ConvertUtil.java | 114 +- .../com/exactpro/sf/actions/DateUtil.java | 39 +- .../exactpro/sf/actions/EncodingUtility.java | 2 +- .../com/exactpro/sf/actions/FakeActions.java | 2 +- .../com/exactpro/sf/actions/FakeUtils.java | 2 +- .../com/exactpro/sf/actions/MathUtil.java | 14 +- .../com/exactpro/sf/actions/MessageUtil.java | 8 +- .../com/exactpro/sf/actions/MiscUtils.java | 2 +- .../com/exactpro/sf/actions/NetworkUtils.java | 2 +- .../exactpro/sf/actions/ServiceActions.java | 30 +- .../com/exactpro/sf/actions/TestActions.java | 64 +- .../sf/actions/data/DateComponent.java | 8 +- .../sf/actions/data/DateModificator.java | 6 +- .../exactpro/sf/actions/tools/Filters.java | 10 +- .../main/java/com/exactpro/sf/aml/AML.java | 87 +- .../java/com/exactpro/sf/aml/AMLAction.java | 293 ++- .../com/exactpro/sf/aml/AMLBlockBrace.java | 4 +- .../exactpro/sf/aml/AMLBlockProcessor.java | 4 +- .../com/exactpro/sf/aml/AMLBlockType.java | 8 +- .../com/exactpro/sf/aml/AMLException.java | 5 +- .../java/com/exactpro/sf/aml/AMLLangUtil.java | 34 +- .../java/com/exactpro/sf/aml/AMLList.java | 37 - .../com/exactpro/sf/aml/AMLMatrixWrapper.java | 2 +- .../exactpro/sf/aml/AMLPrivateActions.java | 8 +- .../java/com/exactpro/sf/aml/AMLSettings.java | 31 +- .../java/com/exactpro/sf/aml/AMLTestCase.java | 66 +- .../exactpro/sf/aml/DictionarySettings.java | 10 +- .../com/exactpro/sf/aml/ICodeGenerator.java | 11 +- .../exactpro/sf/aml/IOutputStreamFactory.java | 4 +- .../java/com/exactpro/sf/aml/IValidator.java | 4 +- .../java/com/exactpro/sf/aml/JsonAML.java | 9 +- .../com/exactpro/sf/aml/MessageReference.java | 8 +- .../sf/aml/converter/ConversionMonitor.java | 10 +- .../converter/IMatrixConverterSettings.java | 12 +- .../aml/converter/MatrixConverterContext.java | 6 +- .../aml/converter/MatrixConverterLoader.java | 6 +- .../aml/converter/MatrixConverterManager.java | 4 +- .../sf/aml/generator/AbstractAlert.java | 16 +- .../sf/aml/generator/AggregateAlert.java | 20 +- .../com/exactpro/sf/aml/generator/Alert.java | 26 +- .../sf/aml/generator/AlertCollector.java | 14 +- .../exactpro/sf/aml/generator/AlertType.java | 6 +- .../sf/aml/generator/GeneratedScript.java | 6 +- .../aml/generator/IGetterSetterGenerator.java | 10 +- .../sf/aml/generator/JavaValidator.java | 52 +- .../sf/aml/generator/MVELInitializer.java | 17 +- .../sf/aml/generator/TypeConverter.java | 152 +- .../BaseMessageGetterSetterGeneratorImpl.java | 14 +- .../HashMapGetterSetterGeneratorImpl.java | 8 +- .../sf/aml/generator/matrix/BoolExp.java | 6 +- .../sf/aml/generator/matrix/Column.java | 72 +- .../aml/generator/matrix/JavaStatement.java | 21 +- .../sf/aml/generator/matrix/RefParameter.java | 4 +- .../sf/aml/generator/matrix/TypeHelper.java | 8 +- .../sf/aml/generator/matrix/Value.java | 21 +- .../sf/aml/generator/matrix/Variable.java | 15 +- .../sf/aml/iomatrix/AdvancedMatrixReader.java | 12 +- .../sf/aml/iomatrix/AdvancedMatrixWriter.java | 21 +- .../sf/aml/iomatrix/CSVDelimiter.java | 14 +- .../sf/aml/iomatrix/CSVMatrixReader.java | 15 +- .../sf/aml/iomatrix/ExcelMatrixReader.java | 6 +- .../sf/aml/iomatrix/ExcelMatrixWriter.java | 12 +- .../sf/aml/iomatrix/IMatrixReader.java | 6 +- .../sf/aml/iomatrix/IMatrixWriter.java | 6 +- .../sf/aml/iomatrix/MatrixFileTypes.java | 4 +- .../exactpro/sf/aml/iomatrix/SimpleCell.java | 4 +- .../sf/aml/iomatrix/SimpleCellUtils.java | 5 +- .../sf/aml/magic/IMessage2Action.java | 4 +- .../sf/aml/script/DefaultSettings.java | 31 +- .../exactpro/sf/aml/script/MetaContainer.java | 48 +- .../java/com/exactpro/sf/aml/script/Util.java | 4 +- .../sf/aml/script/actions/WaitAction.java | 86 +- .../sf/aml/scriptutil/ExpressionResult.java | 16 +- .../scriptutil/IMessagePropertyHandler.java | 2 +- .../sf/aml/scriptutil/LegReorder.java | 32 +- .../sf/aml/scriptutil/MessageCount.java | 56 +- .../sf/aml/scriptutil/StaticUtil.java | 42 +- .../sf/aml/visitors/AMLConverterVisitor.java | 14 +- .../sf/aml/visitors/AMLHeadersVisitor.java | 5 +- .../sf/aml/visitors/IAMLElementVisitor.java | 4 +- .../sf/bigbutton/BigButtonSettings.java | 11 +- .../sf/bigbutton/RegressionRunner.java | 61 +- .../sf/bigbutton/execution/CombineQueue.java | 8 +- .../execution/DownloadsCompleteTask.java | 6 +- .../execution/ExecutionProgressMonitor.java | 148 +- .../execution/ExecutionReportExporter.java | 18 +- .../bigbutton/execution/ExecutorClient.java | 109 +- .../execution/RegressionRunnerUtils.java | 11 +- .../execution/ReportDownloadTask.java | 17 +- .../execution/ScriptExecutionStatistics.java | 2 +- .../importing/CsvLibraryBuilder.java | 150 +- .../sf/bigbutton/importing/ImportError.java | 6 +- .../importing/LibraryImportResult.java | 10 +- .../library/AbstractLibraryItem.java | 4 +- .../sf/bigbutton/library/BigButtonAction.java | 2 +- .../sf/bigbutton/library/CsvHeader.java | 2 +- .../exactpro/sf/bigbutton/library/Daemon.java | 17 +- .../sf/bigbutton/library/DaemonList.java | 4 +- .../sf/bigbutton/library/Executor.java | 23 +- .../sf/bigbutton/library/ExecutorList.java | 4 +- .../sf/bigbutton/library/Globals.java | 4 +- .../sf/bigbutton/library/Library.java | 22 +- .../exactpro/sf/bigbutton/library/Script.java | 39 +- .../sf/bigbutton/library/ScriptList.java | 29 +- .../sf/bigbutton/library/Service.java | 27 +- .../sf/bigbutton/library/ServiceList.java | 14 +- .../sf/bigbutton/library/SfApiOptions.java | 28 +- .../sf/bigbutton/library/StartMode.java | 2 +- .../exactpro/sf/bigbutton/library/Tag.java | 29 +- .../sf/bigbutton/library/TagList.java | 2 +- .../sf/bigbutton/util/BigButtonUtil.java | 8 +- .../java/com/exactpro/sf/center/IVersion.java | 4 +- .../exactpro/sf/center/SFContextSettings.java | 7 +- .../sf/center/impl/AbstractVersion.java | 12 +- .../com/exactpro/sf/center/impl/LoadInfo.java | 4 +- .../exactpro/sf/center/impl/PluginLoader.java | 56 +- .../sf/center/impl/SFLocalContext.java | 64 +- .../sf/common/adapting/IAdapterFactory.java | 4 +- .../sf/common/adapting/IAdapterManager.java | 24 +- .../adapting/impl/DefaultAdapterFactory.java | 13 +- .../sf/common/codecs/AbstractCodec.java | 2 +- .../sf/common/codecs/CodecFactory.java | 6 +- .../messages/IMessageTimestampComparator.java | 22 +- .../impl/messages/StrictMessageWrapper.java | 38 +- .../logging/DailyMaxRollingFileAppender.java | 142 +- .../structures/DictionaryComparator.java | 37 +- .../exactpro/sf/common/profiler/Profiler.java | 55 +- .../sf/common/util/BeanConfigurator.java | 8 +- .../exactpro/sf/common/util/ErrorUtil.java | 4 +- .../sf/common/util/GenericConverter.java | 35 +- .../exactpro/sf/common/util/HexDumper.java | 27 +- .../sf/common/util/ICommonSettings.java | 2 +- .../sf/common/util/InvalidRangeException.java | 3 +- .../util/InvalidXMLCharacterException.java | 2 +- .../com/exactpro/sf/common/util/Range.java | 92 +- .../exactpro/sf/common/util/SearchUtil.java | 89 +- .../util/SendMessageFailedException.java | 1 - .../sf/common/util/TextOutputStream.java | 10 +- .../com/exactpro/sf/common/util/Utils.java | 1603 ++++++++--------- .../sf/comparison/ComparatorSettings.java | 4 +- .../sf/comparison/ComparisonResult.java | 2 +- .../sf/comparison/ComparisonUtil.java | 10 +- .../exactpro/sf/comparison/Convention.java | 35 +- .../com/exactpro/sf/comparison/Formatter.java | 211 ++- .../sf/comparison/IPostValidation.java | 2 +- .../sf/comparison/MessageComparator.java | 18 +- .../conversion/ConvertingComparator.java | 9 +- .../comparison/conversion/MultiConverter.java | 11 +- .../impl/AbstractNumberConverter.java | 6 +- .../exactpro/sf/comparison/table/Column.java | 6 +- .../com/exactpro/sf/comparison/table/Row.java | 10 +- .../exactpro/sf/comparison/table/Status.java | 6 +- .../exactpro/sf/comparison/table/Table.java | 28 +- .../sf/configuration/DataManager.java | 12 +- .../configuration/DefaultAdapterManager.java | 75 +- .../sf/configuration/DictionaryManager.java | 99 +- .../configuration/DummyDictionaryManager.java | 2 +- .../sf/configuration/EnvironmentManager.java | 16 +- .../sf/configuration/ILoadableManager.java | 4 +- .../ILoadableManagerContext.java | 8 +- .../configuration/LoggingConfiguration.java | 4 +- .../sf/configuration/LoggingConfigurator.java | 2 +- .../DictionaryValidationErrorLevel.java | 2 +- .../dictionary/ValidationHelper.java | 125 +- .../impl/AbstractDictionaryValidator.java | 18 +- .../impl/DefaultDictionaryValidator.java | 19 +- .../impl/PrototypeDictionaryValidator.java | 29 +- .../interfaces/IDictionaryValidator.java | 2 +- .../netdumper/NetDumperOptions.java | 21 +- .../netdumper/NetDumperService.java | 65 +- .../netdumper/RESTDumperClient.java | 16 +- .../recorder/FlightRecorderOptions.java | 9 +- .../recorder/FlightRecorderService.java | 136 +- .../configuration/recorder/RecordedFile.java | 3 +- .../workspace/AbstractWorkspaceLayout.java | 3 +- .../workspace/DefaultWorkspaceDispatcher.java | 81 +- .../workspace/ResourceWorkspaceLayout.java | 2 +- ...DefaultMulticastDatagramSessionConfig.java | 2 +- .../net/MulticastDatagramSessionConfig.java | 9 +- .../mina/net/MulticastSocketConnector.java | 19 +- .../mina/net/MulticastSocketProcessor.java | 25 +- .../mina/net/MulticastSocketSession.java | 8 +- .../AbstractHibernateServiceSettings.java | 8 +- .../machinelearning/JsonEntityParser.java | 27 +- .../MachineLearningService.java | 24 +- .../machinelearning/entities/EntryType.java | 2 +- .../entities/FailedAction.java | 44 +- .../machinelearning/entities/Message.java | 41 +- .../entities/MessageEntry.java | 70 +- .../entities/MessageParticipant.java | 23 +- .../machinelearning/entities/MessageType.java | 25 +- .../machinelearning/entities/SimpleValue.java | 9 +- .../storage/MLFileStorage.java | 4 +- .../sf/embedded/mail/EMailService.java | 18 +- .../configuration/EMailServiceSettings.java | 15 +- .../sf/embedded/statistics/DimensionMap.java | 10 +- .../sf/embedded/statistics/MatrixInfo.java | 15 +- .../statistics/StatisticsException.java | 2 +- .../statistics/StatisticsFlywayWrapper.java | 21 +- .../statistics/StatisticsMigration.java | 9 +- .../statistics/StatisticsService.java | 160 +- .../embedded/statistics/StatisticsUtils.java | 37 +- .../statistics/configuration/DbmsType.java | 2 +- .../StatisticsServiceSettings.java | 64 +- .../embedded/statistics/entities/Action.java | 3 +- .../statistics/entities/ActionRun.java | 6 +- .../entities/ActionRunKnownBug.java | 2 +- .../statistics/entities/Environment.java | 3 +- .../statistics/entities/KnownBug.java | 11 +- .../embedded/statistics/entities/Matrix.java | 3 +- .../statistics/entities/MatrixRun.java | 8 +- .../statistics/entities/MessageType.java | 3 +- .../embedded/statistics/entities/Service.java | 3 +- .../statistics/entities/SfInstance.java | 30 +- .../sf/embedded/statistics/entities/Tag.java | 30 +- .../statistics/entities/TagGroup.java | 30 +- .../statistics/entities/TestCase.java | 30 +- .../statistics/entities/TestCaseRun.java | 30 +- .../entities/TestCaseRunStatus.java | 30 +- .../statistics/entities/TestCaseRunTag.java | 13 +- .../statistics/entities/TestCaseRunTagId.java | 13 +- .../sf/embedded/statistics/entities/User.java | 3 +- .../statistics/handlers/ReportValue.java | 2 +- .../StatisticsReportHandlerLoader.java | 2 +- .../impl/AbstractStatisticsReportHandler.java | 8 +- .../impl/DefaultStatisticsHandlerFactory.java | 2 +- .../storage/AggregatedReportRow.java | 163 +- .../storage/DayleTestCasesStatRow.java | 2 - .../storage/NativeDbOperations.java | 12 +- .../storage/StatisticsReportingStorage.java | 95 +- .../statistics/storage/StatisticsStorage.java | 220 ++- .../storage/TestCaseHistoryRow.java | 3 +- .../storage/reporting/ActionInfoRow.java | 3 +- .../reporting/AggregateReportParameters.java | 2 +- .../storage/reporting/ScriptWeatherRow.java | 9 +- .../storage/reporting/TagGroupDimension.java | 29 +- .../storage/reporting/TagGroupReportRow.java | 8 +- .../reporting/TaggedComparisonRow.java | 58 +- .../reporting/TestCasesDisplayMode.java | 2 +- .../storage/AbstractHibernateStorage.java | 17 +- .../storage/HibernateStorageSettings.java | 109 +- .../sf/embedded/updater/UpdateService.java | 29 +- .../configuration/UpdateServiceSettings.java | 21 +- .../sf/externalapi/AbstractSettingsProxy.java | 16 +- .../sf/externalapi/IMessageFactoryProxy.java | 9 +- .../sf/externalapi/ServiceFactory.java | 71 +- .../sf/externalapi/ServiceFactoryBuilder.java | 6 +- .../impl/StrictDictionaryManager.java | 2 +- .../com/exactpro/sf/help/HelpBuilder.java | 16 +- .../exactpro/sf/help/HelpLanguageManager.java | 3 +- .../help/helpmarshaller/HelpEntityName.java | 10 +- .../help/helpmarshaller/HelpEntityType.java | 2 +- .../describers/FieldsDescriber.java | 30 +- .../jsoncontainers/FieldJsonContainer.java | 4 +- .../jsoncontainers/HelpJsonContainer.java | 6 +- .../jsoncontainers/MethodJsonContainer.java | 9 +- .../jsoncontainers/URIJsonContainer.java | 4 +- .../matrixhandlers/MatrixProviderHolder.java | 6 +- .../sf/scriptrunner/AbstractScriptRunner.java | 116 +- .../sf/scriptrunner/AdaptersLoader.java | 8 +- .../sf/scriptrunner/AsyncScriptRunner.java | 68 +- .../sf/scriptrunner/DebugController.java | 34 +- .../sf/scriptrunner/EnvironmentSettings.java | 72 +- .../sf/scriptrunner/IConnectionManager.java | 4 +- .../sf/scriptrunner/IPauseListener.java | 4 +- .../sf/scriptrunner/IScriptProgress.java | 44 +- .../sf/scriptrunner/IScriptReport.java | 2 +- .../com/exactpro/sf/scriptrunner/Outcome.java | 12 +- .../sf/scriptrunner/OutcomeCollector.java | 65 +- .../sf/scriptrunner/SailFishAction.java | 2 +- .../sf/scriptrunner/SailFishTestCase.java | 12 +- .../sf/scriptrunner/ScriptContext.java | 40 +- .../sf/scriptrunner/ScriptProgress.java | 50 +- .../sf/scriptrunner/ScriptSettings.java | 44 +- .../sf/scriptrunner/StatusDescription.java | 12 +- .../exactpro/sf/scriptrunner/StatusType.java | 2 +- .../sf/scriptrunner/SyncScriptRunner.java | 40 +- .../scriptrunner/TestScriptDescription.java | 65 +- .../TestScriptProgressListener.java | 6 +- .../exactpro/sf/scriptrunner/ZipReport.java | 6 +- .../actionmanager/ActionInfo.java | 38 +- .../actionmanager/ActionManager.java | 2 +- .../actionmanager/ActionRequirements.java | 8 +- .../actionmanager/IActionCaller.java | 10 +- .../actioncontext/IActionContext.java | 56 +- .../actioncontext/IActionReport.java | 4 +- .../actioncontext/IActionServiceManager.java | 22 +- .../impl/ActionContextWrapper.java | 2 +- .../actioncontext/impl/ActionReport.java | 2 +- .../impl/BroadcastScriptReport.java | 20 +- .../impl/DefaultConnectionManager.java | 156 +- .../impl/DefaultEnvironmentMonitor.java | 6 +- .../impl/DefaultScriptConfig.java | 14 +- .../sf/scriptrunner/impl/ReportAppender.java | 8 +- .../sf/scriptrunner/impl/ReportTable.java | 2 +- .../impl/ScriptReportWithLogs.java | 9 +- .../impl/StatisticScriptReport.java | 34 +- .../impl/htmlreport/HtmlReport.java | 191 +- .../impl/htmlreport/data/Action.java | 9 +- .../impl/htmlreport/data/ActionGroup.java | 8 +- .../impl/htmlreport/data/ActionParameter.java | 2 +- .../impl/htmlreport/data/BaseEntity.java | 6 +- .../htmlreport/data/MachineLearningData.java | 6 +- .../impl/htmlreport/data/Message.java | 2 +- .../impl/htmlreport/data/Report.java | 8 +- .../impl/htmlreport/data/TestCase.java | 15 +- .../impl/htmlreport/data/Verification.java | 15 +- .../data/VerificationSerializer.java | 14 +- .../impl/jsonreport/IJsonReportNode.java | 6 +- .../impl/jsonreport/JsonReport.java | 138 +- .../impl/jsonreport/beans/Action.java | 20 +- .../impl/jsonreport/beans/ReportRoot.java | 2 - .../impl/jsonreport/beans/TestCase.java | 18 +- .../scriptrunner/junit40/SFJUnitRunner.java | 41 +- .../languagemanager/AutoLanguageFactory.java | 2 +- .../ICompatibilityChecker.java | 2 +- .../languagemanager/LanguageManager.java | 2 - .../textformatter/TextColor.java | 4 +- .../textformatter/TextStyle.java | 4 +- .../utilitymanager/IUtilityCaller.java | 2 +- .../utilitymanager/UtilityInfo.java | 23 +- .../utilitymanager/UtilityManager.java | 5 +- .../utilitymanager/UtilityManagerUtils.java | 25 +- .../sf/services/AbstractServiceSettings.java | 6 +- .../exactpro/sf/services/CSHArrayList.java | 11 +- .../com/exactpro/sf/services/CSHIterator.java | 6 +- .../sf/services/CollectorServiceHandler.java | 2 +- .../exactpro/sf/services/CustomDialog.java | 2 +- .../sf/services/DefaultServiceContext.java | 12 +- .../sf/services/DisabledServiceSettings.java | 5 +- .../sf/services/FileSessionStorage.java | 37 +- .../services/FilterServiceHandlerWrapper.java | 2 +- .../com/exactpro/sf/services/IService.java | 10 +- .../exactpro/sf/services/MessageHelper.java | 8 +- .../OptionalServiceHandlerWrapper.java | 2 +- .../sf/services/ServiceDescription.java | 2 +- .../exactpro/sf/services/ServiceEvent.java | 4 +- .../sf/services/ServiceHandlerException.java | 2 - .../sf/services/ServiceHandlerRoute.java | 2 +- .../sf/services/ServiceMarshalManager.java | 17 +- .../exactpro/sf/services/TaskExecutor.java | 46 +- .../sf/services/WrapperNioSocketAcceptor.java | 34 +- .../services/WrapperNioSocketConnector.java | 26 +- .../services/codecs/CodecMessageFilter.java | 6 +- .../codecs/HackedProtocolCodecFilter.java | 57 +- .../sf/services/fake/FakeClientService.java | 26 +- .../sf/services/fake/FakeSession.java | 6 +- .../sf/services/loopback/LoopbackService.java | 18 +- .../loopback/LoopbackServiceSettings.java | 2 +- .../sf/services/mina/MINASession.java | 8 +- .../exactpro/sf/services/mina/MINAUtil.java | 16 +- .../sf/services/netty/NettyClientService.java | 54 +- .../netty/NettyMulticastClientService.java | 26 +- .../sf/services/netty/NettySession.java | 24 +- .../handlers/ExceptionInboundHandler.java | 3 +- .../handlers/MessagePersisterHandler.java | 2 +- .../netty/handlers/NettyServiceHandler.java | 21 +- .../sf/services/util/RulesProcessor.java | 40 +- .../sf/services/util/ServiceUtil.java | 26 +- .../sf/statictesting/AbstractStaticTest.java | 3 +- .../sf/statictesting/StaticMatrixTest.java | 14 +- .../exactpro/sf/storage/DefaultMatrix.java | 42 +- .../exactpro/sf/storage/FileBackedList.java | 2 +- .../com/exactpro/sf/storage/IAuthStorage.java | 24 +- .../exactpro/sf/storage/IMessageStorage.java | 2 +- .../exactpro/sf/storage/IObjectFlusher.java | 12 +- .../com/exactpro/sf/storage/ISerializer.java | 8 +- .../com/exactpro/sf/storage/MessageList.java | 4 +- .../exactpro/sf/storage/MessageLoader.java | 6 +- .../exactpro/sf/storage/ServiceEventList.java | 4 +- .../exactpro/sf/storage/StorageFilter.java | 2 +- .../exactpro/sf/storage/TimestampToLong.java | 15 +- .../sf/storage/TimestampToString.java | 20 +- .../exactpro/sf/storage/TruncatedString.java | 12 +- .../sf/storage/auth/PasswordHasher.java | 15 +- .../com/exactpro/sf/storage/auth/User.java | 4 +- .../exactpro/sf/storage/entities/AppUser.java | 24 +- .../exactpro/sf/storage/entities/Role.java | 22 +- .../storage/entities/StoredEnvironment.java | 24 +- .../sf/storage/entities/StoredMatrix.java | 4 +- .../sf/storage/entities/StoredMessage.java | 10 +- .../sf/storage/entities/StoredService.java | 2 +- .../storage/impl/AbstractMessageStorage.java | 4 +- .../impl/AbstractPersistentObject.java | 23 +- .../sf/storage/impl/DatabaseAuthStorage.java | 7 +- .../storage/impl/DatabaseMatrixStorage.java | 36 +- .../storage/impl/DatabaseMessageStorage.java | 61 +- .../storage/impl/DatabaseOptionsStorage.java | 31 +- .../storage/impl/DatabaseServiceStorage.java | 195 +- .../impl/DefaultTestScriptStorage.java | 42 +- .../sf/storage/impl/FileMatrixStorage.java | 8 +- .../sf/storage/impl/FileMessageLoader.java | 2 +- .../sf/storage/impl/FileMessageStorage.java | 10 +- .../sf/storage/impl/FileServiceStorage.java | 8 +- .../impl/FilterMessageStorageWrapper.java | 2 +- .../sf/storage/impl/HibernateFactory.java | 2 +- .../sf/storage/impl/HibernateStorage.java | 103 +- .../exactpro/sf/storage/impl/IDGenerator.java | 2 +- .../sf/storage/impl/MemoryServiceStorage.java | 86 +- .../sf/storage/impl/MessageRowLoaderBase.java | 20 +- .../storage/impl/MessageStorageWrapper.java | 10 +- .../sf/storage/impl/ObjectFlusher.java | 47 +- .../sf/storage/impl/PersistentObject.java | 8 +- .../sf/storage/util/JsonHumanDecoder.java | 2 +- .../sf/storage/util/JsonIMessageDecoder.java | 4 +- .../sf/storage/util/JsonMessageConverter.java | 16 +- .../sf/storage/util/JsonMessageDecoder.java | 98 +- .../PropertiesSettingsReaderSerializer.java | 9 +- .../sf/storage/util/StorageMeasureUtils.java | 2 +- .../storage/xml/DataMessageReaderVisitor.java | 6 +- .../storage/xml/DataMessageWriterVisitor.java | 4 +- .../sf/storage/xml/TypeConverter.java | 9 +- .../sf/storage/xml/db/DBPersister.java | 25 +- .../exactpro/sf/util/AbstractBugsChecker.java | 3 +- .../com/exactpro/sf/util/BugDescription.java | 50 +- .../exactpro/sf/util/BugsCheckerBuilder.java | 25 +- .../sf/util/BugsListCheckerBuilder.java | 26 +- .../com/exactpro/sf/util/CompareUtil.java | 2 +- .../exactpro/sf/util/DictionaryValidator.java | 2 +- .../com/exactpro/sf/util/EnumReplacer.java | 4 +- .../java/com/exactpro/sf/util/ExecUtil.java | 4 +- .../sf/util/FieldKnownBugException.java | 4 +- .../java/com/exactpro/sf/util/HelpUtil.java | 7 +- .../java/com/exactpro/sf/util/Interner.java | 2 +- .../java/com/exactpro/sf/util/JdbcUtils.java | 20 +- .../sf/util/KnownBugPostValidation.java | 63 +- .../java/com/exactpro/sf/util/LRUMap.java | 5 +- .../sf/util/MatrixActionsGenerator.java | 7 +- .../com/exactpro/sf/util/UnicodeReader.java | 10 +- .../com/exactpro/sf/TestObjectFlusher.java | 4 +- .../java/com/exactpro/sf/TestUnsigned.java | 2 +- .../sf/actions/TestCommonActions.java | 5 +- .../com/exactpro/sf/actions/TestDateUtil.java | 80 +- .../sf/actions/TestEncodingUtility.java | 2 +- .../com/exactpro/sf/actions/TestMathUtil.java | 2 +- .../exactpro/sf/actions/TestMessageUtil.java | 2 +- .../exactpro/sf/actions/TestMiscUtils.java | 34 +- .../impl/TestDefaultAdapterManager.java | 7 +- .../sf/aml/AMLBlockProcessorTest.java | 25 +- .../com/exactpro/sf/aml/AMLConverterTest.java | 10 +- .../iomatrix/AdvancedMatrixReaderTest.java | 6 +- .../iomatrix/AdvancedMatrixWriterTest.java | 8 +- .../sf/aml/iomatrix/CSVMatrixReaderTest.java | 5 +- .../sf/aml/iomatrix/CSVMatrixWriterTest.java | 6 +- .../aml/iomatrix/ExcelMatrixWriterTest.java | 14 +- .../sf/aml/script/actions/WaitActionTest.java | 72 +- .../sf/aml/scriptutil/LegReorderTest.java | 4 +- .../sf/aml/scriptutil/MessageCountTest.java | 5 +- .../sf/aml/scriptutil/StaticUtilTest.java | 29 +- .../messages/TestStrictMessageWrapper.java | 6 +- .../messages/CreateIMessageVisitor.java | 4 +- .../sf/common/profiler/ProfilerTest.java | 2 +- .../sf/common/util/TestGenericConverter.java | 12 +- .../sf/comparison/TestMessageComparator.java | 330 ++-- .../conversion/TestMultiConverter.java | 2 +- .../TestAbstractDictionaryValidator.java | 40 +- .../TestDefaultWorkspaceDispatcher.java | 7 +- .../exactpro/sf/configuration/TestRules.java | 6 +- .../TestDefaultDictionaryValidator.java | 6 +- .../TestPrototypeDictionaryValidator.java | 12 +- .../sf/scriptrunner/TestAbstractCaller.java | 2 +- .../sf/scriptrunner/TestScriptRunner.java | 44 +- .../exactpro/sf/services/EnabledSettings.java | 6 +- .../exactpro/sf/services/TestCSHIterator.java | 4 +- .../services/TestDisabledServiceSettings.java | 64 +- .../exactpro/sf/services/TestExternalApi.java | 22 +- .../sf/services/TestTaskExecutor.java | 16 +- .../exactpro/sf/storage/impl/TestStorage.java | 2 +- .../com/exactpro/sf/util/AbstractTest.java | 6 +- .../sf/util/JsonMessageConverterTest.java | 2 +- .../sf/util/KnownBugPostValidationTest.java | 60 +- .../exactpro/sf/util/NettyTestUtility.java | 8 +- .../exactpro/sf/util/TestCodeGenerator.java | 6 +- .../sf/util/TestConfigurationReader.java | 8 +- .../com/exactpro/sf/util/TestHexDump.java | 1 + .../sf/util/TestMatrixActionsGenerator.java | 15 +- .../com/exactpro/sf/util/TestStringUtil.java | 10 +- .../java/com/exactpro/sf/xml/StoreTest.java | 3 +- .../exactpro/sf/aml/AML3LanguageFactory.java | 6 +- .../exactpro/sf/aml/checkers/AML3Checker.java | 4 - .../sf/aml/generator/AbstractCodeBuilder.java | 13 +- .../sf/aml/generator/CodeGenerator_new.java | 499 +---- .../exactpro/sf/aml/generator/NewImpl.java | 242 ++- .../sf/aml/generator/NewImplHelper.java | 67 +- .../exactpro/sf/aml/generator/OldImpl.java | 122 +- .../sf/aml/generator/OldImplHelper.java | 65 +- .../com/exactpro/sf/aml/TestAML3Base.java | 2 +- .../java/com/exactpro/sf/aml/TestAML3_0.java | 19 +- .../com/exactpro/sf/util/AML3PluginTest.java | 8 +- .../sf/actions/FastMatrixActions.java | 24 +- .../factory/FASTMessageFactory.java | 2 +- .../sf/services/fast/FASTAbstractClient.java | 77 +- .../services/fast/FASTAbstractTCPClient.java | 2 +- .../exactpro/sf/services/fast/FASTCodec.java | 27 +- .../sf/services/fast/FASTCodecSettings.java | 10 +- .../sf/services/fast/FASTInvalidSession.java | 2 +- .../sf/services/fast/FASTMessageHelper.java | 4 +- .../services/fast/FASTMessageInputStream.java | 15 +- .../fast/FASTMulticastProxyClient.java | 12 +- .../sf/services/fast/FASTSession.java | 8 +- .../sf/services/fast/FASTTcpClient.java | 22 +- .../sf/services/fast/FASTUdpClient.java | 29 +- .../BlockEncodedUdpInputStream.java | 8 +- .../fast/blockstream/DatagramConnection.java | 18 +- .../fast/blockstream/IPacketHandler.java | 2 +- .../blockstream/MulticastProxyConnection.java | 12 +- .../MulticastProxyInputStream.java | 30 +- .../blockstream/StreamBlockLengthReader.java | 8 +- .../fast/blockstream/UdpInputStream.java | 24 +- .../fast/converter/ConverterException.java | 3 +- .../fast/converter/FASTException.java | 3 +- .../converter/FastToIMessageConverter.java | 38 +- .../converter/IMessageToFastConverter.java | 9 +- .../fast/filter/IFastMessageFilter.java | 2 +- .../fast/filter/SimpleMessageFilter.java | 18 +- .../services/fast/fixup/EofCheckedStream.java | 2 +- .../services/fast/fixup/EofIOException.java | 3 +- .../sf/services/fast/TestFastCodec.java | 10 +- .../converter/TestFastConverterPositive.java | 2 +- .../exactpro/sf/util/FastConverterTest.java | 13 +- .../com/exactpro/sf/actions/DirtyFixUtil.java | 51 +- .../sf/actions/ExtendedConvertUtil.java | 2 +- .../exactpro/sf/actions/FIXMatrixUtil.java | 44 +- .../com/exactpro/sf/actions/FIXPacket.java | 100 +- .../exactpro/sf/actions/FixCommonActions.java | 8 +- .../sf/actions/FixConnectivityActions.java | 101 +- .../sf/actions/FixConnectivityUtil.java | 4 +- ...SailfishDictionaryToQuckfixjConverter.java | 22 +- .../impl/FIXDictionaryValidator.java | 7 +- .../impl/MessageEntityValidator.java | 6 +- .../factory/FixMessageFactory.java | 8 +- .../sf/services/fix/FIXApplication.java | 123 +- .../exactpro/sf/services/fix/FIXClient.java | 260 ++- .../sf/services/fix/FIXClientSettings.java | 8 +- .../exactpro/sf/services/fix/FIXCodec.java | 54 +- .../sf/services/fix/FIXCommonSettings.java | 14 +- .../com/exactpro/sf/services/fix/FIXLog.java | 15 +- .../sf/services/fix/FIXLogFactory.java | 4 +- .../exactpro/sf/services/fix/FIXSession.java | 49 +- .../fix/FixDataDictionaryProvider.java | 28 +- .../sf/services/fix/FixFieldConverter.java | 30 +- .../sf/services/fix/FixSessionFactory.java | 53 +- .../com/exactpro/sf/services/fix/FixUtil.java | 39 +- .../sf/services/fix/IQuickfixApplication.java | 14 +- .../sf/services/fix/QFJDictionaryAdapter.java | 132 +- .../converter/MessageConvertException.java | 1 - .../fix/converter/QFJIMessageConverter.java | 26 +- .../converter/SailfishQuickfixMessage.java | 6 +- .../dirty/DirtyQFJIMessageConverter.java | 24 +- .../fix/converter/dirty/struct/Field.java | 6 +- .../fix/converter/dirty/struct/FieldList.java | 8 +- .../converter/dirty/struct/RawMessage.java | 2 +- .../fix/handler/AbstractProxyIoHandler.java | 48 +- .../fix/handler/ClientSideIoHandler.java | 22 +- .../fix/handler/ServerSideIoHandler.java | 12 +- .../dictionary/SfDictionaryConverterTest.java | 6 +- .../TestFIXDictionaryValidator.java | 8 +- .../sf/services/fix/FixCodecTest.java | 89 +- .../fix/QFJDictionaryAdapterTest.java | 24 +- .../DirtyQFJIMessageConverterTest.java | 33 +- .../converter/QFJMessage2IMessageTest.java | 25 +- .../fix/converter/TestRawMessage.java | 10 +- .../com/exactpro/sf/util/ConverterTest.java | 6 +- .../sf/actions/ITCHCommonActions.java | 44 +- .../impl/ITCHDictionaryValidator.java | 21 +- .../factory/ITCHMessageFactory.java | 18 +- .../exactpro/sf/services/itch/ITCHCodec.java | 30 +- .../sf/services/itch/ITCHDeflateCodec.java | 44 +- .../sf/services/itch/ITCHMessageHelper.java | 4 +- .../sf/services/itch/ITCHPreprocessor.java | 13 +- .../sf/services/itch/ITCHSession.java | 2 +- .../services/itch/ITCHTCPClientSettings.java | 14 +- .../sf/services/itch/ITCHTcpClient.java | 49 +- .../sf/services/itch/ITCHVisitorBase.java | 14 +- .../sf/services/itch/ITCHVisitorDecode.java | 17 +- .../sf/services/itch/ITCHVisitorEncode.java | 12 +- .../sf/services/itch/MessageLevelType.java | 2 +- .../itch/multicast/ITCHCodecFactory.java | 10 +- .../itch/multicast/ITCHMulticastCache.java | 39 +- .../itch/multicast/ITCHMulticastServer.java | 83 +- .../ITCHMulticastTCPHandlerAdapter.java | 41 +- .../multicast/ITCHMulticastTCPSession.java | 19 +- .../multicast/ITCHMulticastUDPSession.java | 71 +- .../services/itch/TestITCHClientNegative.java | 18 +- .../services/itch/TestITCHClientPositive.java | 41 +- .../services/itch/TestITCHCodecPositive.java | 244 +-- .../itch/TestITCHVisitorNegative.java | 27 +- .../itch/TestITCHVisitorPositive.java | 81 +- .../exactpro/sf/util/ITCHWaitResponse.java | 2 +- .../com/exactpro/sf/util/TestITCHHelper.java | 42 +- .../sf/util/TestITCHMessageCreator.java | 8 +- .../exactpro/sf/actions/NTGCommonActions.java | 16 +- .../exactpro/sf/actions/NTGMatrixUtil.java | 26 +- .../impl/NTGDictionaryValidator.java | 1 - .../sf/services/ntg/INTGApplication.java | 4 +- .../exactpro/sf/services/ntg/NTGClient.java | 83 +- .../sf/services/ntg/NTGClientSettings.java | 38 +- .../exactpro/sf/services/ntg/NTGCodec.java | 68 +- .../services/ntg/NTGDefaultApplication.java | 8 +- .../sf/services/ntg/NTGFieldFormat.java | 6 +- .../sf/services/ntg/NTGMessageHelper.java | 14 +- .../sf/services/ntg/NTGProtocolAttribute.java | 2 +- .../sf/services/ntg/NTGServerSettings.java | 24 +- .../exactpro/sf/services/ntg/NTGUtility.java | 57 +- .../sf/services/ntg/NTGVisitorBase.java | 12 +- .../sf/services/ntg/NTGVisitorDecode.java | 72 +- .../sf/services/ntg/NTGVisitorEncode.java | 43 +- .../sf/services/ntg/NTGClientTest.java | 8 +- .../sf/services/ntg/NTGServerTest.java | 175 +- .../sf/services/ntg/RunTaskTestClient.java | 22 +- .../services/ntg/TestNTGActionFunctions.java | 4 +- .../sf/services/ntg/TestNTGClient.java | 189 -- .../services/ntg/TestNTGClientNTGServer.java | 266 --- .../services/ntg/TestNTGClientPositive.java | 5 +- .../ntg/TestNTGCodecForWebHexDump.java | 89 +- .../sf/services/ntg/TestNTGCodecNegative.java | 8 +- .../sf/services/ntg/TestNTGCodecPositive.java | 28 +- .../sf/services/ntg/TestNTGDictionary.java | 2 +- .../sf/services/ntg/TestNTGHelper.java | 4 +- .../sf/services/ntg/TestNTGMessageHelper.java | 10 +- .../sf/services/ntg/TestNTGUtility.java | 4 +- .../services/ntg/TestNTGVisitorPositive.java | 21 +- .../sf/services/ntg/TestSettings.java | 17 +- .../exactpro/sf/util/TestNTGClientBase.java | 2 +- .../sf/actions/ConnectivityActions.java | 51 +- .../com/exactpro/sf/actions/ProxyActions.java | 4 +- .../sf/services/tcpip/InternalJsonCodec.java | 10 +- .../services/tcpip/MessageParseException.java | 2 +- .../sf/services/tcpip/TCPIPClient.java | 4 +- .../sf/services/tcpip/TCPIPMessageHelper.java | 5 +- .../sf/services/tcpip/TCPIPProxy.java | 100 +- .../sf/services/tcpip/TCPIPProxySettings.java | 8 +- .../sf/services/tcpip/TCPIPServer.java | 66 +- .../sf/services/tcpip/TCPIPServerSession.java | 42 +- .../sf/services/tcpip/TCPIPSettings.java | 12 +- .../services/tcpip/TCPIPSettingsServer.java | 6 +- .../services/tcpip/TestInternalJsonCodec.java | 31 +- .../com/exactpro/sf/util/TCPIPPluginTest.java | 4 +- .../com/exactpro/sf/util/TestClientBase.java | 45 +- .../com/exactpro/sf/FileDownloadWrapper.java | 12 +- .../main/java/com/exactpro/sf/Response.java | 2 +- .../java/com/exactpro/sf/SFAPIClient.java | 122 +- .../main/java/com/exactpro/sf/Service.java | 19 +- .../com/exactpro/sf/ServiceDescriptor.java | 6 +- .../com/exactpro/sf/ServiceDescriptors.java | 7 +- .../com/exactpro/sf/ServiceImportResult.java | 16 +- .../java/com/exactpro/sf/TestScriptRun.java | 51 +- ...tScriptRunAggregateReportQueryBuilder.java | 10 +- .../src/main/java/com/exactpro/sf/Util.java | 18 +- .../sf/configuration/suri/SailfishURI.java | 23 +- .../configuration/suri/SailfishURIUtils.java | 25 +- .../restapi/xml/XmlImportError.java | 6 +- .../restapi/xml/XmlLibraryImportResult.java | 10 +- .../restapi/xml/XmlMlDBSettings.java | 2 +- .../restapi/xml/XmlRunReference.java | 8 +- .../restapi/xml/XmlStatisticsDBSettings.java | 2 +- .../com/exactpro/sf/testwebgui/BeanUtil.java | 49 +- .../sf/testwebgui/CustomExceptionHandler.java | 2 +- .../CustomExceptionHandlerFactory.java | 5 +- .../sf/testwebgui/GuiSettingsProxy.java | 24 +- .../exactpro/sf/testwebgui/RedmineLoader.java | 12 +- .../sf/testwebgui/RedmineLoaderRuntime.java | 62 +- .../sf/testwebgui/RevisionFetcher.java | 33 +- .../sf/testwebgui/SFWebApplication.java | 7 +- .../sf/testwebgui/SessionListener.java | 6 +- .../sf/testwebgui/api/IMatrixListener.java | 4 +- .../sf/testwebgui/api/TestToolsAPI.java | 82 +- .../exactpro/sf/testwebgui/auth/AuthBean.java | 11 +- .../testwebgui/bigbutton/BigButtonBean.java | 93 +- .../configuration/AppenderAdapter.java | 15 +- .../configuration/BigButtonConfigBean.java | 2 +- .../testwebgui/configuration/CleanupBean.java | 2 +- .../testwebgui/configuration/ConfigBean.java | 110 +- .../testwebgui/configuration/EMailBean.java | 6 +- .../configuration/EnvironmentEntity.java | 2 +- .../configuration/FlightRecorderBean.java | 18 +- .../configuration/IterableConverter.java | 8 +- .../configuration/IterableValidator.java | 8 +- .../configuration/LoggerAdapter.java | 18 +- .../configuration/NetDumperBean.java | 10 +- .../configuration/ResourceCleaner.java | 2 +- .../SFLogConfigurationVisualizer.java | 13 +- .../configuration/StatisticsConfigBean.java | 12 +- .../configuration/UpdaterConfigBean.java | 23 +- .../configuration/UserEventsBean.java | 8 +- .../sf/testwebgui/context/ContextBean.java | 6 +- .../context/FacesMessageAdapter.java | 6 +- .../context/PopupMessageHolder.java | 7 +- .../dictionaries/AttributeModel.java | 13 +- .../dictionaries/ClassNameConverter.java | 19 +- .../ComplexAttributesUpdateModel.java | 4 +- .../dictionaries/DictFileContainer.java | 47 +- .../DictFileContainerConverter.java | 7 +- .../dictionaries/DictionariesBean.java | 8 +- .../dictionaries/DictionaryEditorModel.java | 721 ++++---- .../dictionaries/EditorModelConverter.java | 8 +- .../dictionaries/FieldEditorModel.java | 320 ++-- .../sf/testwebgui/download/AppZip.java | 36 +- .../sf/testwebgui/download/DownloadBean.java | 94 +- .../sf/testwebgui/download/FileAdapter.java | 28 +- .../download/FileNameComparator.java | 14 +- .../environment/EnumSetContainer.java | 4 +- .../environment/EnvironmentBean.java | 125 +- .../environment/EnvironmentNode.java | 110 +- .../environment/EnvironmentTrackingBean.java | 16 +- .../environment/ServiceEventLazyModel.java | 9 +- .../environment/ServiceNodeLazyModel.java | 110 +- .../sf/testwebgui/general/ErrorBean.java | 2 +- .../sf/testwebgui/general/GeneralBean.java | 19 +- .../sf/testwebgui/general/SessionStorage.java | 12 +- .../sf/testwebgui/general/SessionStored.java | 2 +- .../sf/testwebgui/help/CopyingFormat.java | 64 +- .../exactpro/sf/testwebgui/help/HelpBean.java | 154 +- .../sf/testwebgui/help/HelpContentHolder.java | 45 +- .../testwebgui/help/RedminePageBuilder.java | 4 +- .../sf/testwebgui/help/TextileAdapter.java | 20 +- .../sf/testwebgui/help/search/Search.java | 9 +- .../testwebgui/help/search/SearchOptions.java | 14 +- .../testwebgui/messages/CsvMessageWriter.java | 28 +- .../sf/testwebgui/messages/MessageSorter.java | 34 +- .../sf/testwebgui/messages/MessagesBean.java | 56 +- .../messages/MessagesLazyModel.java | 36 +- .../sf/testwebgui/messages/ScrollWrapper.java | 14 +- .../notifications/chanel/SFWebHandler.java | 2 +- .../notifications/events/EventRetriever.java | 4 +- .../notifications/events/EventSubscriber.java | 2 +- .../events/WebLoggingAppender.java | 8 +- .../matrices/MatrixUpdateRetriever.java | 2 +- .../matrices/MatrixUpdateSubscriber.java | 2 +- .../notifications/messages/CloseChannel.java | 9 +- .../notifications/messages/CloseRequest.java | 9 +- .../messages/EnvironmentUpdateResponse.java | 11 +- .../messages/EventUpdateRequest.java | 8 +- .../messages/EventUpdateResponse.java | 8 +- .../messages/MatrixUpdateRequest.java | 8 +- .../messages/MatrixUpdateResponse.java | 8 +- .../messages/MessagesUpdateEvent.java | 2 +- .../messages/MessagesUpdateRequest.java | 4 - .../messages/MessagesUpdateResponse.java | 4 - .../messages/MessagesUpdateRetriever.java | 2 +- .../messages/MessagesUpdateSubscriber.java | 2 +- .../notifications/messages/NotifyRequest.java | 6 +- .../messages/NotifyResponse.java | 8 +- .../notifications/messages/RequestStatus.java | 9 +- .../messages/ScriptrunnerUpdateRequest.java | 8 +- .../messages/ScriptrunnerUpdateResponse.java | 6 +- .../messages/ServiceUpdateRequest.java | 8 +- .../messages/ServiceUpdateResponse.java | 6 +- .../messages/WrappedConverterUtils.java | 16 +- .../ScriptrunEventHTMLBuilder.java | 50 +- .../ScriptrunUpdateRetriever.java | 4 +- .../ScriptrunUpdateSubscriber.java | 2 +- .../services/EnvironmentUpdateRetriever.java | 2 +- .../services/EnvironmentUpdateSubscriber.java | 2 +- .../testwebgui/restapi/ActionsResource.java | 10 +- .../testwebgui/restapi/BigButtonResource.java | 139 +- .../sf/testwebgui/restapi/CORSFilter.java | 2 +- .../restapi/DictionaryResource.java | 26 +- .../restapi/EnvironmentResource.java | 23 +- .../testwebgui/restapi/InternalResources.java | 5 +- .../sf/testwebgui/restapi/JsonAMLUtil.java | 22 +- .../sf/testwebgui/restapi/JsonMultiError.java | 2 +- .../restapi/MachineLearningResource.java | 19 +- .../restapi/MatrixEditorResource.java | 81 +- .../sf/testwebgui/restapi/MatrixResource.java | 159 +- .../testwebgui/restapi/ResponseResolver.java | 7 +- .../testwebgui/restapi/SFRestApiListener.java | 2 +- .../testwebgui/restapi/ServiceResource.java | 25 +- .../restapi/StatisticsResource.java | 138 +- .../testwebgui/restapi/StorageResource.java | 5 +- .../restapi/TestLibraryResource.java | 7 +- .../restapi/TestscriptRunResource.java | 135 +- .../restapi/VariableSetsResource.java | 7 +- .../restapi/editor/EditorConfig.java | 8 +- .../editor/GuiMatrixEditorStorage.java | 11 +- .../restapi/editor/MatrixWithHistory.java | 19 +- .../editor/UnexpectedMessagesContainer.java | 3 +- .../sf/testwebgui/restapi/json/JsonError.java | 5 +- .../restapi/json/JsonErrorMessage.java | 2 +- .../testwebgui/restapi/json/LogMessage.java | 3 +- .../restapi/json/action/JsonAction.java | 12 +- .../json/dictionary/JsonComplexFieldType.java | 2 +- .../json/dictionary/JsonEnumField.java | 2 +- .../restapi/json/dictionary/JsonField.java | 34 +- .../json/dictionary/JsonSimpleField.java | 2 +- .../json/dictionary/JsonUtilFunction.java | 6 +- .../json/editor/JsonMatrixDescription.java | 6 +- .../restapi/json/editor/JsonMatrixLine.java | 20 +- .../restapi/json/editor/JsonMatrixList.java | 3 +- .../json/editor/JsonMatrixTestCase.java | 6 +- .../editor/JsonTestScriptDescription.java | 16 +- .../json/editor/JsonUpdateTransaction.java | 3 +- .../JsonUpdateTransactionSpliceEntry.java | 3 +- .../scriptruns/JSONMatrixEditor.java | 26 +- .../testwebgui/scriptruns/MatrixAdapter.java | 13 +- .../scriptruns/MatrixEditorBean.java | 12 +- .../testwebgui/scriptruns/MatrixHolder.java | 6 +- .../sf/testwebgui/scriptruns/MatrixType.java | 2 +- .../scriptruns/PlainTextMatrixEditorBean.java | 7 +- .../scriptruns/TestScriptsBean.java | 73 +- .../scriptruns/UploadMatrixBean.java | 11 +- .../scriptruns/converters/ConverterBean.java | 19 +- .../converters/ConverterFormMapAdapter.java | 4 +- .../scriptruns/converters/ConverterModel.java | 2 +- .../scriptruns/converters/ConverterNode.java | 11 +- .../converters/MappingContainer.java | 2 +- .../converters/MatrixNameValidator.java | 2 +- .../servlets/CustomPropertyConfigurator.java | 2 +- .../testwebgui/servlets/PollingServlet.java | 6 +- .../sf/testwebgui/servlets/ReportServlet.java | 6 +- .../sf/testwebgui/servlets/ReportTask.java | 27 +- .../testwebgui/servlets/SFContextServlet.java | 18 +- .../servlets/SessionModelsMapper.java | 14 +- .../statistics/AbstractStatisticsBean.java | 7 +- .../AbstractTagsStatisticsBean.java | 23 +- .../sf/testwebgui/statistics/Action.java | 9 +- .../statistics/SfInstanceConverter.java | 17 +- .../statistics/StatisticsHomeBean.java | 12 +- .../statistics/StatisticsReportingBean.java | 28 +- .../TagGroupDimensionListWrapper.java | 4 - .../TagGroupDimensionalReportBean.java | 108 +- .../statistics/TaggedSetsComparisonBean.java | 100 +- .../testwebgui/statistics/TagsAdminBean.java | 12 +- .../statistics/TestCaseConverter.java | 17 +- .../statistics/TestCaseHistoryBean.java | 34 +- .../statistics/TestScriptsHistoryBean.java | 128 +- .../ModifiableDictionaryStructure.java | 18 +- .../structures/ModifiableFieldStructure.java | 45 +- .../ModifiableMessageStructure.java | 26 +- 870 files changed, 11478 insertions(+), 13664 deletions(-) delete mode 100644 BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLList.java delete mode 100644 BackEnd/Service/service-ntg/src/test/java/com/exactpro/sf/services/ntg/TestNTGClient.java delete mode 100644 BackEnd/Service/service-ntg/src/test/java/com/exactpro/sf/services/ntg/TestNTGClientNTGServer.java diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/BaseMessage.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/BaseMessage.java index 7775bfd0..e7a9d615 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/BaseMessage.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/BaseMessage.java @@ -31,7 +31,7 @@ public BaseMessage(IMessage message) public IMessage getMessage() { - return this.msg; + return msg; } public boolean isAdmin(){ @@ -40,15 +40,12 @@ public boolean isAdmin(){ @Override public BaseMessage clone() { - Constructor ctor = null; - BaseMessage clone = null; - try { - ctor = this.getClass().getConstructor(IMessage.class); - clone = ctor.newInstance(this.msg.cloneMessage()); + try { + Constructor ctor = getClass().getConstructor(IMessage.class); + return ctor.newInstance(msg.cloneMessage()); } catch (Exception e) { throw new EPSCommonException(e); } - return clone; - } + } } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/DefaultMessageFactory.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/DefaultMessageFactory.java index f444a400..8617d834 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/DefaultMessageFactory.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/DefaultMessageFactory.java @@ -21,7 +21,7 @@ public class DefaultMessageFactory extends AbstractMessageFactory { - private static IMessageFactory factory = null; + private static IMessageFactory factory; private DefaultMessageFactory() {} @@ -29,8 +29,9 @@ public static IMessageFactory getFactory() { synchronized (DefaultMessageFactory.class) { - if ( factory == null ) - factory = new DefaultMessageFactory(); + if(factory == null) { + factory = new DefaultMessageFactory(); + } } return factory; diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/MapMessage.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/MapMessage.java index dc6b68b0..b1981a6a 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/MapMessage.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/MapMessage.java @@ -15,8 +15,10 @@ ******************************************************************************/ package com.exactpro.sf.common.impl.messages; - import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -27,9 +29,6 @@ import org.apache.commons.lang3.builder.HashCodeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; import com.exactpro.sf.common.impl.messages.xml.configuration.JavaType; import com.exactpro.sf.common.messages.FieldMetaData; @@ -46,8 +45,8 @@ public class MapMessage implements IMessage { private static final Logger logger = LoggerFactory.getLogger(MapMessage.class ); - private Map fieldsMap = new HashMap<>(); - private Map fieldsMetaData = new HashMap<>(); + private final Map fieldsMap = new HashMap<>(); + private final Map fieldsMetaData = new HashMap<>(); private MsgMetaData msgMetaData; private String namespace; private String name; @@ -95,7 +94,7 @@ public Map getFieldsMap(){ return resultFieldsMap; } - @JsonSetter(value = "fieldsMap") + @JsonSetter("fieldsMap") public void addFieldsMap(Map fieldsMap){ this.fieldsMap.putAll(fieldsMap); } @@ -112,7 +111,7 @@ public T getField(String name) { throw new IllegalArgumentException("[name] could not be null"); } - return (T)this.fieldsMap.get(name); + return (T)fieldsMap.get(name); } @Override @@ -145,21 +144,20 @@ public String getNamespace() @Override public Object removeField(String name) { - if ( null == name ) + if(name == null) { throw new IllegalArgumentException("[name] could not be null"); } - return this.fieldsMap.remove(name); + return fieldsMap.remove(name); } @Override public MapMessage cloneMessage() { - MapMessage cloned = new MapMessage( this.namespace, this.name ); + MapMessage cloned = new MapMessage(namespace, name); - for( String fldName : this.fieldsMap.keySet()) - { - cloned.addField(fldName, clone(this.fieldsMap.get(fldName))); + for(String fldName : fieldsMap.keySet()) { + cloned.addField(fldName, clone(fieldsMap.get(fldName))); } cloned.msgMetaData = msgMetaData.clone(); @@ -169,8 +167,9 @@ public MapMessage cloneMessage() private Object clone (Object o) { - if (o instanceof IMessage) - return ((IMessage) o).cloneMessage(); + if(o instanceof IMessage) { + return ((IMessage)o).cloneMessage(); + } if (o instanceof List) { List list = new ArrayList<>(); @@ -199,78 +198,76 @@ public boolean compare( IMessage message ) boolean equal = true; - if(!this.namespace.equals( message.getNamespace())) + if(!namespace.equals(message.getNamespace())) { equal = false; logger.debug("Comparision failed. Message name [{}]. Namespaces mismatch: this [{}], other [{}].", - this.name, this.namespace, message.getNamespace()); - } - else if (! this.name.equals(message.getName())) + name, namespace, message.getNamespace()); + } else if(!name.equals(message.getName())) { equal = false; logger.debug("Comparision failed. Message name [{}]. Names mismatch: this [{}], other [{}].", - this.name, this.name, message.getName()); + name, name, message.getName()); } else { - for( String fldName : this.getFieldNames() ) + for(String fldName : getFieldNames()) { if( ! message.getFieldNames().contains(fldName)) { equal = false; logger.debug("Comparision failed. Message name [{}]. Other message does not contain field: [{}].", - this.name, fldName ); + name, fldName); - break; + return equal; } else { - if(( this.getField( fldName ) instanceof MapMessage) - || (this.getField( fldName ) instanceof MapMessage[]) + if((getField(fldName) instanceof MapMessage) + || (getField(fldName) instanceof MapMessage[]) || ( message.getField( fldName ) instanceof MapMessage) || (message.getField( fldName ) instanceof MapMessage[])) { - if(! ((( this.getField( fldName ) instanceof MapMessage[]) && + if(!(((getField(fldName) instanceof MapMessage[]) && ( message.getField( fldName ) instanceof MapMessage[] )) - ||(( this.getField( fldName ) instanceof MapMessage) && + || ((getField(fldName) instanceof MapMessage) && ( message.getField( fldName ) instanceof MapMessage )))) { equal = false; logger.debug("Comparision failed. Message name [{}]. Field name: [{}]. Types mismatch. Class this: [{}], class other: [{}].", - this.name, fldName, - this.getField( fldName ).getClass(), + name, fldName, + getField(fldName).getClass(), message.getField( fldName ).getClass()); - break; + return equal; } else { - if( this.getField( fldName ) instanceof IMessage ) + if(getField(fldName) instanceof IMessage) { - equal = ((IMessage)this.getField( fldName )) + equal = ((IMessage)getField(fldName)) .compare((IMessage) message.getField( fldName )); if(! equal ) { - break; + return equal; } } else { - IMessage[] thisArr = (IMessage[]) this.getField( fldName ); + IMessage[] thisArr = (IMessage[])getField(fldName); IMessage[] thatArr = (IMessage[]) message.getField( fldName ); if(thisArr.length != thatArr.length) { logger.debug("Comparision failed. Message name [{}]. Field name: [{}]. Arrays lengths are not equal. this: [{}], other: [{}].", - this.name, fldName, thisArr.length, thatArr.length); - equal = false; - break; - } + name, fldName, thisArr.length, thatArr.length); + return false; + } for( int i = 0 ; i < thisArr.length; i++ ) { @@ -279,33 +276,33 @@ else if (! this.name.equals(message.getName())) if(! equal ) { logger.debug("Comparision failed. Message name [{}]. Field name: [{}]. Sub messages at index [{}] are not equal.", - this.name, fldName, i ); + name, fldName, i); break; } } if(! equal ) { - break; + return equal; } } } } else { - if( this.getFieldType(fldName) != ((MapMessage)message).getFieldType(fldName)) + if(getFieldType(fldName) != ((MapMessage)message).getFieldType(fldName)) { equal = false; logger.debug("Comparision failed. Message name [{}]. Field name: [{}]. FieldType mismatch. this: [{}], other: [{}].", - this.name, fldName, - this.getFieldType(fldName), + name, fldName, + getFieldType(fldName), ((MapMessage)message).getFieldType(fldName)); - break; + return equal; } else { - Object valueThis = this.getField( fldName ); + Object valueThis = getField(fldName); Object valueThat = message.getField( fldName ); if(! compareValues(fldName, valueThis, valueThat)) @@ -315,11 +312,11 @@ else if (! this.name.equals(message.getName())) equal = false; logger.debug("Comparision failed. Message name [{}]. Field name: [{}]. Values mismatch. this: [{}], other: [{}].", - this.name, fldName, + name, fldName, valueThis, valueThat); - break; + return equal; } } } @@ -331,9 +328,8 @@ else if (! this.name.equals(message.getName())) private boolean compareValues(String fieldname, Object valueThis, Object valueThat) { - boolean equal = false; - Class clazzThis = valueThis.getClass(); + Class clazzThis = valueThis.getClass(); Class clazzThat = valueThat.getClass(); if(clazzThis == clazzThat) @@ -341,7 +337,7 @@ private boolean compareValues(String fieldname, Object valueThis, Object valueTh Object castedThis = clazzThis.cast(valueThis); Object castedThat = clazzThis.cast(valueThat); - if(BigDecimal.class == clazzThis) + if(clazzThis == BigDecimal.class) { BigDecimal bigDecimalThis = (BigDecimal)castedThis; BigDecimal bigDecimalThat = (BigDecimal)castedThat; @@ -349,23 +345,23 @@ private boolean compareValues(String fieldname, Object valueThis, Object valueTh if(subtract.doubleValue() == 0.0 ) { - equal = true; + return true; } } else if(castedThis.equals( castedThat)) { - equal = true; + return true; } } else { logger.debug("Comparision failed. Message name [{}]. Field name: [{}]. Types mismatch. this: [{}], other: [{}].", - this.name, fieldname, + name, fieldname, clazzThis, clazzThat); } - return equal; + return false; } @Override @@ -383,39 +379,35 @@ public int getFieldCount() { public JavaType getFieldType(String name) { - if ( null == name ) + if(name == null) { throw new IllegalArgumentException("[name] could not be null"); } - JavaType fieldType = null; - - if (this.fieldsMap.containsKey(name)) - { - Object field = this.fieldsMap.get(name); - fieldType = JavaType.fromValue(field.getClass().getCanonicalName()); + if(fieldsMap.containsKey(name)) { + Object field = fieldsMap.get(name); + return JavaType.fromValue(field.getClass().getCanonicalName()); } else { throw new EPSCommonException( String.format( "Field [%s] is not defined in the message. " + "Details: namespace [%s], message name [%s].", - name, this.namespace, this.name )); - } - return fieldType; - } + name, namespace, this.name)); + } + } @Override public String toString() { StringBuilder toString = new StringBuilder(1024); - for(String fldName : this.getFieldNames()) { + for(String fldName : getFieldNames()) { if(toString.length() > 0) { toString.append('|'); } - if(this.getField(fldName) instanceof IMessage) { - toString.append(((MapMessage)this.getField(fldName)).toString()); + if(getField(fldName) instanceof IMessage) { + toString.append((MapMessage)getField(fldName)); } else { toString.append(fldName); toString.append('='); @@ -430,11 +422,8 @@ public String toString() { @Override public IFieldInfo getFieldInfo(String name) { - if ( this.fieldsMap.containsKey(name) ) - return new MapFieldInfo(name, this.fieldsMap.get(name)); - - return null; - } + return fieldsMap.containsKey(name) ? new MapFieldInfo(name, fieldsMap.get(name)) : null; + } public void setNamespace(String namespace) { this.namespace = namespace; @@ -447,8 +436,8 @@ public void setName(String name) { private class MapFieldInfo implements IFieldInfo { - private String fldName; - private Object value; + private final String fldName; + private final Object value; private MapFieldInfo(String name, Object value) @@ -467,7 +456,7 @@ public FieldType getFieldType() @Override public String getName() { - return this.fldName; + return fldName; } @@ -507,50 +496,65 @@ else if ( value instanceof boolean[] || private FieldType convert(Object value) { - if ( value == null ) - throw new NullPointerException("value"); + if(value == null) { + throw new NullPointerException("value"); + } - if ( value instanceof IMessage ) - return FieldType.SUBMESSAGE; + if(value instanceof IMessage) { + return FieldType.SUBMESSAGE; + } - if ( value instanceof Boolean || value instanceof boolean[] ) - return FieldType.BOOLEAN; + if(value instanceof Boolean || value instanceof boolean[]) { + return FieldType.BOOLEAN; + } - if ( value instanceof Short || value instanceof short[] ) - return FieldType.SHORT; + if(value instanceof Short || value instanceof short[]) { + return FieldType.SHORT; + } - if ( value instanceof Integer || value instanceof int[] ) - return FieldType.INT; + if(value instanceof Integer || value instanceof int[]) { + return FieldType.INT; + } - if ( value instanceof Long || value instanceof long[] ) - return FieldType.LONG; + if(value instanceof Long || value instanceof long[]) { + return FieldType.LONG; + } - if ( value instanceof Byte || value instanceof byte[] ) - return FieldType.BYTE; + if(value instanceof Byte || value instanceof byte[]) { + return FieldType.BYTE; + } - if ( value instanceof Float || value instanceof float[] ) - return FieldType.FLOAT; + if(value instanceof Float || value instanceof float[]) { + return FieldType.FLOAT; + } - if ( value instanceof Double || value instanceof double[] ) - return FieldType.DOUBLE; + if(value instanceof Double || value instanceof double[]) { + return FieldType.DOUBLE; + } - if ( value instanceof String || value instanceof String[] ) - return FieldType.STRING; + if(value instanceof String || value instanceof String[]) { + return FieldType.STRING; + } - if ( value instanceof LocalDateTime || value instanceof LocalDateTime[] ) + if(value instanceof LocalDateTime || value instanceof LocalDateTime[]) { return FieldType.DATE_TIME; + } - if ( value instanceof LocalDate || value instanceof LocalDate[] ) + if(value instanceof LocalDate || value instanceof LocalDate[]) { return FieldType.DATE; + } - if ( value instanceof LocalTime || value instanceof LocalTime[] ) + if(value instanceof LocalTime || value instanceof LocalTime[]) { return FieldType.TIME; + } - if ( value instanceof Character || value instanceof char[] ) - return FieldType.CHAR; + if(value instanceof Character || value instanceof char[]) { + return FieldType.CHAR; + } - if ( value instanceof BigDecimal || value instanceof BigDecimal[] ) - return FieldType.DECIMAL; + if(value instanceof BigDecimal || value instanceof BigDecimal[]) { + return FieldType.DECIMAL; + } throw new EPSCommonException("Cannot associate [" + value.getClass().getCanonicalName() + "] with FieldType" ); } @@ -580,11 +584,11 @@ public boolean equals(Object obj) { MapMessage that = (MapMessage)obj; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.name, that.name); - builder.append(this.namespace, that.namespace); - builder.append(this.msgMetaData, that.msgMetaData); - builder.append(this.fieldsMap, that.fieldsMap); - builder.append(this.fieldsMetaData, that.fieldsMetaData); + builder.append(name, that.name); + builder.append(namespace, that.namespace); + builder.append(msgMetaData, that.msgMetaData); + builder.append(fieldsMap, that.fieldsMap); + builder.append(fieldsMetaData, that.fieldsMetaData); return builder.isEquals(); } @@ -593,11 +597,11 @@ public boolean equals(Object obj) { public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); - builder.append(this.name); - builder.append(this.namespace); - builder.append(this.msgMetaData); - builder.append(this.fieldsMap); - builder.append(this.fieldsMetaData); + builder.append(name); + builder.append(namespace); + builder.append(msgMetaData); + builder.append(fieldsMap); + builder.append(fieldsMetaData); return builder.toHashCode(); } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/XMLTransmitter.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/XMLTransmitter.java index ef095e9e..fbba4dbf 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/XMLTransmitter.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/XMLTransmitter.java @@ -42,6 +42,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.format.DateTimeFormatter; + +import org.w3c.dom.Node; import org.xml.sax.SAXException; import com.exactpro.sf.common.util.EPSCommonException; @@ -49,9 +51,9 @@ public class XMLTransmitter { - private static Logger logger = LoggerFactory.getLogger(XMLTransmitter.class); + private static final Logger logger = LoggerFactory.getLogger(XMLTransmitter.class); - private static XMLTransmitter instance = new XMLTransmitter(); + private static final XMLTransmitter instance = new XMLTransmitter(); private final Map contexts = new HashMap<>(); @@ -61,7 +63,7 @@ private JAXBContext getContext(Class tclass) throws Exception { JAXBContext context; Package pack = tclass.getPackage(); if(contexts.containsKey(pack)){ - context = contexts.get(pack); + return contexts.get(pack); }else{ context = JAXBContext.newInstance(pack.getName()); contexts.put(pack, context); @@ -75,7 +77,7 @@ private static class ValidationEventWriteHandler implements ValidationEventHandl public boolean handleEvent(ValidationEvent ve) { String msg = ve.getMessage(); ValidationEventLocator vel = ve.getLocator(); - org.w3c.dom.Node node = vel.getNode(); + Node node = vel.getNode(); String name = node!=null?node.getLocalName():"null"; logger.error( "node : {}.{}: {}", name, vel.getOffset(), msg ); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/ConverterVisitor.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/ConverterVisitor.java index 5ff46d9d..4f42df87 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/ConverterVisitor.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/ConverterVisitor.java @@ -36,16 +36,16 @@ public class ConverterVisitor implements IMessageStructureVisitor { - private static Logger logger = LoggerFactory.getLogger(ConverterVisitor.class); + private static final Logger logger = LoggerFactory.getLogger(ConverterVisitor.class); - private static int COUNTER = 0; + private static int COUNTER; - synchronized public static int getId() { + public static synchronized int getId() { return COUNTER++; } - private Message xmlMessage; - private Dictionary dictionary; + private final Message xmlMessage; + private final Dictionary dictionary; public ConverterVisitor(Message xmlMessage, Dictionary dictionary) { this.xmlMessage = xmlMessage; @@ -79,10 +79,9 @@ public void visit(String fieldName, IFieldStructure fldStruct, Class clazz) { }); if (fldStruct.isEnum()) { - Field enumXmlField; - enumXmlField = XmlDictionaryUtils.getDictionaryField(dictionary, - fldStruct.getName()); + Field enumXmlField = XmlDictionaryUtils.getDictionaryField(dictionary, + fldStruct.getName()); if (enumXmlField == null) { enumXmlField = new Field(); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/XmlDictionaryUtils.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/XmlDictionaryUtils.java index 2ec8006c..fa044ebb 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/XmlDictionaryUtils.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/impl/messages/xml/converter/XmlDictionaryUtils.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import com.exactpro.sf.common.impl.messages.xml.configuration.Dictionary; import com.exactpro.sf.common.impl.messages.xml.configuration.Field; @@ -54,11 +55,11 @@ public static List> getGroupFieldsName(IFieldStructure field return fieldsName; } - protected static List> getGroupFieldsName(Message field){ + protected static List> getGroupFieldsName(Message field){ if(field == null){ return null; } - List> groupFieldsName = new ArrayList>(); + List> groupFieldsName = new ArrayList>(); Message subField = (Message)field.getReference(); if(subField == null){ for(Field fieldName: field.getFields()){ diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/DirtyMessageTraverser.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/DirtyMessageTraverser.java index 6eba4cba..2efe7129 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/DirtyMessageTraverser.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/DirtyMessageTraverser.java @@ -10,18 +10,16 @@ package com.exactpro.sf.common.messages; -import com.exactpro.sf.common.impl.messages.xml.configuration.JavaType; -import com.exactpro.sf.common.messages.ReorderFieldComparator; -import com.exactpro.sf.common.messages.structures.IFieldStructure; -import com.exactpro.sf.common.util.EPSCommonException; +import static com.exactpro.sf.common.messages.DirtyConst.EXCLUDED_FIELD; +import static com.exactpro.sf.common.messages.DirtyConst.FIELD_ORDER; import java.util.List; import java.util.Map; import java.util.TreeMap; -import static com.exactpro.sf.common.messages.DirtyConst.FIELD_ORDER; -import static com.exactpro.sf.common.messages.DirtyConst.EXCLUDED_FIELD; -import static com.exactpro.sf.common.messages.DirtyConst.FIELD_ORDER; +import com.exactpro.sf.common.impl.messages.xml.configuration.JavaType; +import com.exactpro.sf.common.messages.structures.IFieldStructure; +import com.exactpro.sf.common.util.EPSCommonException; public class DirtyMessageTraverser extends MessageTraverser { @@ -75,8 +73,9 @@ protected List validateFieldOrderValue(Object fieldValue, Class type) public void visitSimpleField(IFieldStructure curField, IMessageStructureVisitor msgStrVisitor, JavaType javaType, String fieldName, Object value, boolean isDefault) { - if (dropMetaField(curField, value)) + if(dropMetaField(curField, value)) { return; + } super.visitSimpleField(curField, msgStrVisitor, javaType, fieldName, value, isDefault); } @@ -85,8 +84,9 @@ public void visitSimpleField(IFieldStructure curField, IMessageStructureVisitor protected void visitField(IFieldStructure curField, IMessageStructureVisitor msgStrVisitor, IMessageStructureReaderHandler handler, String fieldName, Object value) { - if (dropMetaField(curField, value)) + if(dropMetaField(curField, value)) { return; + } super.visitField(curField, msgStrVisitor, handler, fieldName, value); } @@ -94,17 +94,14 @@ protected void visitField(IFieldStructure curField, IMessageStructureVisitor msg @Override protected void visitComplexField(IFieldStructure curField, IMessageStructureVisitor msgStrVisitor, String fieldName, Object value) { - if (dropMetaField(curField, value)) + if(dropMetaField(curField, value)) { return; + } super.visitComplexField(curField, msgStrVisitor, fieldName, value); } private boolean dropMetaField(IFieldStructure curField, Object value) { - if (value == EXCLUDED_FIELD) - return true; - if (curField.getName().equals(FIELD_ORDER)) - return true; - return false; + return value == EXCLUDED_FIELD || curField.getName().equals(FIELD_ORDER); } } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/EmptyMessageStructureReaderHandler.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/EmptyMessageStructureReaderHandler.java index d163bffa..82008682 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/EmptyMessageStructureReaderHandler.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/EmptyMessageStructureReaderHandler.java @@ -19,7 +19,7 @@ public class EmptyMessageStructureReaderHandler implements IMessageStructureReaderHandler { - private static EmptyMessageStructureReaderHandler instance = new EmptyMessageStructureReaderHandler(); + private static final EmptyMessageStructureReaderHandler instance = new EmptyMessageStructureReaderHandler(); private EmptyMessageStructureReaderHandler() { } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/HumanMessageStructureVisitor.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/HumanMessageStructureVisitor.java index 9d88ae34..62adffbe 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/HumanMessageStructureVisitor.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/HumanMessageStructureVisitor.java @@ -16,12 +16,11 @@ package com.exactpro.sf.common.messages; import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; import com.exactpro.sf.common.messages.structures.IFieldStructure; @@ -251,7 +250,7 @@ public void visitMessageCollection(String fieldName, List messages, IF * @param traverser */ protected IHumanMessage visit(String fieldName, IMessage message, IFieldStructure complexField, MessageTraverser traverser) { - HumanMessageStructureVisitor visitor = new HumanMessageStructureVisitor(this.messageFactory, complexField.getName()); + HumanMessageStructureVisitor visitor = new HumanMessageStructureVisitor(messageFactory, complexField.getName()); traverser.traverse(visitor, complexField.getFields(), message, EmptyMessageStructureReaderHandler.instance()); return visitor.getHumanMessage(); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IFieldInfo.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IFieldInfo.java index 2d1971f0..255e2898 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IFieldInfo.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IFieldInfo.java @@ -32,8 +32,8 @@ enum FieldType TIME, CHAR, DECIMAL, - SUBMESSAGE; - } + SUBMESSAGE + } FieldType getFieldType(); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IHumanMessage.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IHumanMessage.java index a95c7d77..4571dafb 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IHumanMessage.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IHumanMessage.java @@ -19,6 +19,6 @@ public interface IHumanMessage { - public void addField(IFieldStructure fieldStructure, String fieldName, Object value); + void addField(IFieldStructure fieldStructure, String fieldName, Object value); } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessage.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessage.java index d44a97a0..e45d9c29 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessage.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessage.java @@ -37,24 +37,24 @@ public interface IMessage MsgMetaData getMetaData(); - void addField(final String name, final Object value); + void addField(String name, Object value); - Object removeField(final String name); + Object removeField(String name); - T getField(final String name); + T getField(String name); - FieldMetaData getFieldMetaData(final String name); + FieldMetaData getFieldMetaData(String name); - boolean isFieldSet(final String name); + boolean isFieldSet(String name); Set getFieldNames(); int getFieldCount(); - IFieldInfo getFieldInfo(final String name); + IFieldInfo getFieldInfo(String name); IMessage cloneMessage(); - boolean compare(final IMessage message); + boolean compare(IMessage message); } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessageFactory.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessageFactory.java index 1f1aabfd..6224a8f6 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessageFactory.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/IMessageFactory.java @@ -23,13 +23,13 @@ public interface IMessageFactory { void init(String namespace, SailfishURI dictionaryURI); - public IMessage createMessage(String name, String namespace); + IMessage createMessage(String name, String namespace); - public IMessage createMessage(String name); + IMessage createMessage(String name); - public IHumanMessage createHumanMessage(String name); + IHumanMessage createHumanMessage(String name); - public void fillMessageType(IMessage message); + void fillMessageType(IMessage message); Set getUncheckedFields(); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReader.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReader.java index 65e792f7..3ec87aa6 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReader.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReader.java @@ -32,20 +32,16 @@ public class MessageStructureReader { - private final static Logger LOGGER = LoggerFactory.getLogger(MessageStructureReader.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MessageStructureReader.class); - public MessageStructureReader() { - } - - - public void traverse(IMessageStructureVisitor msgStrVisitor, + public void traverse(IMessageStructureVisitor msgStrVisitor, IMessageStructure msgStructure, IMessage message, IMessageStructureReaderHandler handler) { try { - this.traverse(msgStrVisitor, msgStructure.getFields(), message, handler); + traverse(msgStrVisitor, msgStructure.getFields(), message, handler); } catch ( Exception e ) { @@ -67,7 +63,9 @@ public void traverse(IMessageStructureVisitor msgStrVisitor, { fields.forEach((fieldName, curField) -> { - if (message == null) throw new NullPointerException("message is null for field "+fieldName); + if(message == null) { + throw new NullPointerException("message is null for field " + fieldName); + } Object value = message.getField(fieldName); @@ -119,154 +117,167 @@ public void visitSimpleField(IFieldStructure curField, IMessageStructureVisitor switch ( javaType ) { case JAVA_LANG_BOOLEAN : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit(fieldName, (Boolean)value, curField, isDefault); - else + } else { msgStrVisitor.visitBooleanCollection(fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_SHORT : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (Short)value, curField, isDefault); - else + } else { msgStrVisitor.visitShortCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_INTEGER : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (Integer)value, curField, isDefault); - else + } else { msgStrVisitor.visitIntCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_LONG : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (Long)value, curField, isDefault); - else + } else { msgStrVisitor.visitLongCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_BYTE : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( curField.getName(), (Byte)value, curField, isDefault); - else + } else { msgStrVisitor.visitByteCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_FLOAT : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (Float)value, curField, isDefault); - else + } else { msgStrVisitor.visitFloatCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_DOUBLE : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (Double)value, curField, isDefault); - else + } else { msgStrVisitor.visitDoubleCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_STRING : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (String)value, curField, isDefault); - else + } else { msgStrVisitor.visitStringCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_TIME_LOCAL_DATE_TIME: - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (LocalDateTime) value, curField, isDefault); - else + } else { msgStrVisitor.visitDateTimeCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_TIME_LOCAL_DATE: - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (LocalDate) value, curField, isDefault); - else + } else { msgStrVisitor.visitDateCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_TIME_LOCAL_TIME: - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (LocalTime) value, curField, isDefault); - else + } else { msgStrVisitor.visitTimeCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_LANG_CHARACTER: - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (Character)value, curField, isDefault); - else + } else { msgStrVisitor.visitCharCollection( fieldName, (List)value, curField, isDefault); + } break; case JAVA_MATH_BIG_DECIMAL: - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit( fieldName, (BigDecimal)value, curField, isDefault); - else + } else { msgStrVisitor.visitBigDecimalCollection( fieldName, (List)value, curField, isDefault); + } break; default: throw new EPSCommonException("Unknown FieldType = [" + diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReaderHandlerImpl.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReaderHandlerImpl.java index 5d56b2cb..92939aa8 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReaderHandlerImpl.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureReaderHandlerImpl.java @@ -20,7 +20,7 @@ public class MessageStructureReaderHandlerImpl implements IMessageStructureReaderHandler { - private static MessageStructureReaderHandlerImpl instance = new MessageStructureReaderHandlerImpl(); + private static final MessageStructureReaderHandlerImpl instance = new MessageStructureReaderHandlerImpl(); private MessageStructureReaderHandlerImpl(){} diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureWriter.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureWriter.java index 862d4f70..1686f641 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureWriter.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageStructureWriter.java @@ -29,18 +29,13 @@ public class MessageStructureWriter { - - public MessageStructureWriter() - { - } - - - public void traverse(IMessageStructureVisitor msgStrVisitor, - IMessageStructure msgStructure) + + public void traverse(IMessageStructureVisitor msgStrVisitor, + IMessageStructure msgStructure) { try { - this.traverse(msgStrVisitor, msgStructure.getFields()); + traverse(msgStrVisitor, msgStructure.getFields()); } catch ( Exception e ) { @@ -60,82 +55,95 @@ public void traverse(IMessageStructureVisitor msgStrVisitor, switch ( javaType ) { case JAVA_LANG_BOOLEAN : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Boolean)null, curField, false); - else - msgStrVisitor.visitBooleanCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Boolean)null, curField, false); + } else { + msgStrVisitor.visitBooleanCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_SHORT : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Short) null, curField, false); - else - msgStrVisitor.visitShortCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Short)null, curField, false); + } else { + msgStrVisitor.visitShortCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_INTEGER : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Integer)null, curField, false); - else - msgStrVisitor.visitIntCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Integer)null, curField, false); + } else { + msgStrVisitor.visitIntCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_LONG : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Long) null, curField, false); - else - msgStrVisitor.visitLongCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Long)null, curField, false); + } else { + msgStrVisitor.visitLongCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_BYTE : - if ( !curField.isCollection() ) - msgStrVisitor.visit(curField.getName(), (Byte) null, curField, false); - else - msgStrVisitor.visitByteCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(curField.getName(), (Byte)null, curField, false); + } else { + msgStrVisitor.visitByteCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_FLOAT : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Float) null, curField, false); - else - msgStrVisitor.visitFloatCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Float)null, curField, false); + } else { + msgStrVisitor.visitFloatCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_DOUBLE : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Double) null, curField, false); - else - msgStrVisitor.visitDoubleCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Double)null, curField, false); + } else { + msgStrVisitor.visitDoubleCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_STRING : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (String) null, curField, false); - else - msgStrVisitor.visitStringCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (String)null, curField, false); + } else { + msgStrVisitor.visitStringCollection(fieldName, null, curField, false); + } break; case JAVA_TIME_LOCAL_DATE_TIME : - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (LocalDateTime) null, curField, false); - else - msgStrVisitor.visitDateTimeCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (LocalDateTime)null, curField, false); + } else { + msgStrVisitor.visitDateTimeCollection(fieldName, null, curField, false); + } break; case JAVA_TIME_LOCAL_DATE : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit(fieldName, (LocalDate) null, curField, false); - else + } else { msgStrVisitor.visitDateCollection(fieldName, null, curField, false); + } break; case JAVA_TIME_LOCAL_TIME : - if ( !curField.isCollection() ) + if(!curField.isCollection()) { msgStrVisitor.visit(fieldName, (LocalTime) null, curField, false); - else + } else { msgStrVisitor.visitTimeCollection(fieldName, null, curField, false); + } break; case JAVA_LANG_CHARACTER: - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (Character) null, curField, false); - else - msgStrVisitor.visitCharCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (Character)null, curField, false); + } else { + msgStrVisitor.visitCharCollection(fieldName, null, curField, false); + } break; case JAVA_MATH_BIG_DECIMAL: - if ( !curField.isCollection() ) - msgStrVisitor.visit(fieldName, (BigDecimal) null, curField, false); - else - msgStrVisitor.visitBigDecimalCollection(fieldName, null, curField, false); + if(!curField.isCollection()) { + msgStrVisitor.visit(fieldName, (BigDecimal)null, curField, false); + } else { + msgStrVisitor.visitBigDecimalCollection(fieldName, null, curField, false); + } break; default: throw new EPSCommonException("Unknown FieldType = [" + @@ -150,13 +158,8 @@ public void traverse(IMessageStructureVisitor msgStrVisitor, } } } catch (RuntimeException e) { - StringBuilder builder; - if(e.getMessage() != null) { - builder = new StringBuilder(e.getMessage()); - } else { - builder = new StringBuilder(); - } - builder.append(". in field name = [").append(fieldName).append("]"); + StringBuilder builder = e.getMessage() != null ? new StringBuilder(e.getMessage()) : new StringBuilder(); + builder.append(". in field name = [").append(fieldName).append("]"); throw new EPSCommonException(builder.toString(), e); } }); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageTraverser.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageTraverser.java index 275a3a49..9e526308 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageTraverser.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageTraverser.java @@ -21,8 +21,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -39,9 +37,6 @@ public class MessageTraverser extends MessageStructureReader { private final IMessageStructure emptyMessageStructure = new MessageStructure("Empty", "Empty", false, null); - - public MessageTraverser() { - } @Override public void traverse(IMessageStructureVisitor msgStrVisitor, @@ -119,7 +114,7 @@ protected void visitComplexField(IFieldStructure curField, IMessageStructureVisi value = ((List) value).stream() .map(msg -> { if (msg instanceof Map) { - msg = MessageUtil.convertToIMessage((Map) msg, DefaultMessageFactory.getFactory(), namespace, name); + return MessageUtil.convertToIMessage((Map)msg, DefaultMessageFactory.getFactory(), namespace, name); } return msg; }).collect(Collectors.toList()); @@ -134,24 +129,24 @@ protected void visitComplexField(IFieldStructure curField, IMessageStructureVisi } protected IFieldStructure createFieldStructure(IFieldStructure fieldStructure, String namespace, String fieldName, Object value) { - Optional optional = Optional.ofNullable(value); - if (optional.isPresent()) { + if(value != null) { boolean isCollection = false; JavaType javaType = null; StructureType structureType = (fieldStructure != null && !fieldStructure.isComplex()) ? fieldStructure.getStructureType() : StructureType.SIMPLE; - if (optional.get() instanceof List) { + if(value instanceof List) { isCollection = true; - optional = ((List) optional.get()).stream() - .filter(Objects::nonNull).findFirst(); + value = ((List)value).stream() + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } - if (optional.isPresent()) { - if ((optional.get() instanceof IMessage) || - (optional.get() instanceof HashMap)) { + if(value != null) { + if((value instanceof IMessage) || (value instanceof HashMap)) { structureType = StructureType.COMPLEX; } else { - javaType = ObjectUtils.defaultIfNull(getJavaTypeSafe(optional.get().getClass().getCanonicalName()), JavaType.JAVA_LANG_STRING); + javaType = ObjectUtils.defaultIfNull(getJavaTypeSafe(value.getClass().getCanonicalName()), JavaType.JAVA_LANG_STRING); } } @@ -167,11 +162,11 @@ protected IFieldStructure createFieldStructure(IFieldStructure fieldStructure, S } } } - + if (fieldStructure == null) { - fieldStructure = new FieldStructure(fieldName, namespace, JavaType.JAVA_LANG_STRING, false, StructureType.SIMPLE); + return new FieldStructure(fieldName, namespace, JavaType.JAVA_LANG_STRING, false, StructureType.SIMPLE); } - + return fieldStructure; } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageUtil.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageUtil.java index 1027e617..a40b0b2e 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageUtil.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MessageUtil.java @@ -44,13 +44,16 @@ public class MessageUtil private static final AtomicLong counter = new AtomicLong(); public static final String MESSAGE_REJECTED_POSTFIX = " (REJECTED)"; - - public static String toString(final IMessage msg, String separator) + + public static String toString(IMessage msg, String separator) { - StringBuilder result = new StringBuilder(128); + if(msg == null) { + return "null"; + } - result.append(( msg == null ) ? "null" : ""); - for ( String fldName : msg.getFieldNames() ) + StringBuilder result = new StringBuilder(128); + + for(String fldName : msg.getFieldNames()) { IFieldInfo fldInfo = msg.getFieldInfo(fldName); @@ -63,12 +66,10 @@ public static String toString(final IMessage msg, String separator) } else { result.append('{'); for(Object o : vals) { - if (o == null) { - result.append("null"); - } else if (o instanceof IMessage) { + if(o instanceof IMessage) { result.append(toString((IMessage) o, separator)); } else { - result.append(o.toString()); + result.append(o); } result.append(separator); } @@ -85,7 +86,7 @@ public static String toString(final IMessage msg, String separator) } else { - result.append(fldInfo.getValue().toString()); + result.append(fldInfo.getValue()); result.append(separator); } } @@ -104,18 +105,12 @@ public static HashMap convertToHashMap(IMessage message) { List list = new ArrayList<>(); for (Object element : (List)value) { - if (element instanceof IMessage) { - list.add(convertToHashMap((IMessage) element)); - } else { - list.add(element); - } + list.add(element instanceof IMessage ? convertToHashMap((IMessage)element) : element); } result.put(fieldName, list); - } else if (value instanceof IMessage) { - result.put(fieldName, convertToHashMap((IMessage) value)); } else { - result.put(fieldName, value); + result.put(fieldName, value instanceof IMessage ? convertToHashMap((IMessage)value) : value); } } @@ -134,29 +129,22 @@ public static IHumanMessage convertToIHumanMessage(IMessageFactory messageFactor public static IMessage convertToIMessage(Map map, IMessageFactory messageFactory, String namespace, String name) { if (map != null) { messageFactory = messageFactory != null ? messageFactory : DefaultMessageFactory.getFactory(); - IMessage result = messageFactory.createMessage(name, namespace); - String key = null; - for (Entry entry : map.entrySet()) { - key = String.class.cast(entry.getKey()); + for(Entry entry : map.entrySet()) { + String key = String.class.cast(entry.getKey()); + Object value = entry.getValue(); - if (entry.getValue() instanceof List) { + if(value instanceof List) { List list = new ArrayList<>(); - for (Object element : (List)entry.getValue()) { - if (element instanceof Map) { - list.add(convertToIMessage(Map.class.cast(element), messageFactory, namespace, name)); - } else { - list.add(element); - } + for(Object element : (List)value) { + list.add(element instanceof Map ? convertToIMessage((Map)element, messageFactory, namespace, name) : element); } result.addField(key, list); - } else if (entry.getValue() instanceof Map) { - result.addField(key, convertToIMessage(Map.class.cast(entry.getValue()), messageFactory, namespace, name)); } else { - result.addField(key, entry.getValue()); + result.addField(key, value instanceof Map ? convertToIMessage((Map)value, messageFactory, namespace, name) : value); } } @@ -166,18 +154,20 @@ public static IMessage convertToIMessage(Map map, IMessageFactory messageF return null; } - public static String convertMsgToHumanReadable(final IMessage msg, IDictionaryStructure dict) - { - if ( msg == null ) - throw new NullPointerException("msg"); + public static String convertMsgToHumanReadable(IMessage msg, IDictionaryStructure dict) { + if(msg == null) { + throw new NullPointerException("msg"); + } - if ( dict == null ) - throw new NullPointerException("dict"); + if(dict == null) { + throw new NullPointerException("dict"); + } IMessageStructure msgStruct = dict.getMessages().get(msg.getName()); - if ( msgStruct == null ) - return null; + if(msgStruct == null) { + return null; + } MessageStructureReader msgStructReader = new MessageStructureReader(); @@ -217,9 +207,9 @@ private static class MsgVisitor extends DefaultMessageStructureVisitor private static final String COLLECTION_END = "]; "; private static final String COLLECTION_START = "=["; private final StringBuilder buffer; - private boolean showNulls = false; + private final boolean showNulls = false; - private final static ThreadLocal df = new ThreadLocal() { + private static final ThreadLocal df = new ThreadLocal() { @Override protected DecimalFormat initialValue() { return new DecimalFormat("#.################"); @@ -290,7 +280,7 @@ public void visit(String fieldName, Double value, IFieldStructure fldStruct, boolean isDefault) { // we also can check Double.isInfinite(), but DecimalFormat works well with +-Infinity - convertField(buffer, fieldName, (value == null || Double.isNaN(value) ? value : df.get().format(value)), fldStruct, showNulls); + convertField(buffer, fieldName, value == null || Double.isNaN(value) ? value : df.get().format(value), fldStruct, showNulls); } @@ -391,8 +381,9 @@ public void visitStringCollection(String fieldName, List values, IFieldS if (values == null) { buffer.append("null"); } else { - for (String value : values) - convertField(buffer, null, value, fldStruct, showNulls); + for(String value : values) { + convertField(buffer, null, value, fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -414,8 +405,9 @@ public void visitIntCollection(String fieldName, List values, if (values == null) { buffer.append("null"); } else { - for (Integer value : values) - convertField(buffer, null, value, fldStruct, showNulls); + for(Integer value : values) { + convertField(buffer, null, value, fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -438,8 +430,9 @@ public void visitLongCollection( if (values == null) { buffer.append("null"); } else { - for (Long value : values) - convertField(buffer, null, value, fldStruct, showNulls); + for(Long value : values) { + convertField(buffer, null, value, fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -462,8 +455,9 @@ public void visitDoubleCollection( if (values == null) { buffer.append("null"); } else { - for (Double value : values) - convertField(buffer, null, value, fldStruct, showNulls); + for(Double value : values) { + convertField(buffer, null, value, fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -484,8 +478,9 @@ public void visitByteCollection(String fieldName, List values, if (values == null) { buffer.append("null"); } else { - for (Byte value : values) - convertField(buffer, null, value, fldStruct, showNulls); + for(Byte value : values) { + convertField(buffer, null, value, fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -508,8 +503,9 @@ public void visitBooleanCollection( if (values == null) { buffer.append("null"); } else { - for (Boolean value : values) - convertField(buffer, null, value, fldStruct, showNulls); + for(Boolean value : values) { + convertField(buffer, null, value, fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -532,8 +528,9 @@ public void visitBigDecimalCollection( if (values == null) { buffer.append("null"); } else { - for (BigDecimal value : values) + for(BigDecimal value : values) { convertField(buffer, null, (value == null) ? value: value.toPlainString(), fldStruct, showNulls); + } } buffer.append(COLLECTION_END); @@ -557,16 +554,13 @@ private static void convertField(StringBuilder buffer, String fieldName, Object { String alias = getAlias(fldStruct, value); buffer.append(alias); - } - else - buffer.append("null"); + } else { + buffer.append("null"); + } } else { - if ( value != null ) - buffer.append(value.toString()); - else - buffer.append("null"); + buffer.append(value); } buffer.append("; "); @@ -608,8 +602,9 @@ private static String getAlias(IFieldStructure enumFldType, Object value) { for ( String enumEl : enumFldType.getValues().keySet() ) { - if ( enumFldType.getValues().get(enumEl).getCastValue().equals(value) ) - return enumEl; + if(enumFldType.getValues().get(enumEl).getCastValue().equals(value)) { + return enumEl; + } } return value.toString(); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MsgMetaData.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MsgMetaData.java index e9c35cf9..88b42afb 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MsgMetaData.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/MsgMetaData.java @@ -29,9 +29,9 @@ public class MsgMetaData implements Cloneable { // unique (during SailFish run time). Mapped to 'StoredId' in StoredMessage private final long id = MessageUtil.generateId(); - private Date msgTimestamp; - private String msgNamespace; - private String msgName; + private final Date msgTimestamp; + private final String msgNamespace; + private final String msgName; private String fromService; private String toService; @@ -52,7 +52,7 @@ public MsgMetaData(@JsonProperty("namespace") String namespace, @JsonProperty("n this.msgTimestamp = msgTimestamp; } - public MsgMetaData(final String namespace, final String name) { + public MsgMetaData(String namespace, String name) { this(namespace, name, new Date()); } @@ -117,7 +117,7 @@ public String getMsgName() { } public byte[] getRawMessage() { - return this.rawMessage; + return rawMessage; } public void setRawMessage(byte[] value) { @@ -182,18 +182,18 @@ public boolean equals(Object obj) { MsgMetaData that = (MsgMetaData)obj; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.msgName, that.msgName); - builder.append(this.msgNamespace, that.msgNamespace); - builder.append(this.msgTimestamp, that.msgTimestamp); - builder.append(this.fromService, that.fromService); - builder.append(this.toService, that.toService); - builder.append(this.isAdmin, that.isAdmin); - builder.append(this.isRejected, that.isRejected); - builder.append(this.isDirty, that.isDirty); - builder.append(this.rawMessage, that.rawMessage); - builder.append(this.serviceInfo, that.serviceInfo); - builder.append(this.dictionaryURI, that.dictionaryURI); - builder.append(this.rejectReason, that.rejectReason); + builder.append(msgName, that.msgName); + builder.append(msgNamespace, that.msgNamespace); + builder.append(msgTimestamp, that.msgTimestamp); + builder.append(fromService, that.fromService); + builder.append(toService, that.toService); + builder.append(isAdmin, that.isAdmin); + builder.append(isRejected, that.isRejected); + builder.append(isDirty, that.isDirty); + builder.append(rawMessage, that.rawMessage); + builder.append(serviceInfo, that.serviceInfo); + builder.append(dictionaryURI, that.dictionaryURI); + builder.append(rejectReason, that.rejectReason); return builder.isEquals(); @@ -203,18 +203,18 @@ public boolean equals(Object obj) { public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); - builder.append(this.msgName); - builder.append(this.msgNamespace); - builder.append(this.msgTimestamp); - builder.append(this.fromService); - builder.append(this.toService); - builder.append(this.isAdmin); - builder.append(this.isRejected); - builder.append(this.isDirty); - builder.append(this.rawMessage); - builder.append(this.serviceInfo); - builder.append(this.dictionaryURI); - builder.append(this.rejectReason); + builder.append(msgName); + builder.append(msgNamespace); + builder.append(msgTimestamp); + builder.append(fromService); + builder.append(toService); + builder.append(isAdmin); + builder.append(isRejected); + builder.append(isDirty); + builder.append(rawMessage); + builder.append(serviceInfo); + builder.append(dictionaryURI); + builder.append(rejectReason); return builder.toHashCode(); } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/ReorderFieldComparator.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/ReorderFieldComparator.java index 0ef6b8e3..91aec226 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/ReorderFieldComparator.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/ReorderFieldComparator.java @@ -24,7 +24,9 @@ public ReorderFieldComparator(List order, Collection names) { for (String name : names) { int index = order.indexOf(name); - if (index == -1) continue; + if(index == -1) { + continue; + } this.order.put(name, index); } @@ -41,6 +43,6 @@ public ReorderFieldComparator(List order, Collection names) { @Override public int compare(String o1, String o2) { - return this.order.get(o1) - this.order.get(o2); + return order.get(o1) - order.get(o2); } } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureBuilder.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureBuilder.java index 4aa40af4..c4768cee 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureBuilder.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureBuilder.java @@ -26,8 +26,8 @@ public class StructureBuilder { private final Map msgStructures; private final Map fieldStructures; - - private String namespace; + + private final String namespace; public StructureBuilder(String namespace) { this(namespace, new HashMap<>(), new HashMap<>()); @@ -47,11 +47,11 @@ public void addMessageStructure(IMessageStructure msgStructure) { throw new IllegalArgumentException("name parameter is null"); } - if (this.msgStructures.containsKey(name)) { - throw new EPSCommonException("There is another message with \"" + name + "\" name in \"" + this.namespace + "\""); + if(msgStructures.containsKey(name)) { + throw new EPSCommonException("There is another message with \"" + name + "\" name in \"" + namespace + "\""); } - this.msgStructures.put(name, msgStructure); + msgStructures.put(name, msgStructure); } public void addFieldStructure(IFieldStructure fieldStructure) { @@ -61,12 +61,12 @@ public void addFieldStructure(IFieldStructure fieldStructure) { if (name == null) { throw new IllegalArgumentException("name parameter is null"); } - - if (this.fieldStructures.containsKey(name)) { - throw new EPSCommonException("There is another field with \"" + name + "\" name in \"" + this.namespace + "\""); - } - - this.fieldStructures.put(name, fieldStructure); + + if(fieldStructures.containsKey(name)) { + throw new EPSCommonException("There is another field with \"" + name + "\" name in \"" + namespace + "\""); + } + + fieldStructures.put(name, fieldStructure); } public IMessageStructure getMessageStructure(String name) { @@ -74,7 +74,7 @@ public IMessageStructure getMessageStructure(String name) { } public IFieldStructure getFieldStructure(String name) { - return this.fieldStructures.get(name); + return fieldStructures.get(name); } public List getMsgStructures() { diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureType.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureType.java index bedbddb1..6773066f 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureType.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/StructureType.java @@ -18,5 +18,5 @@ public enum StructureType { SIMPLE, ENUM, - COMPLEX; + COMPLEX } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/DictionaryStructure.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/DictionaryStructure.java index 3d642298..2cf039f0 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/DictionaryStructure.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/DictionaryStructure.java @@ -37,24 +37,9 @@ public DictionaryStructure(String namespace, String description, Map messages, Map fields) { this.namespace = namespace; this.description = description; - - if(messages != null) { - this.messages = Collections.unmodifiableMap(messages); - } else { - this.messages = Collections.emptyMap(); - } - - if(fields != null) { - this.fields = Collections.unmodifiableMap(fields); - } else { - this.fields = Collections.emptyMap(); - } - - if (attributes != null) { - this.attributes = Collections.unmodifiableMap(attributes); - } else { - this.attributes = Collections.emptyMap(); - } + this.messages = messages != null ? Collections.unmodifiableMap(messages) : Collections.emptyMap(); + this.fields = fields != null ? Collections.unmodifiableMap(fields) : Collections.emptyMap(); + this.attributes = attributes != null ? Collections.unmodifiableMap(attributes) : Collections.emptyMap(); } @Override @@ -64,17 +49,17 @@ public Map getAttributes() { @Override public Map getMessages() { - return this.messages; + return messages; } @Override public Map getFields() { - return this.fields; + return fields; } @Override public String getNamespace() { - return this.namespace; + return namespace; } @Override diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/FieldStructure.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/FieldStructure.java index bbcc170e..3cc88171 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/FieldStructure.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/FieldStructure.java @@ -65,18 +65,8 @@ protected FieldStructure(String name, String namespace, String description, Stri this.collection = isCollection; this.serviceName = isServiceName; this.defaultValue = StructureUtils.castValueToJavaType(defaultValue, javaType); - - if (attributes != null) { - this.attributes = Collections.unmodifiableMap(attributes); - } else { - this.attributes = Collections.emptyMap(); - } - - if (values != null) { - this.values = Collections.unmodifiableMap(values); - } else { - this.values = Collections.emptyMap(); - } + this.attributes = attributes != null ? Collections.unmodifiableMap(attributes) : Collections.emptyMap(); + this.values = values != null ? Collections.unmodifiableMap(values) : Collections.emptyMap(); if(structureType == null && !this.values.isEmpty()) { structureType = StructureType.ENUM; @@ -92,17 +82,17 @@ protected FieldStructure(String name, String namespace, String description, Stri @Override public boolean isComplex() { - return StructureType.COMPLEX.equals(this.structureType); + return structureType == StructureType.COMPLEX; } @Override public boolean isEnum() { - return StructureType.ENUM.equals(this.structureType); + return structureType == StructureType.ENUM; } @Override public boolean isSimple() { - return StructureType.SIMPLE.equals(this.structureType); + return structureType == StructureType.SIMPLE; } @Override @@ -167,6 +157,6 @@ public String getReferenceName() { @Override public Map getFields() { - throw new UnsupportedOperationException("Field '" + this.name + "' don't have another fields"); + throw new UnsupportedOperationException("Field '" + name + "' don't have another fields"); } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/MessageStructure.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/MessageStructure.java index f5012850..19679fd1 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/MessageStructure.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/impl/MessageStructure.java @@ -30,7 +30,7 @@ public class MessageStructure extends FieldStructure implements IMessageStructure { private final Map fields; - private IMessageStructure reference; + private final IMessageStructure reference; public MessageStructure(String name, String namespace, boolean isCollection, IMessageStructure reference) { this(name, namespace, null, null, false, isCollection, null, reference); @@ -50,24 +50,14 @@ private MessageStructure(String name, String namespace, String description, Map< boolean isRequired, boolean isCollection, Map attributes, IMessageStructure reference) { super(name, namespace, description, reference != null ? reference.getName() : null, attributes, null, null, isRequired, isCollection, false, null, StructureType.COMPLEX); - - if (fields != null) { - this.fields = Collections.unmodifiableMap(fields); - } else { - this.fields = Collections.emptyMap(); - } - + this.fields = fields != null ? Collections.unmodifiableMap(fields) : Collections.emptyMap(); this.reference = reference; } @Override public Map getFields() { - if (this.reference != null) { - return this.reference.getFields(); - } - - return this.fields; - } + return reference != null ? reference.getFields() : fields; + } @Override public Map getValues() { @@ -81,7 +71,7 @@ public JavaType getJavaType() { @Override public boolean isRequired() { - if (this.reference != null) { + if(reference != null) { return super.isRequired(); } @@ -90,7 +80,7 @@ public boolean isRequired() { @Override public boolean isCollection() { - if (this.reference != null) { + if(reference != null) { return super.isCollection(); } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XmlDictionaryStructureLoader.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XmlDictionaryStructureLoader.java index 490bd62d..cdcc50ba 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XmlDictionaryStructureLoader.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XmlDictionaryStructureLoader.java @@ -89,16 +89,16 @@ public Dictionary loadXmlEntity(InputStream input) throws EPSCommonException { SAXParseException saxParseException = null; - if (null != jabEx.getCause() && (jabEx.getCause() instanceof SAXParseException)) { - saxParseException = ((SAXParseException) jabEx.getCause()); - } else if (null != jabEx.getLinkedException() + if(jabEx.getCause() != null && (jabEx.getCause() instanceof SAXParseException)) { + saxParseException = (SAXParseException)jabEx.getCause(); + } else if(jabEx.getLinkedException() != null && (jabEx.getLinkedException() instanceof SAXParseException)) { - saxParseException = ((SAXParseException) jabEx.getLinkedException()); + saxParseException = (SAXParseException)jabEx.getLinkedException(); } - if (null != saxParseException) { + if(saxParseException != null) { - final String strError = String.format("%4$sThis xml stream structure could not be unmarshaled due to SAXParser error %4$s[%1$s].%4$sError was found on the line [%2$d], column [%3$d].%4$s", + String strError = String.format("%4$sThis xml stream structure could not be unmarshaled due to SAXParser error %4$s[%1$s].%4$sError was found on the line [%2$d], column [%3$d].%4$s", saxParseException.getMessage(), saxParseException.getLineNumber(), saxParseException.getColumnNumber(), StringUtil.EOL); @@ -156,8 +156,8 @@ public IDictionaryStructure convert(Dictionary dictionary) throws EPSCommonExcep throw new EPSCommonException("It is impossible to keep messages in fields"); } else { - JavaType javaType = getFieldType(field, this.aggregateAttributes); - String defVal = getDefaultValue(field, this.aggregateAttributes); + JavaType javaType = getFieldType(field, aggregateAttributes); + String defVal = getDefaultValue(field, aggregateAttributes); IFieldStructure fieldStructure = createFieldStructure( field, true, @@ -200,7 +200,7 @@ public IDictionaryStructure convert(Dictionary dictionary) throws EPSCommonExcep } throw new EPSCommonException( - "Messages with same names has been detected! Check names of your messages. Message names: " + duplicatedNames.toString()); + "Messages with same names has been detected! Check names of your messages. Message names: " + duplicatedNames); } Message msg = messages.get(i++); @@ -289,20 +289,12 @@ protected IAttributeStructure createAttributeStructure(String name, String value } private String getDefaultValue(Field field, boolean search) { - if (!search) { - return field.getDefaultvalue(); - } - - if (field.getDefaultvalue() != null) { - return field.getDefaultvalue(); - } - - if (field.getReference() != null) { - return getDefaultValue((Field)field.getReference(), search); - } + if(!search || field.getDefaultvalue() != null) { + return field.getDefaultvalue(); + } - return null; - } + return field.getReference() != null ? getDefaultValue((Field)field.getReference(), true) : null; + } private Map createFieldStructures(StructureBuilder builder, Message message, String namespace) { Map result = new LinkedHashMap<>(); @@ -331,8 +323,8 @@ private Map createFieldStructures(StructureBuilder buil field.getName(), message.getName())); } - JavaType javaType = getFieldType(field, this.aggregateAttributes); - String defVal = getDefaultValue(field, this.aggregateAttributes); + JavaType javaType = getFieldType(field, aggregateAttributes); + String defVal = getDefaultValue(field, aggregateAttributes); fieldStructure = createFieldStructure( field, false, @@ -360,27 +352,18 @@ private JavaType getFieldType(Field field, boolean search) { if (!search) { return field.getType(); } - - if (field.getReference() != null) { - return getFieldType((Field) field.getReference(), search); - } else { - return field.getType(); - } - } - private boolean isComplex(Field field) { - Object reference = field.getReference(); - - boolean value = (field instanceof Message); + return field.getReference() != null ? getFieldType((Field)field.getReference(), true) : field.getType(); + } - if (!value) { - if (reference != null) { - value = isComplex((Field) field.getReference()); - } - } + private boolean isComplex(Field field) { + if(field instanceof Message) { + return true; + } - return value; - } + Object reference = field.getReference(); + return reference != null && isComplex((Field)reference); + } private Map getAttributes(Field field, boolean isValues, JavaType javaType) { List attributes = new ArrayList<>(); @@ -427,7 +410,7 @@ protected void collectFieldValues(Field field, Collection values) { private void collectFieldAttributesOrValues(Field field, Collection attrOrVal, List attrOrValList, boolean isValue) { - if (this.aggregateAttributes) { + if(aggregateAttributes) { Object reference = field.getReference(); if (reference != null) { collectFieldAttributesOrValues((Field) reference, attrOrVal, isValue ? ((Field)reference).getValues() : ((Field)reference).getAttributes(), isValue); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XsdDictionaryStructureLoader.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XsdDictionaryStructureLoader.java index 37d615b2..1a54dbab 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XsdDictionaryStructureLoader.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/messages/structures/loaders/XsdDictionaryStructureLoader.java @@ -233,13 +233,13 @@ private void complexType(StructureBuilder builder, ComplexType type) { if (type.getDerivationMethod() == null) { - if (States.MESSAGE.equals(curState)) { + if(curState == States.MESSAGE) { for (int i = 0; i < type.getParticleCount(); ++i) { - this.particle(builder, type.getParticle(i)); + particle(builder, type.getParticle(i)); } - } else if (States.FIELD.equals(curState)) { + } else if(curState == States.FIELD) { // Should create complex field type Map fieldAttributes = (Map) context.value; @@ -310,7 +310,7 @@ private void elementDecl(StructureBuilder builder, ElementDecl decl) { String declName = decl.getName(); XMLType type = decl.getType(); - if (States.MESSAGE.equals(curState)) { + if(curState == States.MESSAGE) { // Field declaration Context fldStrContext = new Context(); fldStrContext.deep = curIntend + 1; @@ -329,7 +329,7 @@ private void elementDecl(StructureBuilder builder, ElementDecl decl) { Boolean isCollection = decl.getMaxOccurs() != 1; - Boolean isServiceName = isComplexType ? false : fieldStructureForType.isServiceName(); + Boolean isServiceName = !isComplexType && fieldStructureForType.isServiceName(); StructureBuilder msgStruct = (StructureBuilder) context.value; @@ -339,7 +339,7 @@ private void elementDecl(StructureBuilder builder, ElementDecl decl) { if (!isComplexType) { // Simple field - String defValue = (decl.getDefaultValue() == null) ? null : decl.getDefaultValue(); + String defValue = decl.getDefaultValue(); IFieldStructure fldStruct = new FieldStructure(declName, builder.getNamespace(), description, null, declProtocolAttributes, null, fieldStructureForType.getJavaType() == null @@ -364,7 +364,7 @@ private void elementDecl(StructureBuilder builder, ElementDecl decl) { private void modelGroup(StructureBuilder builder, ModelGroup group) { - final int len = group.getParticleCount(); + int len = group.getParticleCount(); for (int i = 0; i < len; i++) { particle(builder, group.getParticle(i)); @@ -373,7 +373,7 @@ private void modelGroup(StructureBuilder builder, ModelGroup group) { private void group(StructureBuilder builder, Group group) { - final int len = group.getParticleCount(); + int len = group.getParticleCount(); for (int i = 0; i < len; i++) { particle(builder, group.getParticle(i)); @@ -383,15 +383,15 @@ private void group(StructureBuilder builder, Group group) { private void particle(StructureBuilder builder, Particle particle) { if (particle.getStructureType() == Structure.ELEMENT) { - this.elementDecl(builder, (ElementDecl) particle); + elementDecl(builder, (ElementDecl)particle); } else if (particle.getStructureType() == Structure.MODELGROUP) { - this.modelGroup(builder, (ModelGroup) particle); + modelGroup(builder, (ModelGroup)particle); } else if (particle.getStructureType() == Structure.GROUP) { - this.group(builder, (Group) particle); + group(builder, (Group)particle); } else if (particle.getStructureType() == Structure.MODELGROUP_REF) { - this.modelGroup(builder, (ModelGroup) particle); + modelGroup(builder, (ModelGroup)particle); } else if (particle.getStructureType() == Structure.WILDCARD) { - this.wildcard((Wildcard) particle); + wildcard((Wildcard)particle); } else { throw new RuntimeException("not implemented. Structure type = " + particle.getStructureType()); } @@ -413,7 +413,7 @@ private void simpleType(StructureBuilder builder, SimpleType simpleType) { if (simpleType.isBuiltInType()) { - if (States.FIELD.equals(curState)) { + if(curState == States.FIELD) { Map fieldAttribs = (Map) context.value; @@ -429,9 +429,9 @@ private void simpleType(StructureBuilder builder, SimpleType simpleType) { throw new RuntimeException("is not implemented"); } - } else if (simpleType.getDerivationMethod().equals("restriction")) { + } else if("restriction".equals(simpleType.getDerivationMethod())) { - if (States.FIELD.equals(curState)) { + if(curState == States.FIELD) { Map fieldAttribs = (Map) context.value; @@ -445,9 +445,9 @@ private void simpleType(StructureBuilder builder, SimpleType simpleType) { IFieldStructure fieldStructure = null; List> enumElementsList = null; - if (simpleType.isBuiltInType()) - fieldStructure = builder.getFieldStructure(simpleType.getName()); - else if (simpleType.getBaseType().isSimpleType() + if(simpleType.isBuiltInType()) { + fieldStructure = builder.getFieldStructure(simpleType.getName()); + } else if(simpleType.getBaseType().isSimpleType() && ((SimpleType) simpleType.getBaseType()).isBuiltInType()) { fieldStructure = builder.getFieldStructure(simpleType.getBaseType().getName()); @@ -462,37 +462,32 @@ else if (simpleType.getBaseType().isSimpleType() intend(curIntend), facet.getName(), facet.getValue()); } - if (facet.getName().equals("enumeration")) { + if("enumeration".equals(facet.getName())) { Map enumElementProtocolAttributes = getProtocolAttributes( facet.getAnnotations()); String alias = null; - if (enumElementProtocolAttributes != null) - alias = enumElementProtocolAttributes.get("Alias").getValue(); + if(enumElementProtocolAttributes != null) { + alias = enumElementProtocolAttributes.get("Alias").getValue(); + } - Pair enumElement = null; + IAttributeStructure attr = enumElementProtocolAttributes.values().iterator().next(); - IAttributeStructure attr = enumElementProtocolAttributes.values().iterator().next(); + JavaType javaType = fieldStructure != null ? fieldStructure.getJavaType() : getFieldType(simpleType.getBaseType().getName()); - JavaType javaType = null; - - if (fieldStructure != null) { - javaType = fieldStructure.getJavaType(); - } else { - javaType = getFieldType(simpleType.getBaseType().getName()); - } - - enumElement = new Pair<>(alias, - new AttributeStructure(attr.getValue(), facet.getValue(), - StructureUtils.castValueToJavaType(facet.getValue(), javaType), javaType)); + Pair enumElement = new Pair<>(alias, + new AttributeStructure(attr.getValue(), facet.getValue(), + StructureUtils.castValueToJavaType(facet.getValue(), javaType), javaType)); enumElements.add(enumElement); } } if (!enumElements.isEmpty()) { - if (enumElementsList == null) enumElementsList = new ArrayList<>(); + if(enumElementsList == null) { + enumElementsList = new ArrayList<>(); + } enumElementsList.addAll(enumElements); } } @@ -626,15 +621,15 @@ private Map getProtocolAttributes(Enumeration getProtocolAttributes(Enumeration getProtocolAttributes(Enumeration { @@ -49,11 +48,7 @@ public ServiceName(String toParse) { @JsonCreator public ServiceName(@JsonProperty("env") String env, @JsonProperty("serviceName") String serviceName) { - if (env == null) { - this.environment = DEFAULT_ENVIRONMENT; - } else { - this.environment = StringUtils.trim(env); - } + this.environment = env == null ? DEFAULT_ENVIRONMENT : StringUtils.trim(env); this.serviceName = StringUtils.trim(serviceName); } @@ -67,25 +62,24 @@ public String getServiceName() { @JsonIgnore public boolean isDefault() { - return DEFAULT_ENVIRONMENT.equals(this.environment); + return DEFAULT_ENVIRONMENT.equals(environment); } @Override public String toString() { - return this.environment + ENVIRONMENT_SEPARATOR + this.serviceName; + return environment + ENVIRONMENT_SEPARATOR + serviceName; } public static String toString(String env, String serviceName) { - if (null == env) env = DEFAULT_ENVIRONMENT; + if(env == null) { + env = DEFAULT_ENVIRONMENT; + } return env+ENVIRONMENT_SEPARATOR+serviceName; } public static ServiceName parse(String serviceName) { - if (null == serviceName) { - return null; - } - return new ServiceName(serviceName); - } + return serviceName == null ? null : new ServiceName(serviceName); + } @Override public int hashCode() { @@ -110,15 +104,15 @@ public boolean equals(Object obj) { ServiceName that = (ServiceName)obj; EqualsBuilder builder = new EqualsBuilder(); - builder.append(StringUtils.lowerCase(this.environment), StringUtils.lowerCase(that.environment)); - builder.append(this.serviceName, that.serviceName); + builder.append(StringUtils.lowerCase(environment), StringUtils.lowerCase(that.environment)); + builder.append(serviceName, that.serviceName); return builder.isEquals(); } @Override public ServiceName clone() { - return new ServiceName(this.environment, this.serviceName); + return new ServiceName(environment, serviceName); } @Override @@ -129,8 +123,8 @@ public int compareTo(ServiceName o) { CompareToBuilder builder = new CompareToBuilder(); - builder.append(this.environment, o.environment, String.CASE_INSENSITIVE_ORDER); - builder.append(this.serviceName, o.serviceName); + builder.append(environment, o.environment, String.CASE_INSENSITIVE_ORDER); + builder.append(serviceName, o.serviceName); return builder.toComparison(); } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenUtils.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenUtils.java index 4c76c784..bc679bbc 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenUtils.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenUtils.java @@ -38,7 +38,7 @@ public static String getShortClass(IFieldStructure fieldStructure, boolean under String className = fieldStructure.getName(); if (underscoreAsPackageSeparator) { String[] nodes = className.split("_"); - className = nodes[nodes.length - 1]; + return nodes[nodes.length - 1]; } return className; } @@ -67,7 +67,9 @@ public static String getEnumValueTypeName(IFieldStructure fieldStructure) { public static String convertSimpleFieldTypeToJavaType(JavaType fldType) { - if (fldType == null) return null; + if(fldType == null) { + return null; + } switch ( fldType ) { @@ -107,7 +109,9 @@ public static String convertSimpleFieldTypeToJavaType(JavaType fldType) { public static String convertSimpleFieldTypeToJavaObjectType(JavaType fldType) { - if (fldType == null) return null; + if(fldType == null) { + return null; + } switch ( fldType ) { @@ -147,7 +151,9 @@ public static String convertSimpleFieldTypeToJavaObjectType(JavaType fldType) { public static boolean isPrimitive(JavaType fldType) { - if (fldType == null) return false; + if(fldType == null) { + return false; + } switch ( fldType ) { @@ -175,7 +181,9 @@ public static boolean isPrimitive(JavaType fldType) { public static String getStringValueView(JavaType javaType, Object value) { - if (javaType == null || value == null) return "null"; + if(javaType == null || value == null) { + return "null"; + } switch (javaType) { case JAVA_LANG_BOOLEAN: @@ -186,7 +194,7 @@ public static String getStringValueView(JavaType javaType, Object value) { case JAVA_LANG_DOUBLE: return value.toString(); case JAVA_LANG_LONG: - return value.toString() + "L"; + return value + "L"; case JAVA_LANG_CHARACTER: return "'" + value + "'"; case JAVA_LANG_STRING: diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenerator.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenerator.java index 241f7060..941b16b5 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenerator.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/CodeGenerator.java @@ -25,7 +25,6 @@ import java.io.StringWriter; import java.io.Writer; import java.nio.file.Paths; -import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; @@ -51,7 +50,7 @@ */ public class CodeGenerator { - public void generate(String path, String[] distPackagePath, final IDictionaryStructure dictStructure, boolean adminOnly, + public void generate(String path, String[] distPackagePath, IDictionaryStructure dictStructure, boolean adminOnly, boolean underscoreAsPackageSeparator) throws IOException { Set filteredMessages = filterMessages(dictStructure, adminOnly); @@ -160,8 +159,9 @@ private boolean generateFieldType(Writer writer, String fullPackage, String clas private void writeFile(String path, String className, String contents, String fullPackage) throws IOException { File file = Paths.get(path, fullPackage.replace('.', File.separatorChar), className + ".java").toFile(); - if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) + if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { throw new EPSCommonException("Could not create \"" + file.getParentFile().getAbsolutePath() + "\" folder"); + } try (FileWriter writer = new FileWriter(file)) { writer.write(contents); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/Pair.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/Pair.java index 75480315..64617f37 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/Pair.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/Pair.java @@ -15,15 +15,15 @@ ******************************************************************************/ package com.exactpro.sf.common.util; -public class Pair { +public class Pair { private A first; private B second; public Pair(A first, B second) { - this.setFirst(first); - this.setSecond(second); + setFirst(first); + setSecond(second); } public void setFirst(A first) { @@ -46,9 +46,9 @@ public B getSecond() { public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(this.first); + sb.append(first); sb.append("="); - sb.append(this.second); + sb.append(second); return sb.toString(); } } diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/StringUtil.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/StringUtil.java index 150e227a..86459a00 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/StringUtil.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/common/util/StringUtil.java @@ -15,16 +15,21 @@ ******************************************************************************/ package com.exactpro.sf.common.util; +import static java.lang.Character.isWhitespace; + import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.lang3.StringUtils; + public class StringUtil { public static final String EOL = System.getProperty("line.separator"); @@ -58,13 +63,13 @@ public static String capitalize(String s) for (byte b : s.getBytes()) { - if ((b >= 'a' && b <= 'z')) + if (b >= 'a' && b <= 'z') { if (isFirst) { b -= shift; isFirst = false; } - } else if ((b >= 'A' && b <= 'Z')) + } else if (b >= 'A' && b <= 'Z') { if (isFirst) { isFirst = false; @@ -152,9 +157,8 @@ public static String join(String delim, String[] arr, int begin) * @return */ public static String getSSuffix(int quantity) { - if (quantity != 1) return "s"; - return ""; - } + return quantity != 1 ? "s" : ""; + } /** * Parse string: '1-3,5 , 7-' to set of integers. @@ -165,7 +169,7 @@ public static String getSSuffix(int quantity) { public static Set parseRange(String s, int size) { Set list = new HashSet<>(); - if (s == null || s.trim().equals("")) { + if(StringUtils.isBlank(s)) { for (int i=0; i parseRange(String s, int size) return list; } - /** - * Compare 2 objects without NullPointerException. - * @param o1 - * @param o2 - * @return {@code true} if objects are equals or both are {@code null} - */ - public static boolean equals(Object o1, Object o2) { - if (o1 == null && o2 == null) { - return true; - } - if (o1 != null) { - return o1.equals(o2); - } - return false; - } - /** * Split string to array. * @param s source string * @param delim delimiter * @return */ - public static String[] split(final String s, final String delim) + public static String[] split(String s, String delim) { if (s == null) { throw new NullPointerException("String is null"); @@ -287,7 +275,7 @@ public static String[] split(final String s, final String delim) if (delim == null) { throw new NullPointerException("Delimiter is null"); } - if (delim.equals("")) { + if(delim.isEmpty()) { List arr = new ArrayList<>(); for (int i=0; i trans = null; + private static HashMap trans; private static int cur = 192; private static void next(String s) { @@ -423,17 +411,19 @@ private static void initHTMLtransformer() public static final String escapeHTML(String s){ StringBuffer sb = new StringBuffer(); int n = s.length(); - if (trans == null) - initHTMLtransformer(); + if(trans == null) { + initHTMLtransformer(); + } for (int i = 0; i < n; i++) { char c = s.charAt(i); String app = trans.get(c); - if (app != null) - sb.append(app); - else - sb.append(c); + if(app != null) { + sb.append(app); + } else { + sb.append(c); + } } return sb.toString(); } @@ -478,8 +468,7 @@ public static final String replaceChars(String string, String chars, char replac * @return the maximum string */ public static final String maximumString(String s1, String s2) { - if (s1.compareTo(s2) > 0) return s1; - else return s2; + return s1.compareTo(s2) > 0 ? s1 : s2; } public static final String enclose(String input) { @@ -491,12 +480,8 @@ public static final String enclose(String input, char enclosure) { } public static boolean isStripped(CharSequence cs) { - if(cs == null || cs.length() == 0) { - return true; - } - - return !Character.isWhitespace(cs.charAt(0)) && !Character.isWhitespace(cs.charAt(cs.length() - 1)); - } + return cs == null || cs.length() == 0 || !isWhitespace(cs.charAt(0)) && !isWhitespace(cs.charAt(cs.length() - 1)); + } public static String validateFileName(String fileName) { Matcher matcher = FORBIDDEN_FILENAME_ELEMENTS.matcher(fileName); diff --git a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java index 2590f080..e6163c6f 100644 --- a/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java +++ b/BackEnd/Core/sailfish-common/src/main/java/com/exactpro/sf/util/DateTimeUtility.java @@ -16,8 +16,6 @@ package com.exactpro.sf.util; import java.sql.Timestamp; -import java.util.Date; - import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; @@ -30,6 +28,7 @@ import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; +import java.util.Date; public class DateTimeUtility { @@ -388,10 +387,7 @@ public static DateTimeFormatter createFormatter(String pattern) { } private static int getOrDefault(TemporalAccessor temporalAccessor, TemporalField field, int defaultValue) { - if (temporalAccessor.isSupported(field)) { - return temporalAccessor.get(field); - } - return defaultValue; + return temporalAccessor.isSupported(field) ? temporalAccessor.get(field) : defaultValue; } private static ZoneId getZoneId(TemporalAccessor temporalAccessor) { diff --git a/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/impl/messages/TestMapMessage.java b/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/impl/messages/TestMapMessage.java index 200f78ed..73a7be54 100644 --- a/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/impl/messages/TestMapMessage.java +++ b/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/impl/messages/TestMapMessage.java @@ -19,6 +19,7 @@ import java.math.BigDecimal; import java.util.Arrays; +import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.junit.Assert; import org.junit.Test; @@ -84,7 +85,7 @@ public void testMapMessageSerializationWithJson() throws IOException { message.addField("message", subMessage); message.addField("message_array", Arrays.asList(new MapMessage[] { subMessage, subMessage })); - ObjectMapper objectMapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL) + ObjectMapper objectMapper = new ObjectMapper().enableDefaultTyping(DefaultTyping.NON_FINAL) .registerModule(new JavaTimeModule()); ObjectReader reader = objectMapper.reader(IMessage.class); ObjectWriter writer = objectMapper.writer(); diff --git a/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/xml/ReadConfigTest.java b/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/xml/ReadConfigTest.java index f9723d22..7f860e76 100644 --- a/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/xml/ReadConfigTest.java +++ b/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/common/xml/ReadConfigTest.java @@ -29,6 +29,8 @@ import com.exactpro.sf.common.impl.messages.xml.XMLTransmitter; import com.exactpro.sf.common.impl.messages.xml.configuration.Attribute; import com.exactpro.sf.common.impl.messages.xml.configuration.Dictionary; +import com.exactpro.sf.common.impl.messages.xml.configuration.Dictionary.Fields; +import com.exactpro.sf.common.impl.messages.xml.configuration.Dictionary.Messages; import com.exactpro.sf.common.impl.messages.xml.configuration.Field; import com.exactpro.sf.common.impl.messages.xml.configuration.JavaType; import com.exactpro.sf.common.impl.messages.xml.configuration.Message; @@ -47,7 +49,7 @@ public class ReadConfigTest extends EPSTestCase { - private String PATH_PREFIX = getBaseDir() + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator ; + private final String PATH_PREFIX = getBaseDir() + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator ; @Test public void test0() throws Exception { @@ -76,7 +78,7 @@ public void test0() throws Exception { tmp.setType(JavaType.JAVA_LANG_BYTE); tmp.setValue("3"); field.getValues().add(tmp); - dict.setFields(new Dictionary.Fields()); + dict.setFields(new Fields()); dict.getFields().getFields().add(field); Message message = new Message(); @@ -86,7 +88,7 @@ public void test0() throws Exception { mfield.setName("f_name"); mfield.setReference(field); message.getFields().add(mfield); - dict.setMessages(new Dictionary.Messages()); + dict.setMessages(new Messages()); dict.getMessages().getMessages().add(message); XMLTransmitter @@ -196,7 +198,7 @@ public void swift518Test() throws Exception { System.out.println(fieldStructure0.getName() + " " + fieldStructure0.getStructureType()); if (fieldStructure0.isComplex()) { messageCount518++; - if( fieldStructure0.getName().equals("SMandatorySequenceBConfirmationDetails") ){ + if("SMandatorySequenceBConfirmationDetails".equals(fieldStructure0.getName())) { Assert.assertEquals(3, fieldStructure0.getFields().size()); for(IFieldStructure fieldStructure1 : fieldStructure0.getFields().values()) { System.out.println(fieldStructure1.getName() + " " + fieldStructure1.getStructureType()); diff --git a/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/util/EPSTestCase.java b/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/util/EPSTestCase.java index e27cee46..6b210f84 100644 --- a/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/util/EPSTestCase.java +++ b/BackEnd/Core/sailfish-common/src/test/java/com/exactpro/sf/util/EPSTestCase.java @@ -23,7 +23,7 @@ public class EPSTestCase { - private static boolean isLoggingAlreadyConfigured = false; + private static boolean isLoggingAlreadyConfigured; protected static final String BIN_FOLDER_PATH = "build/test-results"; protected static final Path BASE_DIR = Paths.get((System.getProperty("basedir") == null) ? "." : System.getProperty("basedir")).toAbsolutePath().normalize(); diff --git a/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/aml/scriptutil/LegReorderBenchmark.java b/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/aml/scriptutil/LegReorderBenchmark.java index a661ee5e..75cb466f 100644 --- a/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/aml/scriptutil/LegReorderBenchmark.java +++ b/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/aml/scriptutil/LegReorderBenchmark.java @@ -36,7 +36,7 @@ public class LegReorderBenchmark { // $ gradle jmhJar // $ java -jar build/libs/testtools-std-1.0-SNAPSHOT-jmh.jar - final static String NS = "namespace"; + private static final String NS = "namespace"; @State(Scope.Thread) public static class BMState { @@ -74,7 +74,7 @@ public static IMessage fromString(String name, String str, Object...nested) { MapMessage result = new MapMessage(NS, name); if (str != null) { - while (str.length() != 0) { + while (!str.isEmpty()) { List pair = pareseKV(str); String key = pair.get(0); diff --git a/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/comparison/MessageComparatorBenchmark.java b/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/comparison/MessageComparatorBenchmark.java index 6a239378..a39f97e5 100644 --- a/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/comparison/MessageComparatorBenchmark.java +++ b/BackEnd/Core/sailfish-core/src/jmh/java/com/exactpro/sf/comparison/MessageComparatorBenchmark.java @@ -31,12 +31,12 @@ import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; +import com.exactpro.sf.aml.scriptutil.StaticUtil; import com.exactpro.sf.common.impl.messages.MapMessage; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.messages.structures.loaders.XmlDictionaryStructureLoader; import com.exactpro.sf.common.util.EPSCommonException; -import com.exactpro.sf.aml.scriptutil.StaticUtil; public class MessageComparatorBenchmark { public static void main(String[] args) { @@ -50,7 +50,7 @@ public static void main(String[] args) { } @State(Scope.Thread) - public static abstract class AbstractState { + public abstract static class AbstractState { public IMessage actual; public IMessage expected; public ComparatorSettings settings; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/BugsUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/BugsUtils.java index a859fdcb..69472768 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/BugsUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/BugsUtils.java @@ -31,7 +31,7 @@ * */ @MatrixUtils -@ResourceAliases({"BugsUtils"}) +@ResourceAliases("BugsUtils") public class BugsUtils extends AbstractCaller { @UtilityMethod @Description("This method compares the actual value against the expected value and also takes into account
" diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/CommonActions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/CommonActions.java index 03cb56f7..c20e22f1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/CommonActions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/CommonActions.java @@ -31,7 +31,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Map; +import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.zip.DeflaterInputStream; import java.util.zip.InflaterOutputStream; @@ -82,7 +82,7 @@ */ @MatrixActions -@ResourceAliases({"CommonActions"}) +@ResourceAliases("CommonActions") public class CommonActions extends AbstractCaller { private static final Logger logger = LoggerFactory.getLogger(CommonActions.class); @@ -91,9 +91,7 @@ public class CommonActions extends AbstractCaller { public static final String FIRST_ARG = "firstArg"; public static final String SECOND_ARG = "secondArg"; - @CommonColumns({ - @CommonColumn(value = Column.Reference, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.Reference, required = true)) @ActionMethod public CheckPoint GetCheckPoint(IActionContext actionContext) { @@ -137,9 +135,7 @@ public CheckPoint GetCheckPoint(IActionContext actionContext) return checkPoint; } - @CommonColumns({ - @CommonColumn(value = Column.Reference, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.Reference, required = true)) @ActionMethod public CheckPoint GetAdminCheckPoint(IActionContext actionContext) { @@ -177,9 +173,7 @@ public CheckPoint GetAdminCheckPoint(IActionContext actionContext) // return checkPoint; } - @CommonColumns({ - @CommonColumn(value = Column.Timeout, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.Timeout, required = true)) @ActionMethod public void Sleep(IActionContext actionContext) throws InterruptedException { @@ -187,9 +181,7 @@ public void Sleep(IActionContext actionContext) throws InterruptedException Thread.sleep(actionContext.getTimeout()); } - @CustomColumns({ - @CustomColumn(value = WAIT_TILL_TIME_ARG_DATE, required = true) - }) + @CustomColumns(@CustomColumn(value = WAIT_TILL_TIME_ARG_DATE, required = true)) @ActionMethod public void WaitTillTime(IActionContext actionContext, HashMap inputData) throws InterruptedException { Object o = inputData.get(WAIT_TILL_TIME_ARG_DATE); @@ -225,9 +217,7 @@ public T System_DefineMessage(IActionContext actionContext, T message) return message; } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CheckLogon(IActionContext actionContext) throws InterruptedException { @@ -255,9 +245,7 @@ public void CheckLogon(IActionContext actionContext) throws InterruptedException throw new EPSCommonException("Service "+serviceName+" is not logged on."); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CleanMessages(IActionContext actionContext) { @@ -266,9 +254,7 @@ public void CleanMessages(IActionContext actionContext) client.getServiceHandler().cleanMessages(ServiceHandlerRoute.values()); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CleanAppMessages(IActionContext actionContext) { @@ -286,9 +272,7 @@ public void CleanAppMessages(IActionContext actionContext) } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CleanAdminMessages(IActionContext actionContext) { @@ -357,22 +341,20 @@ public void AskForContinue(IActionContext actionContext) throws InterruptedExcep "relatively - 16:56:00+1m (where 1m = 1 minute)
" + "17:00:00+3h (where 3h = 3 hours)
" + "17:13:00+25s (where 25s = 25 seconds)
") - @CustomColumns({ - @CustomColumn(value = "TimeSync", required = true) - }) + @CustomColumns(@CustomColumn(value = "TimeSync", required = true)) @ActionMethod public void TimeSync(IActionContext actionContext, HashMap inputData) throws Exception { - final DateTimeFormatter df = DateTimeUtility.createFormatter("HH:mm:ss"); + DateTimeFormatter df = DateTimeUtility.createFormatter("HH:mm:ss"); - final int s_ms = 1000; - final int m_ms = 60000; - final int h_ms = 3600000; + int s_ms = 1000; + int m_ms = 60000; + int h_ms = 3600000; String value = ((String) inputData.get("TimeSync")).trim(); - final StringTokenizer t = new StringTokenizer(value, "+"); + StringTokenizer t = new StringTokenizer(value, "+"); - final List tokens = new ArrayList<>(); + List tokens = new ArrayList<>(); while (t.hasMoreTokens()) { tokens.add(t.nextToken().trim()); } @@ -397,9 +379,13 @@ public void TimeSync(IActionContext actionContext, HashMap inputData) thro int mul = Integer.parseInt(token.substring(0, token.length()-1)); String smul2 = token.substring(token.length()-1, token.length()); int mul2 = 0; - if ("h".equals(smul2)) mul2 = h_ms; - else if ("m".equals(smul2)) mul2 = m_ms; - else if ("s".equals(smul2)) mul2 = s_ms; + if("h".equals(smul2)) { + mul2 = h_ms; + } else if("m".equals(smul2)) { + mul2 = m_ms; + } else if("s".equals(smul2)) { + mul2 = s_ms; + } abs += mul*mul2; } } @@ -413,9 +399,7 @@ public void TimeSync(IActionContext actionContext, HashMap inputData) thro } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public HashMap GetSettings(IActionContext actionContext) { @@ -431,9 +415,7 @@ public HashMap GetSettings(IActionContext actionContext) { } } - @CommonColumns({ - @CommonColumn(value = Column.Reference, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.Reference, required = true)) @ActionMethod public String GetEnvironmentName(IActionContext actionContext) { return actionContext.getEnvironmentName(); @@ -460,9 +442,7 @@ public String GetEnvironmentName(IActionContext actionContext) { * Value of "PathArgs" must contain path to script and its arguments, separated by space.
* @throws Exception - throws an exception */ - @CustomColumns({ - @CustomColumn(value = "PathArgs", required = true) - }) + @CustomColumns(@CustomColumn(value = "PathArgs", required = true)) @ActionMethod public void RunScript(IActionContext actionContext, HashMap inputData) throws Exception { String command = (String) inputData.get("PathArgs"); @@ -536,7 +516,7 @@ public void SaveBase64Content(IActionContext actionContext, HashMap inputD String content = (String) inputData.get("Content"); try (InputStream bais = new ByteArrayInputStream(content.getBytes()); - InputStream b64 = new Base64InputStream(bais, false);) { + InputStream b64 = new Base64InputStream(bais, false)) { saveContent(actionContext, inputData, b64); } } @@ -555,7 +535,7 @@ public void SaveBase64Content(IActionContext actionContext, HashMap inputD @CustomColumns({ @CustomColumn(value = "FileAlias", required = true), @CustomColumn(value = "Content", required = true), - @CustomColumn(value = "Append") + @CustomColumn("Append") }) @ActionMethod @Description("Save specified \"Content\" into file mapped by \"FileAlias\". " @@ -583,7 +563,7 @@ public void SaveContent(IActionContext actionContext, HashMap inputData) t @Description("Encode file to base64.
"+ "FileAlias - file to encode.
" + "Compress - do compress result string (y / Y / n / N).
") - @CommonColumns({ @CommonColumn(value = Column.Reference, required = true) }) + @CommonColumns(@CommonColumn(value = Column.Reference, required = true)) @CustomColumns({ @CustomColumn(value = "FileAlias", required = true), @CustomColumn(value = "Compress", required = false)}) @ActionMethod public String LoadBase64Content(IActionContext actionContext, HashMap inputData) throws Exception { @@ -597,7 +577,7 @@ public String LoadBase64Content(IActionContext actionContext, HashMap inpu byte[] result; - try (ByteArrayOutputStream os = new ByteArrayOutputStream();) { + try(ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (OutputStream b64 = new Base64OutputStream(os, true, -1, new byte[0]); InputStream dm = dataManager.getDataInputStream(target); InputStream is = compress ? new DeflaterInputStream(dm) : dm) { @@ -642,13 +622,13 @@ private void saveContent(IActionContext actionContext, HashMap inputData, */ private static String preparePath(String path) { if (path.startsWith("~")) { - path = System.getProperty("user.home") + path.substring(1); + return System.getProperty("user.home") + path.substring(1); } else if (path.startsWith("$HOME")) { - path = System.getProperty("user.home") + path.substring(5); + return System.getProperty("user.home") + path.substring(5); } else if (path.startsWith("$")) { String var = path.substring(1, path.indexOf(File.separator)); if (System.getenv().containsKey(var)) { - path = path.replace(path.substring(0, path.indexOf(File.separator)), System.getenv(var)); + return path.replace(path.substring(0, path.indexOf(File.separator)), System.getenv(var)); } else { throw new RuntimeException("Can't find environment variable " + var); } @@ -688,8 +668,9 @@ private static String[] toPathArgs(String command) { //remove empty args Iterator it = args.iterator(); while(it.hasNext()){ - if(it.next().trim().isEmpty()) + if(it.next().trim().isEmpty()) { it.remove(); + } } String[] result = new String[args.size()]; for (int i = 0; i < args.size(); i++) { @@ -706,9 +687,7 @@ private static String[] toPathArgs(String command) { * Value of "Command" must contain path to script, its arguments must be in column with it name.
* @throws Exception - throws an exception */ - @CustomColumns({ - @CustomColumn(value = "Command", required = true) - }) + @CustomColumns(@CustomColumn(value = "Command", required = true)) @ActionMethod public void RunScriptWithArgs(IActionContext actionContext, HashMap inputData) throws Exception { String command = preparePath((String) inputData.get("Command")); @@ -717,7 +696,7 @@ public void RunScriptWithArgs(IActionContext actionContext, HashMap inputD pathArgs.add(command); for(Object arg:inputData.keySet()) { - if(!((String)arg).equals("Command")) { + if(!"Command".equals((String)arg)) { pathArgs.add((String)arg + "=" +inputData.get(arg)); } } @@ -766,7 +745,7 @@ public void CheckMessage(IActionContext actionContext, HashMap filterData) Throwable problem = null; - for ( Map.Entry entry : filterData.entrySet() ) { + for(Entry entry : filterData.entrySet()) { ComparisonResult curResult = new ComparisonResult(entry.getKey().toString()); curResult.setExpected("True"); @@ -775,9 +754,9 @@ public void CheckMessage(IActionContext actionContext, HashMap filterData) try { Boolean result = (Boolean)MVEL.eval(entry.getValue().toString()); - if ( result ) - curResult.setStatus(StatusType.PASSED); - else { + if(result) { + curResult.setStatus(StatusType.PASSED); + } else { curResult.setStatus(StatusType.FAILED); compResult.setStatus(StatusType.FAILED); } @@ -821,9 +800,6 @@ public void CheckMessage(IActionContext actionContext, HashMap filterData) @Description("Create message with pair column / value. Value will have type String if it is not contain AML constructions.") @ActionMethod public HashMap SetVariables(IActionContext actionContext, HashMap message) throws Exception { - if (message.size() > 0) { - return message; - } - return null; + return message.isEmpty() ? null : message; } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ConvertUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ConvertUtil.java index 6776fa7c..77afb7f7 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ConvertUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ConvertUtil.java @@ -32,7 +32,7 @@ import com.exactpro.sf.scriptrunner.utilitymanager.UtilityMethod; @MatrixUtils -@ResourceAliases({"ConvertUtil"}) +@ResourceAliases("ConvertUtil") public class ConvertUtil extends AbstractCaller { @UtilityMethod @Description("Converts a Number value with zero precision to BigDecimal.
" @@ -40,11 +40,7 @@ public class ConvertUtil extends AbstractCaller { + "Example:
" + "#{toBigDecimal(5.444)} returns 5.444") public BigDecimal toBigDecimal(Number value) { - if(value == null) { - return null; - } - - return toBigDecimal(value.toString(), 0); + return value == null ? null : toBigDecimal(value.toString(), 0); } @UtilityMethod @@ -54,11 +50,7 @@ public BigDecimal toBigDecimal(Number value) { + "Example:
" + "#{toBigDecimal(5.444, 3)} returns 5.44") public BigDecimal toBigDecimal(Number value, int presision) { - if(value == null) { - return null; - } - - return toBigDecimal(value.toString(), presision); + return value == null ? null : toBigDecimal(value.toString(), presision); } @UtilityMethod @@ -67,11 +59,7 @@ public BigDecimal toBigDecimal(Number value, int presision) { + "Example:
" + "#{toBigDecimal(\"5.0\")} returns 5.0") public BigDecimal toBigDecimal(String value) { - if(value == null) { - return null; - } - - return new BigDecimal(value); + return value == null ? null : new BigDecimal(value); } @UtilityMethod @@ -95,11 +83,7 @@ public BigDecimal toBigDecimal(String value, int presision) { + "Example:
" + "#{toDouble(5)} returns 5.0") public Double toDouble(Number value) { - if(value == null) { - return null; - } - - return value.doubleValue(); + return value == null ? null : value.doubleValue(); } @UtilityMethod @@ -108,11 +92,7 @@ public Double toDouble(Number value) { + "Example:
" + "#{toDouble(\"5\")} returns 5.0") public Double toDouble(String value) { - if(value == null) { - return null; - } - - return Double.valueOf(value); + return value == null ? null : Double.valueOf(value); } @UtilityMethod @@ -121,11 +101,7 @@ public Double toDouble(String value) { + "Example:
" + "#{toInteger(5.0)} returns 5") public Integer toInteger(Number value) { - if(value == null) { - return null; - } - - return value.intValue(); + return value == null ? null : value.intValue(); } @UtilityMethod @@ -134,11 +110,7 @@ public Integer toInteger(Number value) { + "Example:
" + "#{toInteger(\"5\")} returns 5") public Integer toInteger(String value) { - if(value == null) { - return null; - } - - return Integer.valueOf(value); + return value == null ? null : Integer.valueOf(value); } @UtilityMethod @@ -147,11 +119,7 @@ public Integer toInteger(String value) { + "Example:
" + "#{toByte(5)} returns 5") public Byte toByte(Number value) { - if(value == null) { - return null; - } - - return value.byteValue(); + return value == null ? null : value.byteValue(); } @UtilityMethod @@ -160,11 +128,7 @@ public Byte toByte(Number value) { + "Example:
" + "#{toByte(\"5\")} returns 5") public Byte toByte(String value) { - if(value == null) { - return null; - } - - return Byte.valueOf(value); + return value == null ? null : Byte.valueOf(value); } @UtilityMethod @@ -173,11 +137,7 @@ public Byte toByte(String value) { + "Example:
" + "#{toShort(5)} returns 5") public Short toShort(Number value) { - if(value == null) { - return null; - } - - return value.shortValue(); + return value == null ? null : value.shortValue(); } @UtilityMethod @@ -186,11 +146,7 @@ public Short toShort(Number value) { + "Example:
" + "#{toShort(\"5\")} returns 5") public Short toShort(String value) { - if(value == null) { - return null; - } - - return Short.valueOf(value); + return value == null ? null : Short.valueOf(value); } @UtilityMethod @@ -199,11 +155,7 @@ public Short toShort(String value) { + "Example:
" + "#{toFloat(5)} returns 5.0") public Float toFloat(Number value) { - if(value == null) { - return null; - } - - return value.floatValue(); + return value == null ? null : value.floatValue(); } @UtilityMethod @@ -212,11 +164,7 @@ public Float toFloat(Number value) { + "Example:
" + "#{toFloat(\"5\")} returns 5.0") public Float toFloat(String value) { - if(value == null) { - return null; - } - - return Float.valueOf(value); + return value == null ? null : Float.valueOf(value); } @UtilityMethod @@ -238,11 +186,7 @@ public Long toLong(Number value) { + "Example:
" + "#{toLong(\"5\")} returns 5") public Long toLong(String value) { - if(value == null) { - return null; - } - - return Long.valueOf(value); + return value == null ? null : Long.valueOf(value); } @UtilityMethod @@ -251,10 +195,7 @@ public Long toLong(String value) { + "Considering the above said, the final syntax is:
" + "#{toString(value)}") public String toString(Object value) { - if (value != null) { - return value.toString(); - } - return null; + return value != null ? value.toString() : null; } @UtilityMethod @@ -408,10 +349,7 @@ public Character toChar(Object value, Boolean isDigit) { throw new IllegalArgumentException("No action for value type [" + value.getClass().getCanonicalName() + "]"); } - if (Boolean.TRUE.equals(isDigit)) { - return (char) (charValue + '0'); - } - return charValue; + return Boolean.TRUE.equals(isDigit) ? (char)(charValue + '0') : charValue; } @UtilityMethod @@ -459,18 +397,11 @@ public Map toMap(Object... values) { + "Example:
" + "#{toList(\"Text\", \"example!\")} returns [Test, example]") public List toList(Object... values) { - if(values == null) { - return null; - } - - return Arrays.asList(values); + return values == null ? null : Arrays.asList(values); } protected Object extractValue(Object value) { - if (value instanceof IBaseEnumField) { - value = ((IBaseEnumField)value).getObjectValue(); - } - return value; + return value instanceof IBaseEnumField ? ((IBaseEnumField)value).getObjectValue() : value; } @UtilityMethod @@ -480,11 +411,6 @@ protected Object extractValue(Object value) { + "#{toRegex(\"Text example!\")} returns \\QText example!\\E") public String toRegex(Object value) { String stringValue = toString(value); - - if(stringValue == null) { - return null; - } - - return Pattern.quote(stringValue); + return stringValue == null ? null : Pattern.quote(stringValue); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java index 9c78c8c4..8554265f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/DateUtil.java @@ -15,12 +15,6 @@ ******************************************************************************/ package com.exactpro.sf.actions; - -import java.util.List; -import java.util.Objects; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; @@ -31,11 +25,16 @@ import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.Temporal; +import java.util.List; +import java.util.Objects; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.actions.data.DateComponent; import com.exactpro.sf.actions.data.DateModificator; import com.exactpro.sf.aml.Description; +import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.configuration.ResourceAliases; import com.exactpro.sf.scriptrunner.AbstractCaller; import com.exactpro.sf.scriptrunner.utilitymanager.UtilityMethod; @@ -47,9 +46,9 @@ * */ @MatrixUtils -@ResourceAliases({"DateUtil"}) +@ResourceAliases("DateUtil") public class DateUtil extends AbstractCaller { - private static Logger logger = LoggerFactory.getLogger(DateUtil.class); + private static final Logger logger = LoggerFactory.getLogger(DateUtil.class); private static final String DATE_COMPONENTS = "
YYear" + @@ -221,10 +220,10 @@ public final LocalDateTime getDateTime(String modifyPattern, boolean skipWeekend DayOfWeek dayOfWeek = modifiedDate.getDayOfWeek(); long currentMillis = DateTimeUtility.getMillisecond(nowDate); long modifiedMillis = DateTimeUtility.getMillisecond(modifiedDate); - if (DayOfWeek.SATURDAY.equals(dayOfWeek)) { + if(dayOfWeek == DayOfWeek.SATURDAY) { int shift = modifiedMillis - currentMillis >= 0 ? 2 : -1; return modifiedDate.plusDays(shift); - } else if (DayOfWeek.SUNDAY.equals(dayOfWeek)) { + } else if(dayOfWeek == DayOfWeek.SUNDAY) { int shift = modifiedMillis - currentMillis >= 0 ? 1 : -2; return modifiedDate.plusDays(shift); } @@ -388,21 +387,21 @@ public LocalDateTime toDateTime(String source) { StringBuilder builder = new StringBuilder(); switch (source.length()) { - case (29): + case 29: builder.insert(0, " Z"); - case (23): + case 23: builder.insert(0, ".SSS"); - case (19): + case 19: builder.insert(0, ":ss"); - case (16): + case 16: builder.insert(0, ":mm"); - case (13): + case 13: builder.insert(0, " HH"); - case (10): + case 10: builder.insert(0, "-dd"); - case (7): + case 7: builder.insert(0, "-MM"); - case (4): + case 4: builder.insert(0, "yyyy"); break; default: @@ -683,7 +682,7 @@ private LocalDateTime getBusinessDateTime(LocalDateTime original, LocalDateTime while (past ? !iter.toLocalDate().isBefore(after.toLocalDate()) : !iter.toLocalDate().isAfter(after.toLocalDate())) { DayOfWeek dayOfWeek = iter.getDayOfWeek(); - if (dayOfWeek.equals(DayOfWeek.SATURDAY) || dayOfWeek.equals(DayOfWeek.SUNDAY)) { + if(dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) { after = after.plusDays(counter); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/EncodingUtility.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/EncodingUtility.java index 262ceaba..9f2b0b6a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/EncodingUtility.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/EncodingUtility.java @@ -32,7 +32,7 @@ import java.util.zip.InflaterInputStream; @MatrixUtils -@ResourceAliases({"EncodingUtility"}) +@ResourceAliases("EncodingUtility") public class EncodingUtility extends AbstractCaller { @Description("Encodes string to base64.
"+ "content - string to encode.
" + diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeActions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeActions.java index b23ab90e..99f78f0c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeActions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeActions.java @@ -57,7 +57,7 @@ */ @MatrixActions -@ResourceAliases({"FakeActions"}) +@ResourceAliases("FakeActions") public class FakeActions extends AbstractCaller { @CommonColumns({ diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeUtils.java index 43812b0f..8ea122d9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/FakeUtils.java @@ -23,7 +23,7 @@ import com.exactpro.sf.scriptrunner.utilitymanager.UtilityMethod; import com.exactpro.sf.util.DateTimeUtility; -@ResourceAliases({"FakeUtils"}) +@ResourceAliases("FakeUtils") public class FakeUtils extends AbstractCaller { private static final String FIX_DATE_FORMAT = "yyyyMMdd-HH:mm:ss"; private static final DateTimeFormatter FIX_FORMATTER = DateTimeUtility.createFormatter(FIX_DATE_FORMAT); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MathUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MathUtil.java index abd2d1da..8858de4b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MathUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MathUtil.java @@ -29,7 +29,7 @@ import com.exactpro.sf.scriptrunner.utilitymanager.UtilityMethod; @MatrixUtils -@ResourceAliases({"MathUtil"}) +@ResourceAliases("MathUtil") public class MathUtil extends AbstractCaller { private static final String ROUNDING_MODES = "Rounding Modes:
" + @@ -46,9 +46,7 @@ public class MathUtil extends AbstractCaller { "FLOOR - Rounding mode to round towards negative infinity.
" + "If the value is positive, behave as for DOWN; if negative, behave as for UP.
"; - public MathUtil() {} - - @Description("Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
" + @Description("Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
" + "Special cases:
" + "If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
" + "If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
" @@ -301,15 +299,15 @@ public int roundUp(double value) { } private static long round(long num, int multiplier) { - return ((int) (((num / (double) multiplier) - num / multiplier) * 10) >= 5 ? roundUp(num, multiplier) - : roundDown(num, multiplier)); + return (int) (((num / (double) multiplier) - num / multiplier) * 10) >= 5 ? roundUp(num, multiplier) + : roundDown(num, multiplier); } private static long roundUp(long num, int multiplier) { - return ((num / multiplier) * multiplier + multiplier); + return (num / multiplier) * multiplier + multiplier; } private static long roundDown(long num, int multiplier) { - return ((num / multiplier) * multiplier); + return (num / multiplier) * multiplier; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MessageUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MessageUtil.java index 4b2eb879..68f3bde4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MessageUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MessageUtil.java @@ -28,7 +28,7 @@ import com.exactpro.sf.scriptrunner.utilitymanager.UtilityMethod; @MatrixUtils -@ResourceAliases({"MessageUtil"}) +@ResourceAliases("MessageUtil") public class MessageUtil extends AbstractCaller { @Description("Finds a message within the list, matching the specified field.
" + @@ -66,11 +66,7 @@ public IMessage FindGroup(List groups, String fieldName, Object fieldV public Object FindField(List groups, String fieldName, Object fieldValue, String targetFieldName) { IMessage msg = FindGroup(groups, fieldName, fieldValue); targetFieldName = targetFieldName != null ? targetFieldName.trim() : null; - if (msg.isFieldSet(targetFieldName)) { - return msg.getField(targetFieldName); - } else { - return null; - } + return msg.isFieldSet(targetFieldName) ? msg.getField(targetFieldName) : null; } @Description("Returns the special object representing any value.
" + diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MiscUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MiscUtils.java index b7f896c4..364797c9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MiscUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/MiscUtils.java @@ -40,7 +40,7 @@ import com.exactpro.sf.util.KnownBugPostValidation; @MatrixUtils -@ResourceAliases({"MiscUtils"}) +@ResourceAliases("MiscUtils") public class MiscUtils extends AbstractCaller { @Description("Returns a random element from an array of strings.
" diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/NetworkUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/NetworkUtils.java index e952c917..4b3ec66f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/NetworkUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/NetworkUtils.java @@ -30,7 +30,7 @@ import com.exactpro.sf.scriptrunner.utilitymanager.UtilityMethod; @MatrixUtils -@ResourceAliases({"NetworkUtils"}) +@ResourceAliases("NetworkUtils") public class NetworkUtils extends AbstractCaller { @Description("Returns the IPv4 for the specified network interface name.
" + diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ServiceActions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ServiceActions.java index c1665830..55fccf89 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ServiceActions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/ServiceActions.java @@ -49,7 +49,7 @@ * @author nikita.smirnov * */ -@ResourceAliases({"ServiceActions"}) +@ResourceAliases("ServiceActions") public class ServiceActions extends AbstractCaller { //TODO: change to service_uri someday @@ -62,12 +62,8 @@ protected ConvertUtilsBean initialValue() { } }; - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) - @CustomColumns({ - @CustomColumn(value = SERVICE_TYPE, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) + @CustomColumns(@CustomColumn(value = SERVICE_TYPE, required = true)) @ActionMethod public void createService(IActionContext actionContext, HashMap message) { try { @@ -102,9 +98,7 @@ public void createService(IActionContext actionContext, HashMap message) { } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void deleteService(IActionContext actionContext) { try { @@ -115,9 +109,7 @@ public void deleteService(IActionContext actionContext) { } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void startService(IActionContext actionContext) { ServiceName serviceName = ServiceName.parse(actionContext.getServiceName()); @@ -131,9 +123,7 @@ public void startService(IActionContext actionContext) { } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void stopService(IActionContext actionContext) { ServiceName serviceName = ServiceName.parse(actionContext.getServiceName()); @@ -145,9 +135,7 @@ public void stopService(IActionContext actionContext) { } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void initService(IActionContext actionContext, HashMap message) { ServiceName serviceName = ServiceName.parse(actionContext.getServiceName()); @@ -186,9 +174,7 @@ public void initService(IActionContext actionContext, HashMap message) { } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public HashMap getServiceSettings(IActionContext actionContext) { IService service = SFLocalContext.getDefault().getConnectionManager().getService(ServiceName.parse(actionContext.getServiceName())); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/TestActions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/TestActions.java index a165c761..c91c8cb6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/TestActions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/TestActions.java @@ -89,28 +89,24 @@ import com.google.common.collect.ImmutableSet; @MatrixActions -@ResourceAliases({"TestActions"}) +@ResourceAliases("TestActions") public class TestActions extends AbstractCaller { private static final Logger logger = LoggerFactory.getLogger(TestActions.class); private static final String FROM_TIMESTAMP = "#from_timestamp"; private static final String TO_TIMESTAMP = "#to_timestamp"; private static final String FORCE = "#force"; - private final String MESSAGES_SEPARATOR = ","; - private final long MIN_TIMEOUT = 2000l; - private final String SCRIPT_URIS_COLUMN = "#script_uris"; - private final String CONTEXT_COLUMN = "#context"; - private final List> SUPPORTED_TYPES; - - { - SUPPORTED_TYPES = Arrays.stream(JavaType.values()).map(x -> { - try { - return Class.forName(x.value()); - } catch(ClassNotFoundException e) { - throw new EPSCommonException(e); - } - }).collect(Collectors.toList()); - } + private static final String MESSAGES_SEPARATOR = ","; + private static final long MIN_TIMEOUT = 2000l; + private static final String SCRIPT_URIS_COLUMN = "#script_uris"; + private static final String CONTEXT_COLUMN = "#context"; + private static final List> SUPPORTED_TYPES = Arrays.stream(JavaType.values()).map(x -> { + try { + return Class.forName(x.value()); + } catch(ClassNotFoundException e) { + throw new EPSCommonException(e); + } + }).collect(Collectors.toList()); private final Map pluginAliasToEngineManager = new HashMap<>(); @@ -136,9 +132,7 @@ public IMessage send(IActionContext actionContext, IMessage msg) throws Interrup } @MessageDirection(direction=Direction.SENDDIRTY) - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public IMessage sendDirty(IActionContext actionContext, IMessage msg) throws InterruptedException { String serviceName = actionContext.getServiceName(); @@ -157,9 +151,7 @@ public IMessage sendDirty(IActionContext actionContext, IMessage msg) throws Int } @MessageDirection(direction=Direction.RECEIVE) - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public IMessage receive(IActionContext actionContext, IMessage msg) throws InterruptedException { @@ -178,7 +170,7 @@ public IMessage receive(IActionContext actionContext, IMessage msg) throws Inter @CustomColumn(value = TO_TIMESTAMP, type = LocalDateTime.class) }) @ActionMethod - public IMessage retrieve(final IActionContext actionContext, IMessage message) throws InterruptedException { + public IMessage retrieve(IActionContext actionContext, IMessage message) throws InterruptedException { IService service = ActionUtil.getService(actionContext, IService.class); IActionReport report = actionContext.getReport(); @@ -203,7 +195,7 @@ public IMessage retrieve(final IActionContext actionContext, IMessage message) t @CustomColumn(value = TO_TIMESTAMP, type = LocalDateTime.class) }) @ActionMethod - public void countStored(final IActionContext actionContext, IMessage message) throws InterruptedException { + public void countStored(IActionContext actionContext, IMessage message) throws InterruptedException { IService service = ActionUtil.getService(actionContext, IService.class); ICSHIterator iterator = new JsonMessageIterator(actionContext, service, message); ComparatorSettings compSettings = WaitAction.createCompareSettings(actionContext, null, message); @@ -247,7 +239,7 @@ public void countAdmin(IActionContext actionContext) throws Exception } @CommonColumns({ - @CommonColumn(value = Column.Timeout), + @CommonColumn(Column.Timeout), @CommonColumn(value = Column.ServiceName, required = true) }) @ActionMethod @@ -278,12 +270,10 @@ public void connectService(IActionContext actionContext) "Use the '" + FORCE + "' column to control disconnect logic: if 'true' then no logout message will be sent." + "The default value is 'false'.
") @CommonColumns({ - @CommonColumn(value = Column.Timeout), + @CommonColumn(Column.Timeout), @CommonColumn(value = Column.ServiceName, required = true) }) - @CustomColumns({ - @CustomColumn(value = FORCE, type = Boolean.class) - }) + @CustomColumns(@CustomColumn(value = FORCE, type = Boolean.class)) @ActionMethod public void disconnectService(IActionContext actionContext) { @@ -311,7 +301,7 @@ public void disconnectService(IActionContext actionContext) } @CommonColumns({ - @CommonColumn(value = Column.Timeout), + @CommonColumn(Column.Timeout), @CommonColumn(value = Column.ServiceName, required = true) }) @ActionMethod @@ -341,7 +331,7 @@ public void reconnectService(IActionContext actionContext) { @CommonColumns({ - @CommonColumn(value = Column.Timeout), + @CommonColumn(Column.Timeout), @CommonColumn(value = Column.ServiceName, required = true) }) @ActionMethod @@ -357,7 +347,7 @@ public void isConnectedService(IActionContext actionContext) throws Exception } @CommonColumns({ - @CommonColumn(value = Column.Timeout), + @CommonColumn(Column.Timeout), @CommonColumn(value = Column.ServiceName, required = true) }) @ActionMethod @@ -433,9 +423,7 @@ public void MarkerAML3(IActionContext actionContext){ report.createMessage(StatusType.PASSED, MessageLevel.INFO, "Marks the matrix as AML3"); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CheckActiveClients (IActionContext actionContext) { @@ -537,7 +525,7 @@ private Set checkType(Object value, List> supportedTypes, Strin } Set errors = new HashSet<>(); - Class valueClass = value.getClass(); + Class valueClass = value.getClass(); if(value instanceof List) { List list = (List)value; @@ -581,7 +569,7 @@ private void isConnected(IActionContext actionContext, IInitiatorService initiat do { session = initiatorService.getSession(); - isConnected = null != session && !session.isClosed(); + isConnected = session != null && !session.isClosed(); } while(!isConnected && waitUntil > System.currentTimeMillis()); IActionReport report = actionContext.getReport(); @@ -637,7 +625,7 @@ public boolean hasNext(long timeout) throws InterruptedException { @Override public boolean hasNext() { - return System.currentTimeMillis() < this.endTime && this.iterator.hasNext(); + return System.currentTimeMillis() < endTime && iterator.hasNext(); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateComponent.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateComponent.java index 4e4ab97f..2285a077 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateComponent.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateComponent.java @@ -53,19 +53,19 @@ public static DateComponent parse(String datePart) { } public long diff(LocalDateTime minuend, LocalDateTime subtrahend) { - return this.temporalField.getBaseUnit().between(subtrahend, minuend); + return temporalField.getBaseUnit().between(subtrahend, minuend); } public int extract(Temporal source) { - return source.get(this.temporalField); + return source.get(temporalField); } public TemporalField getTemporalField() { - return this.temporalField; + return temporalField; } @Override public String toString() { - return this.datePart; + return datePart; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateModificator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateModificator.java index 2d695235..d6f2025c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateModificator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/data/DateModificator.java @@ -15,13 +15,13 @@ ******************************************************************************/ package com.exactpro.sf.actions.data; +import java.time.temporal.Temporal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; -import java.time.temporal.Temporal; public class DateModificator { @@ -80,7 +80,7 @@ private static Strategy searchStrategy(String value) { } public T modify(T source) { - return this.strategy.modify(source, this.dateComponent, this.value); + return strategy.modify(source, dateComponent, value); } private enum Strategy { @@ -108,7 +108,7 @@ public T modify(T source, DateComponent dateComponent, long private final char symbol; - private Strategy(char symbol) { + Strategy(char symbol) { this.symbol = symbol; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/tools/Filters.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/tools/Filters.java index 26463dfd..db5f3a57 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/tools/Filters.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/actions/tools/Filters.java @@ -18,9 +18,9 @@ import java.util.Objects; import java.util.function.Function; -import com.exactpro.sf.aml.scriptutil.ExpressionResult; import org.apache.commons.lang3.ObjectUtils; +import com.exactpro.sf.aml.scriptutil.ExpressionResult; import com.exactpro.sf.aml.scriptutil.MvelException; import com.exactpro.sf.aml.scriptutil.StaticUtil; import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; @@ -119,7 +119,7 @@ public FunctionFilter(long line, String column, Object value) { @SuppressWarnings("unchecked") @Override public ExpressionResult validate(Object value) { - return ExpressionResult.create(this.function.apply((T)value)); + return ExpressionResult.create(function.apply((T)value)); } @Override @@ -134,10 +134,10 @@ public String getCondition(Object value) { @Override public Object getValue() throws MvelException { - if (this.value == NOT_PRESENT) { - throw new MvelException(line, column, "Cannot get value from " + this.getClass().getSimpleName()); + if(value == NOT_PRESENT) { + throw new MvelException(line, column, "Cannot get value from " + getClass().getSimpleName()); } - return this.value; + return value; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AML.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AML.java index 7ec27ff5..f9557c30 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AML.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AML.java @@ -78,34 +78,23 @@ public class AML { * 4) java formulas with references */ - private static Logger logger = LoggerFactory.getLogger(AML.class); + private static final Logger logger = LoggerFactory.getLogger(AML.class); - private final static String EOL = System.getProperty("line.separator"); - public final static String INCLUDE_BLOCK_OLD = "Include Block"; - public final static String INCLUDE_BLOCK = INCLUDE_BLOCK_OLD.replace(" ", ""); - public final static SailfishURI INCLUDE_BLOCK_URI; + private static final String EOL = System.getProperty("line.separator"); - public final static String PACKAGE_NAME = "com.exactpro.sf.testscript.matrix"; - public final static String CLASS_NAME = "Matrix"; - public final static String PACKAGE_PATH = AML.PACKAGE_NAME.replace(".", File.separator) + File.separator; + public static final String PACKAGE_NAME = "com.exactpro.sf.testscript.matrix"; + public static final String CLASS_NAME = "Matrix"; + public static final String PACKAGE_PATH = PACKAGE_NAME.replace(".", File.separator) + File.separator; - private final static long M10 = 10*1024*1024L; - - static { - try { - INCLUDE_BLOCK_URI = new SailfishURI(null, null, INCLUDE_BLOCK); - } catch(SailfishURIException e) { - throw new EPSCommonException(e); - } - } + private static final long M10 = 10 * 1024 * 1024L; private final AMLSettings amlSettings; - private AlertCollector alertCollector; + private final AlertCollector alertCollector; private List testCases; private AMLMatrix matrix; - private List progressListeners; + private final List progressListeners; private final IWorkspaceDispatcher workspaceDispatcher; private final IAdapterManager adapterManager; @@ -141,19 +130,19 @@ public AML(AMLSettings settings, IWorkspaceDispatcher workspaceDispatcher, IAdap public GeneratedScript run(ScriptContext scriptContext, String fileEncoding) throws AMLException, IOException, InterruptedException { - try(AdvancedMatrixReader reader = initReader(this.amlSettings.getMatrixPath(), fileEncoding)) { - if(this.alertCollector.getCount(AlertType.ERROR) != 0) { + try(AdvancedMatrixReader reader = initReader(amlSettings.getMatrixPath(), fileEncoding)) { + if(alertCollector.getCount(AlertType.ERROR) != 0) { this.matrix = new AMLMatrix(new ArrayList(), new ArrayList()); - throw new AMLException("Errors detected on reader initialization", this.alertCollector); + throw new AMLException("Errors detected on reader initialization", alertCollector); } - return run(scriptContext, AMLReader.read(reader, this.amlSettings.isSkipOptional())); + return run(scriptContext, AMLReader.read(reader, amlSettings.isSkipOptional())); } catch(AMLException e) { throw e; } catch(Exception e) { - throw new AMLException(e.getMessage(), e, this.alertCollector); + throw new AMLException(e.getMessage(), e, alertCollector); } finally { - this.progressListeners.clear(); + progressListeners.clear(); } } @@ -188,9 +177,10 @@ public GeneratedScript run(ScriptContext scriptContext, AMLMatrix matrix) throws progressListeners, compilerClassPath); - for (IPreprocessor preprocessor : this.amlSettings.getPreprocessors()) { - if (!preprocessor.preprocess(scriptContext.getEnvironmentName(), this, matrix, this.alertCollector)) - throw new AMLException("Preprocessor " + preprocessor.getName() + " detect errors", this.alertCollector); + for(IPreprocessor preprocessor : amlSettings.getPreprocessors()) { + if(!preprocessor.preprocess(scriptContext.getEnvironmentName(), this, matrix, alertCollector)) { + throw new AMLException("Preprocessor " + preprocessor.getName() + " detect errors", alertCollector); + } } GeneratedScript script = null; @@ -198,23 +188,25 @@ public GeneratedScript run(ScriptContext scriptContext, AMLMatrix matrix) throws try { script = codeGen.generateCode(blocks.get(AMLBlockType.TestCase), blocks.get(AMLBlockType.BeforeTCBlock), blocks.get(AMLBlockType.AfterTCBlock)); } finally { - this.alertCollector.add(codeGen.getAlertCollector()); + alertCollector.add(codeGen.getAlertCollector()); } - for (IValidator validator : this.amlSettings.getValidators()) { - if (!validator.validate(matrix, actionManager, languageURI, this.alertCollector)) - throw new AMLException("Validator " + validator.getName() + " detect errors", this.alertCollector); + for(IValidator validator : amlSettings.getValidators()) { + if(!validator.validate(matrix, actionManager, languageURI, alertCollector)) { + throw new AMLException("Validator " + validator.getName() + " detect errors", alertCollector); + } } return script; } finally { - if (codeGen != null) + if(codeGen != null) { codeGen.cleanup(); + } } } public AlertCollector getAlertCollector() { - return this.alertCollector; + return alertCollector; } protected AdvancedMatrixReader initReader(String matrixFile, String fileEncoding) throws IOException { @@ -222,7 +214,7 @@ protected AdvancedMatrixReader initReader(String matrixFile, String fileEncoding try { file = workspaceDispatcher.getFile(FolderType.REPORT, matrixFile); } catch (FileNotFoundException ex) { - this.alertCollector.add(new Alert("Input CSV/XLS file not found: "+matrixFile)); + alertCollector.add(new Alert("Input CSV/XLS file not found: " + matrixFile)); return null; } @@ -230,11 +222,11 @@ protected AdvancedMatrixReader initReader(String matrixFile, String fileEncoding try { reader = new AdvancedMatrixReader(file, fileEncoding); } catch (AMLException e) { - this.alertCollector.add(new Alert(e.getMessage())); + alertCollector.add(new Alert(e.getMessage())); } if (reader != null && !reader.hasNext()) { - this.alertCollector.add(new Alert("Input CSV/XLS/XLSX file is empty: "+matrixFile)); + alertCollector.add(new Alert("Input CSV/XLS/XLSX file is empty: " + matrixFile)); } return reader; @@ -311,15 +303,16 @@ private static void doCompile(List option, List javaFiles) throws printWriter.flush(); boolean isCompiled = compiler.getTask(printWriter, fileManager,null, option, null, units).call(); - if (!isCompiled) - throw new ScriptRunException("Could not compile sources: " + EOL + writer.toString()); + if(!isCompiled) { + throw new ScriptRunException("Could not compile sources: " + EOL + writer); + } } public void cleanup() { - if (this.testCases != null) { - this.testCases.clear(); - this.testCases = null; + if(testCases != null) { + testCases.clear(); + testCases = null; } } @@ -350,21 +343,21 @@ public void writeMatrix(String namePrefix, AMLMatrix matrix) { } public void addProgressListener(IProgressListener iProgressListener) { - this.progressListeners.add(iProgressListener); + progressListeners.add(iProgressListener); } public void removeProgressListener(IProgressListener iProgressListener) { - this.progressListeners.remove(iProgressListener); + progressListeners.remove(iProgressListener); } private void onProgressChanged(int i) { - for (IProgressListener listener : this.progressListeners) { + for(IProgressListener listener : progressListeners) { listener.onProgressChanged(i); } } private void onDetermineLanguage(SailfishURI languageURI) { - for (IProgressListener listener : this.progressListeners) { + for(IProgressListener listener : progressListeners) { listener.onDetermineLanguage(languageURI); } } @@ -374,7 +367,7 @@ private void onDetermineLanguage(SailfishURI languageURI) { * @return */ protected List getTestCases() { - return this.testCases; + return testCases; } /* diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLAction.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLAction.java index 4283fb13..bf2abb1c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLAction.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLAction.java @@ -25,7 +25,6 @@ import java.util.Map.Entry; import java.util.Set; -import com.exactpro.sf.aml.reader.struct.ExecutionMode; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -33,6 +32,7 @@ import com.exactpro.sf.aml.generator.AMLGenerateStatus; import com.exactpro.sf.aml.generator.matrix.Column; import com.exactpro.sf.aml.generator.matrix.Value; +import com.exactpro.sf.aml.reader.struct.ExecutionMode; import com.exactpro.sf.common.util.Pair; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.scriptrunner.actionmanager.ActionInfo; @@ -49,19 +49,19 @@ public class AMLAction implements IAction, Cloneable, Serializable { private static final String GENERATION_PATH_DELIMITER = " -> "; - private final Map parameters; - private final Map serviceFields; - private Map definedServiceFields; //all defined and interpreted service fields (copy) - private final Set definedColumns; + private final Map parameters = new HashMap<>(); + private final Map serviceFields = new HashMap<>(); + private final Map definedServiceFields = new HashMap<>(); //all defined and interpreted service fields (copy) + private final Set definedColumns = new HashSet<>(); private String reference = ""; private String referenceToFilter = ""; private String template = ""; - private String id = null; - private String serviceName = null; + private String id; + private String serviceName; private ExecutionMode executionMode = ExecutionMode.EXECUTABLE; - private SailfishURI actionURI = null; // null if not set - private SailfishURI dictionaryURI = null; - private Value timeout = null; + private SailfishURI actionURI; // null if not set + private SailfishURI dictionaryURI; + private Value timeout; private long line; private Class actionParameterType; private String checkPoint; @@ -69,31 +69,31 @@ public class AMLAction implements IAction, Cloneable, Serializable { private String description = ""; private boolean addToReport = true; private AMLGenerateStatus generateStatus = AMLGenerateStatus.NOT_GENERATED; - private StringBuilder generationPathBuilder; - private String messageCount = null; - private final List> setters; + private final StringBuilder generationPathBuilder = new StringBuilder(); + private String messageCount; + private final List> setters = new ArrayList<>(); private String doublePrecision = ""; private String systemPrecision = ""; private String failUnexpected = ""; private String staticType; private Value staticValue; - private boolean continueOnFailed = false; - private boolean breakPoint = false; - private boolean autoStart = false; + private boolean continueOnFailed; + private boolean breakPoint; + private boolean autoStart; private List headers; private String outcome; private String outcomeGroup; private String outcomeName; - private boolean isLastOutcome = false; - private boolean isGroupFinished = false; - private boolean checkGroupsOrder = false; - private Map messageReferences; - private List> children; + private boolean isLastOutcome; + private boolean isGroupFinished; + private boolean checkGroupsOrder; + private Map messageReferences = new HashMap<>(); + private final List> children = new ArrayList<>(); private Value condition; private String includeBlockReference = ""; - private boolean reorderGroups = false; + private boolean reorderGroups; private ActionInfo actionInfo; - private boolean staticAction = false; + private boolean staticAction; private String tag; private List dependencies = Collections.emptyList(); private List verificationsOrder = Collections.emptyList(); @@ -101,52 +101,42 @@ public class AMLAction implements IAction, Cloneable, Serializable { private final long uid; public AMLAction(long uid, int hash) { - this.parameters = new HashMap<>(); - this.serviceFields = new HashMap<>(); - this.definedServiceFields = new HashMap<>(); - this.definedColumns = new HashSet<>(); - this.setters = new ArrayList<>(); - this.messageReferences = new HashMap<>(); - this.children = new ArrayList<>(); - this.generationPathBuilder = new StringBuilder(); - this.uid = uid; + this.uid = uid; this.hash = hash; } @Override public void setReference(String ref) { - this.reference = (ref == null) ? "" : ref; + this.reference = StringUtils.defaultString(ref); } @Override public String getReference() { - return this.reference; + return reference; } @Override - public boolean hasReference() - { - return this.reference != null && !this.reference.equals(""); + public boolean hasReference() { + return StringUtils.isNotEmpty(reference); } @Override public void setReferenceToFilter(String ref) { - this.referenceToFilter = (ref == null) ? "" : ref; + this.referenceToFilter = StringUtils.defaultString(ref); } @Override - public boolean hasReferenceToFilter() - { - return this.referenceToFilter != null && false == this.referenceToFilter.equals(""); - } + public boolean hasReferenceToFilter() { + return StringUtils.isNotEmpty(referenceToFilter); + } @Override public String getReferenceToFilter() { - return this.referenceToFilter; + return referenceToFilter; } @Override @@ -156,47 +146,46 @@ public String getTemplate() { @Override public void setTemplate(String template) { - this.template = template == null ? "" : template; + this.template = StringUtils.defaultString(template); } @Override public boolean hasTemplate() { - return this.template != null && !this.template.equals(""); - } + return StringUtils.isNotEmpty(template); + } @Override public void put(String key, Value value) { - this.parameters.put(key, value); + parameters.put(key, value); } public void remove(String key) { - this.parameters.remove(key); + parameters.remove(key); } @Override public Value get(String key) { - return this.parameters.get(key); + return parameters.get(key); } @Override public void setId(String id) { - this.id = (id != null) ? id : ""; + this.id = StringUtils.defaultString(id); } @Override public String getId() { - return this.id; + return id; } @Override - public boolean hasId() - { - return this.id != null && !this.id.trim().isEmpty(); - } + public boolean hasId() { + return StringUtils.isNotEmpty(id); + } @Override public void setServiceName(String serviceName) @@ -207,7 +196,7 @@ public void setServiceName(String serviceName) @Override public String getServiceName() { - return this.serviceName; + return serviceName; } @Override @@ -224,13 +213,13 @@ public void setExecutionMode(ExecutionMode executionMode) @Override public ExecutionMode getExecutionMode() { - return this.executionMode; + return executionMode; } @Override public SailfishURI getActionURI() { - return this.actionURI; + return actionURI; } @Override @@ -247,7 +236,7 @@ public boolean hasActionURI() { @Override public SailfishURI getDictionaryURI() { - return this.dictionaryURI; + return dictionaryURI; } @Override @@ -268,7 +257,7 @@ public void setTimeout(Value s) { @Override public Value getTimeout() { - return this.timeout; + return timeout; } public void setLine(long line) { @@ -276,12 +265,12 @@ public void setLine(long line) { } public long getLine() { - return this.line; + return line; } @Override public Map getParameters() { - return this.parameters; + return parameters; } public void setActionParameterType(Class type) @@ -291,7 +280,7 @@ public void setActionParameterType(Class type) public Class getActionParameterType() { - return this.actionParameterType; + return actionParameterType; } @Override @@ -301,12 +290,12 @@ public void setCheckPoint(String checkPoint) { @Override public String getCheckPoint() { - return this.checkPoint; + return checkPoint; } @Override public String getMessageTypeColumn() { - return this.messageTypeColumn; + return messageTypeColumn; } @Override @@ -315,34 +304,34 @@ public void setMessageTypeColumn(String mesageTypeColumn) { } public Map getServiceFields() { - return this.serviceFields; + return serviceFields; } public Value getServiceField(String key) { - return this.serviceFields.get(key); + return serviceFields.get(key); } public boolean isServiceFieldExist(String key) { - return this.serviceFields.containsKey(key); + return serviceFields.containsKey(key); } public void putServiceField(String key, Value value) { - this.serviceFields.put(key, value); + serviceFields.put(key, value); } @Override public void addDefinedColumn(String columnName) { - this.definedColumns.add(columnName); + definedColumns.add(columnName); } @Override public Set getDefinedColumns() { - return this.definedColumns; + return definedColumns; } @Override public String getDescrption() { - return this.description; + return description; } @Override @@ -355,7 +344,7 @@ public void setAddToReport(boolean addToReport) { } public boolean isAddToReport() { - return this.addToReport; + return addToReport; } public void setGenerateStatus(AMLGenerateStatus alreadyGenerated) { @@ -363,22 +352,22 @@ public void setGenerateStatus(AMLGenerateStatus alreadyGenerated) { } public AMLGenerateStatus getGenerateStatus() { - return this.generateStatus; + return generateStatus; } public void addGenerationSteps(String ... generationSteps) { if (generationSteps != null) { for (int i = 0; i < generationSteps.length; i++) { if (!generationSteps[i].trim().isEmpty()) { - this.generationPathBuilder.append(generationSteps[i]).append(GENERATION_PATH_DELIMITER); + generationPathBuilder.append(generationSteps[i]).append(GENERATION_PATH_DELIMITER); } } } } public String getGenerationPath() { - if (this.generationPathBuilder.length() >= GENERATION_PATH_DELIMITER.length()) { - return this.generationPathBuilder.substring(0, this.generationPathBuilder.length() - GENERATION_PATH_DELIMITER.length()); + if(generationPathBuilder.length() >= GENERATION_PATH_DELIMITER.length()) { + return generationPathBuilder.substring(0, generationPathBuilder.length() - GENERATION_PATH_DELIMITER.length()); } return ""; } @@ -390,16 +379,16 @@ public void setMessageCount(String messageCount) { @Override public String getMessageCount() { - return this.messageCount; + return messageCount; } public List> getSetters() { - return this.setters; + return setters; } @Override public String getDoublePrecision() { - return this.doublePrecision; + return doublePrecision; } @Override @@ -409,7 +398,7 @@ public void setDoublePrecision(String precision) { @Override public String getSystemPrecision() { - return this.systemPrecision; + return systemPrecision; } @Override @@ -418,7 +407,7 @@ public void setSystemPrecision(String precision) { } public String getFailUnexpected() { - return this.failUnexpected; + return failUnexpected; } public void setFailUnexpected(String value) @@ -428,7 +417,7 @@ public void setFailUnexpected(String value) @Override public String getStaticType() { - return this.staticType; + return staticType; } @Override @@ -438,7 +427,7 @@ public void setStaticType(String type) { @Override public Value getStaticValue() { - return this.staticValue; + return staticValue; } @Override @@ -448,7 +437,7 @@ public void setStaticValue(Value value) { @Override public boolean getContinueOnFailed() { - return this.continueOnFailed; + return continueOnFailed; } @Override @@ -457,7 +446,7 @@ public void setContinueOnFailed(boolean b) { } public boolean getBreakPoint() { - return this.breakPoint; + return breakPoint; } public void setBreakPoint(boolean b) { @@ -466,7 +455,7 @@ public void setBreakPoint(boolean b) { @Override public boolean getAutoStart() { - return this.autoStart; + return autoStart; } @Override @@ -476,7 +465,7 @@ public void setAutoStart(boolean b) { @Override public boolean getReorderGroups() { - return this.reorderGroups; + return reorderGroups; } @Override @@ -486,7 +475,7 @@ public void setReorderGroups(boolean b) { @Override public List getHeaders() { - return this.headers; + return headers; } @Override @@ -496,7 +485,7 @@ public void setHeaders(List headers) { @Override public String getOutcome() { - return this.outcome; + return outcome; } @Override @@ -541,12 +530,12 @@ public boolean isOptional() { } @Override public void addMessageReference(String lineRef, MessageReference ref) { - this.messageReferences.put(lineRef, ref); + messageReferences.put(lineRef, ref); } @Override public Map getMessageReferences() { - return this.messageReferences; + return messageReferences; } @Override @@ -555,11 +544,11 @@ public void setMessageReferences(Map messageReferences } public void addChildAction(String column, AMLAction action) { - this.children.add(new Pair<>(column, action)); + children.add(new Pair<>(column, action)); } public List> getChildren() { - return this.children; + return children; } public Value getCondition() { @@ -581,91 +570,87 @@ public void setIncludeBlockReference(String includeBlockReference) { @Override public AMLAction clone() { - AMLAction that = new AMLAction(this.uid, this.hash); - that.actionInfo = this.actionInfo; - that.actionParameterType = this.actionParameterType; - that.addToReport = this.addToReport; - that.generateStatus = this.generateStatus; - that.autoStart = this.autoStart; - that.checkGroupsOrder = this.checkGroupsOrder; - that.checkPoint = this.checkPoint; - that.children.addAll(this.children); - that.condition = this.condition != null ? this.condition.clone() : null; - that.continueOnFailed = this.continueOnFailed; - - for (String s : this.definedColumns) { - that.definedColumns.add(s); - } - - that.dictionaryURI = this.dictionaryURI; - that.dependencies = this.dependencies; - that.description = this.description; - that.executionMode = this.executionMode; - that.actionURI = this.actionURI; - that.failUnexpected = this.failUnexpected; - that.headers = this.headers; - that.id = this.id; - that.includeBlockReference = this.includeBlockReference; - that.isLastOutcome = this.isLastOutcome; - that.isGroupFinished = this.isGroupFinished; - that.line = this.line; - that.messageCount = this.messageCount; - that.messageTypeColumn = this.messageTypeColumn; - that.outcome = this.outcome; - that.outcomeGroup = this.outcomeGroup; - that.outcomeName = this.outcomeName; - - for(Entry entry : this.parameters.entrySet()) { + AMLAction that = new AMLAction(uid, hash); + that.actionInfo = actionInfo; + that.actionParameterType = actionParameterType; + that.addToReport = addToReport; + that.generateStatus = generateStatus; + that.autoStart = autoStart; + that.checkGroupsOrder = checkGroupsOrder; + that.checkPoint = checkPoint; + that.children.addAll(children); + that.condition = condition != null ? condition.clone() : null; + that.continueOnFailed = continueOnFailed; + that.definedColumns.addAll(definedColumns); + that.dictionaryURI = dictionaryURI; + that.dependencies = dependencies; + that.description = description; + that.executionMode = executionMode; + that.actionURI = actionURI; + that.failUnexpected = failUnexpected; + that.headers = headers; + that.id = id; + that.includeBlockReference = includeBlockReference; + that.isLastOutcome = isLastOutcome; + that.isGroupFinished = isGroupFinished; + that.line = line; + that.messageCount = messageCount; + that.messageTypeColumn = messageTypeColumn; + that.outcome = outcome; + that.outcomeGroup = outcomeGroup; + that.outcomeName = outcomeName; + + for(Entry entry : parameters.entrySet()) { that.parameters.put(entry.getKey(), entry.getValue().clone()); } - that.reference = this.reference; - that.referenceToFilter = this.referenceToFilter; - that.reorderGroups = this.reorderGroups; + that.reference = reference; + that.referenceToFilter = referenceToFilter; + that.reorderGroups = reorderGroups; - for (Entry entry : this.messageReferences.entrySet()) { + for(Entry entry : messageReferences.entrySet()) { that.messageReferences.put(entry.getKey(), new MessageReference(entry.getValue().getAccessor(), entry.getValue().getDefinition())); } - for(Entry entry : this.serviceFields.entrySet()) { + for(Entry entry : serviceFields.entrySet()) { that.serviceFields.put(entry.getKey(), entry.getValue().clone()); } - that.serviceName = this.serviceName; + that.serviceName = serviceName; - for(Pair entry : this.setters) { + for(Pair entry : setters) { that.setters.add(new Pair<>(entry.getFirst(), entry.getSecond())); } - that.staticType = this.staticType; - that.staticValue = this.staticValue != null ? this.staticValue.clone() : null; - that.tag = this.tag; - that.template = this.template; - that.timeout = this.timeout != null ? this.timeout.clone() : null; + that.staticType = staticType; + that.staticValue = staticValue != null ? staticValue.clone() : null; + that.tag = tag; + that.template = template; + that.timeout = timeout != null ? timeout.clone() : null; - that.doublePrecision = this.doublePrecision; - that.systemPrecision = this.systemPrecision; + that.doublePrecision = doublePrecision; + that.systemPrecision = systemPrecision; - for(Entry entry : this.definedServiceFields.entrySet()) { + for(Entry entry : definedServiceFields.entrySet()) { that.definedServiceFields.put(entry.getKey(), entry.getValue()); } - that.breakPoint = this.breakPoint; - that.staticAction = this.staticAction; + that.breakPoint = breakPoint; + that.staticAction = staticAction; - that.verificationsOrder = this.verificationsOrder; + that.verificationsOrder = verificationsOrder; return that; } public void clear() { - this.definedColumns.clear(); - this.headers.clear(); - this.parameters.clear(); - this.serviceFields.clear(); - this.setters.clear(); - this.messageReferences.clear(); - this.children.clear(); + definedColumns.clear(); + headers.clear(); + parameters.clear(); + serviceFields.clear(); + setters.clear(); + messageReferences.clear(); + children.clear(); this.headers = null; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockBrace.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockBrace.java index 99d53046..7041fef5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockBrace.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockBrace.java @@ -54,7 +54,7 @@ public enum AMLBlockBrace { } public String getName() { - return this.blockBrace; + return blockBrace; } public boolean isStart() { @@ -112,6 +112,6 @@ public AMLBlockBrace getInversed() { @Override public String toString() { - return this.blockBrace; + return blockBrace; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockProcessor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockProcessor.java index 1c96a1d5..ed273fc0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockProcessor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockProcessor.java @@ -206,7 +206,7 @@ private static void insertIncludeBlocks(AMLTestCase block, List blo for(int i = 0; i < actionsSize; i++) { AMLAction action = actions.get(i); - if(JavaStatement.INCLUDE_BLOCK == JavaStatement.value(action.getActionURI())) { + if(JavaStatement.value(action.getActionURI()) == JavaStatement.INCLUDE_BLOCK) { String blockRef = action.getTemplate(); if(invalidBlockReferences.contains(blockRef)) { @@ -273,7 +273,7 @@ private static Set getRecursiveBlockReferences(List blocks, private static void checkBlock(AMLTestCase block, List blocks, Stack refStack, Stack actionStack, Set recursiveBlocks, AlertCollector alertCollector) { for(AMLAction a : block.getActions()) { - if(JavaStatement.INCLUDE_BLOCK == JavaStatement.value(a.getActionURI())) { + if(JavaStatement.value(a.getActionURI()) == JavaStatement.INCLUDE_BLOCK) { String blockReference = a.getTemplate(); AMLTestCase refBlock = getBlockByReference(blockReference, blocks); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockType.java index 726409b2..64a68a68 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLBlockType.java @@ -28,7 +28,7 @@ public enum AMLBlockType { private final AMLBlockBrace openingBrace; private final AMLBlockBrace closingBrace; - private AMLBlockType(String name, AMLBlockBrace openingBrace, AMLBlockBrace closingBrace) { + AMLBlockType(String name, AMLBlockBrace openingBrace, AMLBlockBrace closingBrace) { this.name = name; this.openingBrace = openingBrace; this.closingBrace = closingBrace; @@ -47,11 +47,7 @@ public AMLBlockBrace getClosingBrace() { } public static AMLBlockType value(String value) { - if(value == null) { - return null; - } - - return value(AMLBlockBrace.value(value)); + return value == null ? null : value(AMLBlockBrace.value(value)); } public static AMLBlockType value(AMLBlockBrace blockBrace) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLException.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLException.java index ca21bd55..9fb08c35 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLException.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLException.java @@ -32,8 +32,7 @@ public class AMLException extends Exception { public AMLException() { - super(); - } + } public AMLException(String message) { @@ -61,6 +60,6 @@ public AMLException(String message, Throwable cause, AlertCollector alertCollect } public AlertCollector getAlertCollector() { - return this.alertCollector; + return alertCollector; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLLangUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLLangUtil.java index ec74f2c8..c55bf6bc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLLangUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLLangUtil.java @@ -16,7 +16,13 @@ package com.exactpro.sf.aml; import static com.exactpro.sf.aml.AMLLangConst.BEGIN_FUNCTION; +import static com.exactpro.sf.aml.AMLLangConst.BEGIN_REFERENCE; +import static com.exactpro.sf.aml.AMLLangConst.BEGIN_STATIC; import static com.exactpro.sf.aml.AMLLangConst.END_FUNCTION; +import static com.exactpro.sf.aml.AMLLangConst.END_REFERENCE; +import static com.exactpro.sf.aml.AMLLangConst.END_STATIC; +import static com.exactpro.sf.aml.AMLLangConst.NO; +import static com.exactpro.sf.aml.AMLLangConst.OPTIONAL; import java.util.ArrayDeque; import java.util.ArrayList; @@ -55,11 +61,11 @@ public static List findExpressions(String value) { Deque stack = new ArrayDeque<>(); for(int i = 0; i < value.length(); i++) { - if(value.startsWith(AMLLangConst.BEGIN_FUNCTION, i)) { + if(value.startsWith(BEGIN_FUNCTION, i)) { stack.push(i); - } else if(value.startsWith(AMLLangConst.BEGIN_REFERENCE, i)) { + } else if(value.startsWith(BEGIN_REFERENCE, i)) { stack.push(i); - } else if(value.startsWith(AMLLangConst.BEGIN_STATIC, i)) { + } else if(value.startsWith(BEGIN_STATIC, i)) { stack.push(i); } else if(value.charAt(i) == '}' && !stack.isEmpty()) { expressions.add(value.substring(stack.pop(), i + 1)); @@ -74,8 +80,8 @@ public static String[] findReferences(String value) { List expressions = findExpressions(value); for(String expression : expressions) { - if(expression.startsWith(AMLLangConst.BEGIN_REFERENCE)) { - String ref = expression.substring(AMLLangConst.BEGIN_REFERENCE.length(), expression.length() - 1).replaceAll("\\[.*?\\]", ""); + if(expression.startsWith(BEGIN_REFERENCE)) { + String ref = expression.substring(BEGIN_REFERENCE.length(), expression.length() - 1).replaceAll("\\[.*?\\]", ""); String[] refParts = ref.split("[:.]"); Boolean isValid = refParts.length > 0; @@ -105,18 +111,15 @@ public static String[] getReferences(String value) throws AMLException { public static String[] getValues(String value) { String body = value.substring(1, value.length() - 1).trim(); - if (body.isEmpty()) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - return body.split("\\s*,\\s*"); + return body.isEmpty() ? ArrayUtils.EMPTY_STRING_ARRAY : body.split("\\s*,\\s*"); } public static String getReference(String value) { - return StringUtils.substringBetween(value, AMLLangConst.BEGIN_REFERENCE, AMLLangConst.END_REFERENCE); + return StringUtils.substringBetween(value, BEGIN_REFERENCE, END_REFERENCE); } public static String getStaticVariableName(String value) { - return StringUtils.substringBetween(value, AMLLangConst.BEGIN_STATIC, AMLLangConst.END_STATIC); + return StringUtils.substringBetween(value, BEGIN_STATIC, END_STATIC); } public static boolean isSubmessage(String value) { @@ -136,11 +139,11 @@ public static boolean isString(String value) { } public static boolean isReference(String value) { - return value.startsWith(AMLLangConst.BEGIN_REFERENCE) && value.endsWith(AMLLangConst.END_REFERENCE); + return value.startsWith(BEGIN_REFERENCE) && value.endsWith(END_REFERENCE); } public static boolean isStaticVariableReference(String value) { - return value.startsWith(AMLLangConst.BEGIN_STATIC) && value.endsWith(AMLLangConst.END_STATIC); + return value.startsWith(BEGIN_STATIC) && value.endsWith(END_STATIC); } public static boolean isFunction(String value) { @@ -149,9 +152,6 @@ public static boolean isFunction(String value) { public static boolean isExecutable(String value, boolean skipOptional) { //FIXME: validate value? - if (AMLLangConst.OPTIONAL.equalsIgnoreCase(value)) { - return !skipOptional; - } - return !AMLLangConst.NO.equalsIgnoreCase(value); + return OPTIONAL.equalsIgnoreCase(value) ? !skipOptional : !NO.equalsIgnoreCase(value); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLList.java deleted file mode 100644 index 72b77d01..00000000 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLList.java +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************** - * Copyright 2009-2018 Exactpro (Exactpro Systems Limited) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ******************************************************************************/ -package com.exactpro.sf.aml; - -import java.util.ArrayList; - -import com.exactpro.sf.common.util.EPSCommonException; - -public class AMLList extends ArrayList { - - boolean THROW = false; - - /** - * - */ - private static final long serialVersionUID = -5260897237446841671L; - - @Override - public boolean add(T e) { - if (THROW) - throw new EPSCommonException(e.toString()); - return super.add(e); - } -} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLMatrixWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLMatrixWrapper.java index 03dcb056..f3ca2fa9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLMatrixWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLMatrixWrapper.java @@ -63,7 +63,7 @@ public AMLMatrixWrapper(AMLMatrix matrix, boolean onlyExecutable) throws AMLExce blocks.get(AMLBlockType.LastBlock)); for(AMLBlock block : blocksIterable) { - if(AMLBlockType.GlobalBlock != AMLBlockType.value(block.getValue(Column.Action))) { + if(AMLBlockType.value(block.getValue(Column.Action)) != AMLBlockType.GlobalBlock) { staticVariables.putAll(block, currentVariables); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLPrivateActions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLPrivateActions.java index 5447d3d9..75978490 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLPrivateActions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLPrivateActions.java @@ -95,7 +95,7 @@ public static void CheckUnexpectedMessages(ScriptContext context) { StringBuilder builder = new StringBuilder(); for (Object msg:unexpectedMessages){ builder.append("Message=["); - builder.append(msg.toString()); + builder.append(msg); builder.append("]"); builder.append("\t"); } @@ -108,11 +108,7 @@ public static void CheckUnexpectedMessages(ScriptContext context) { private static Set prepare(Set receivedFromWaitActions) { Set preparedMessage = new HashSet<>(); for(Object o:receivedFromWaitActions){ - if(o instanceof BaseMessage){ - preparedMessage.add(((BaseMessage) o).getMessage()); - } else { - preparedMessage.add(o); - } + preparedMessage.add(o instanceof BaseMessage ? ((BaseMessage)o).getMessage() : o); } return preparedMessage; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLSettings.java index 53e34d27..89aef140 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLSettings.java @@ -19,6 +19,7 @@ import java.util.List; import java.util.Map; +import com.exactpro.sf.aml.IOutputStreamFactory.DefaultOutputStreamFactory; import com.exactpro.sf.configuration.suri.SailfishURI; /** @@ -39,16 +40,14 @@ public class AMLSettings { private boolean autoRun; private boolean runNetDumper; private boolean skipOptional; - private List validators; - private List preprocessors; - private boolean suppressAskForContinue = false; - private IOutputStreamFactory outputStreamFactory = new IOutputStreamFactory.DefaultOutputStreamFactory(); + private final List validators = new ArrayList<>(); + private final List preprocessors = new ArrayList<>(); + private boolean suppressAskForContinue; + private IOutputStreamFactory outputStreamFactory = new DefaultOutputStreamFactory(); private Map staticVariables; public AMLSettings() { - this.validators = new ArrayList(); - this.preprocessors = new ArrayList(); - } + } /** * Set project directory. @@ -121,7 +120,7 @@ public void setSrcDir(String srcDir) { * @return */ public String getSrcDir() { - return this.srcDir; + return srcDir; } /** @@ -150,7 +149,7 @@ public void setTestCasesRange(String range) * @return String representation of number test cases to be executed */ public String getTestCasesRange() { - return this.testCasesRange; + return testCasesRange; } public void setContinueOnFailed(boolean b) { @@ -158,7 +157,7 @@ public void setContinueOnFailed(boolean b) { } public boolean getContinueOnFailed() { - return this.continueOnFailed; + return continueOnFailed; } public void setAutoStart(boolean b) { @@ -166,7 +165,7 @@ public void setAutoStart(boolean b) { } public boolean getAutoStart() { - return this.autoStart; + return autoStart; } public void setAutoRun(boolean b) { @@ -174,7 +173,7 @@ public void setAutoRun(boolean b) { } public boolean getAutoRun() { - return this.autoRun; + return autoRun; } /** @@ -182,7 +181,7 @@ public boolean getAutoRun() { * @return Language name */ public SailfishURI getLanguageURI() { - return this.languageURI; + return languageURI; } public void setLanguageURI(SailfishURI languageURI) { @@ -190,16 +189,16 @@ public void setLanguageURI(SailfishURI languageURI) { } public void addValidator(IValidator validator) { - this.validators.add(validator); + validators.add(validator); } public List getValidators() { - return this.validators; + return validators; } public void addPreprocessor(IPreprocessor preprocessor) { - this.preprocessors.add(preprocessor); + preprocessors.add(preprocessor); } public List getPreprocessors() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLTestCase.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLTestCase.java index f593fabd..d27ddaf4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLTestCase.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/AMLTestCase.java @@ -17,16 +17,14 @@ import java.io.Serializable; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; -import com.exactpro.sf.common.util.StringUtil; -import com.exactpro.sf.aml.reader.struct.ExecutionMode; -import com.exactpro.sf.embedded.statistics.StatisticsService; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import org.apache.commons.lang3.StringUtils; + +import com.exactpro.sf.aml.reader.struct.ExecutionMode; +import com.exactpro.sf.embedded.statistics.StatisticsService; /** * Represent a single test case from matrix. @@ -36,27 +34,23 @@ @SuppressWarnings("serial") public class AMLTestCase implements ITestCase, Cloneable, Serializable { - private List actions; + private final List actions = new ArrayList<>(); private String reference; private long line; private String id; - private ExecutionMode executionMode; + private ExecutionMode executionMode = ExecutionMode.EXECUTABLE; private String description = ""; private int execOrder; private int matrixOrder; - private boolean failOnUnexpectedMessage = false; + private boolean failOnUnexpectedMessage; private boolean addToReport = true; - private AMLBlockType blockType; + private AMLBlockType blockType = AMLBlockType.TestCase; private final long uid; private final int hash; public AMLTestCase(String id, long uid, int hash) { this.id = id; - this.actions = new ArrayList<>(); - // good defaults: - this.executionMode = ExecutionMode.EXECUTABLE; - this.blockType = AMLBlockType.TestCase; - this.uid = uid; + this.uid = uid; this.hash = hash; } @@ -80,17 +74,17 @@ public void addAction(int index, AMLAction action) throws AMLException { } } } finally { - this.actions.add(index, action); + actions.add(index, action); } } public void addAction(AMLAction action) throws AMLException{ - addAction(this.actions.size(), action); + addAction(actions.size(), action); } @Override public List getActions() { - return this.actions; + return actions; } @Override @@ -110,11 +104,11 @@ public boolean hasReference() { @Override public AMLAction getAction(int i) { - return this.actions.get(i); + return actions.get(i); } public void removeAction(int i) { - this.actions.remove(i); + actions.remove(i); } public void addAllActions(int i, List actions) { @@ -122,7 +116,7 @@ public void addAllActions(int i, List actions) { } public long getLine() { - return this.line; + return line; } public void setLine(long line) { @@ -131,7 +125,7 @@ public void setLine(long line) { @Override public String getDescription() { - return this.description; + return description; } @Override @@ -147,7 +141,7 @@ public void setDescription(String description) { @Override public AMLAction findActionByRef(String lineRef) { - for(AMLAction action : this.actions) { + for(AMLAction action : actions) { if((action.getExecutionMode() == ExecutionMode.EXECUTABLE || action.getExecutionMode() == ExecutionMode.OPTIONAL) && (lineRef.equals(action.getReference()) || lineRef.equals(action.getReferenceToFilter()))) { @@ -175,11 +169,11 @@ public void setExecutionMode(ExecutionMode executionMode) { @Override public ExecutionMode getExecutionMode() { - return this.executionMode; + return executionMode; } public boolean isEmpty() { - return this.actions.size() == 0; + return actions.isEmpty(); } public void setExecOrder(int order) { @@ -199,7 +193,7 @@ public void setMatrixOrder(int matrixOrder) { } public void clear() { - for (AMLAction a : this.actions) { + for(AMLAction a : actions) { a.clear(); } } @@ -259,19 +253,19 @@ public String getTagsAsString() { @Override public AMLTestCase clone() { - AMLTestCase that = new AMLTestCase(this.id, this.uid, this.hash); + AMLTestCase that = new AMLTestCase(id, uid, hash); - for (AMLAction a : this.actions) { + for(AMLAction a : actions) { that.actions.add(a.clone()); } - that.reference = this.reference; - that.line = this.line; - that.description = this.description; - that.executionMode = this.executionMode; - that.execOrder = this.execOrder; - that.matrixOrder = this.matrixOrder; - that.blockType = this.blockType; - that.addToReport = this.addToReport; + that.reference = reference; + that.line = line; + that.description = description; + that.executionMode = executionMode; + that.execOrder = execOrder; + that.matrixOrder = matrixOrder; + that.blockType = blockType; + that.addToReport = addToReport; return that; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/DictionarySettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/DictionarySettings.java index 0f2087b2..47e6979b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/DictionarySettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/DictionarySettings.java @@ -28,17 +28,15 @@ public class DictionarySettings implements Serializable { private SailfishURI uri; private Class factoryClass; - private Set utilityClassURIs; + private final Set utilityClassURIs = new HashSet<>(); - public DictionarySettings() { - this.utilityClassURIs = new HashSet<>(); - } + public DictionarySettings() { + } public DictionarySettings(DictionarySettings settings) { this.uri = settings.uri; this.factoryClass = settings.factoryClass; - this.utilityClassURIs = new HashSet<>(); - } + } public void addUtilityClassURI(SailfishURI uri) { utilityClassURIs.add(uri); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/ICodeGenerator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/ICodeGenerator.java index c21713fd..72b22689 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/ICodeGenerator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/ICodeGenerator.java @@ -37,14 +37,15 @@ */ public interface ICodeGenerator { - public abstract GeneratedScript generateCode(List testCases, List beforeTCBlocks, List afterTCBlocks) + GeneratedScript generateCode(List testCases, List beforeTCBlocks, List afterTCBlocks) throws AMLException, IOException, InterruptedException; - public abstract AlertCollector getAlertCollector(); + AlertCollector getAlertCollector(); - public abstract void cleanup(); + void cleanup(); - public abstract void init(IWorkspaceDispatcher workspaceDispatcher, IAdapterManager adapterManager, IEnvironmentManager environment, IDictionaryManager dictionaryManager, IStaticServiceManager staticServiceManager, IActionManager actionManager, IUtilityManager utilityManager, ScriptContext scriptContext, AMLSettings amlSettings, List progressListeners, String compilerClassPath) throws AMLException; + void init(IWorkspaceDispatcher workspaceDispatcher, IAdapterManager adapterManager, IEnvironmentManager environment, IDictionaryManager dictionaryManager, IStaticServiceManager staticServiceManager, IActionManager actionManager, + IUtilityManager utilityManager, ScriptContext scriptContext, AMLSettings amlSettings, List progressListeners, String compilerClassPath) throws AMLException; - public abstract ScriptContext getScriptContext(); + ScriptContext getScriptContext(); } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IOutputStreamFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IOutputStreamFactory.java index 89e53889..65badbfc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IOutputStreamFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IOutputStreamFactory.java @@ -28,7 +28,7 @@ public interface IOutputStreamFactory { OutputStream createOutputStream(String streamName) throws IOException; /* file name */ OutputStream createOutputStream(File file) throws IOException; - public static class DefaultOutputStreamFactory implements IOutputStreamFactory { + class DefaultOutputStreamFactory implements IOutputStreamFactory { @Override public OutputStream createOutputStream(String fileName) throws IOException { @@ -42,7 +42,7 @@ public OutputStream createOutputStream(File file) throws IOException { } - public static class NullOutputStreamFactory implements IOutputStreamFactory { + class NullOutputStreamFactory implements IOutputStreamFactory { @Override public OutputStream createOutputStream(String streamName) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IValidator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IValidator.java index 91ee7a9d..67bfa5c2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IValidator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/IValidator.java @@ -22,7 +22,7 @@ public interface IValidator { - public boolean validate(AMLMatrix matrix, IActionManager actionManager, SailfishURI language, AlertCollector alertCollector) throws AMLException; + boolean validate(AMLMatrix matrix, IActionManager actionManager, SailfishURI language, AlertCollector alertCollector) throws AMLException; - public String getName(); + String getName(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/JsonAML.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/JsonAML.java index c190f1d2..860356e1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/JsonAML.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/JsonAML.java @@ -16,6 +16,7 @@ package com.exactpro.sf.aml; import java.io.IOException; +import java.util.Objects; import com.exactpro.sf.aml.generator.GeneratedScript; import com.exactpro.sf.aml.iomatrix.AdvancedMatrixReader; @@ -32,7 +33,7 @@ public class JsonAML extends AML { - private AMLMatrix amlMatrix; + private final AMLMatrix amlMatrix; public JsonAML(AMLSettings settings, IWorkspaceDispatcher workspaceDispatcher, IAdapterManager adapterManager, IEnvironmentManager environmentManager, IDictionaryManager dictionaryManager, @@ -40,9 +41,7 @@ public JsonAML(AMLSettings settings, IWorkspaceDispatcher workspaceDispatcher, I IUtilityManager utilityManager, String compilerClassPath, AMLMatrix matrix) throws AMLException { super(settings, workspaceDispatcher, adapterManager, environmentManager, dictionaryManager, staticServiceManager, languageManager, actionManager, utilityManager, compilerClassPath); - if (matrix == null) - throw new NullPointerException("matrix can't be null"); - this.amlMatrix = matrix; + this.amlMatrix = Objects.requireNonNull(matrix, "matrix can't be null"); } @Override @@ -53,6 +52,6 @@ protected AdvancedMatrixReader initReader(String file, String fileEncoding) thro @Override public GeneratedScript run(ScriptContext scriptContext, String fileEncoding) throws AMLException, IOException, InterruptedException { - return super.run(scriptContext, amlMatrix); + return run(scriptContext, amlMatrix); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/MessageReference.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/MessageReference.java index 8a0896f6..5f4da654 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/MessageReference.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/MessageReference.java @@ -20,8 +20,8 @@ @SuppressWarnings("serial") public class MessageReference implements Serializable { - private String accessor; - private String definition; + private final String accessor; + private final String definition; public MessageReference(String accessor, String definition) { @@ -30,10 +30,10 @@ public MessageReference(String accessor, String definition) } public String getAccessor() { - return this.accessor; + return accessor; } public String getDefinition() { - return this.definition; + return definition; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/ConversionMonitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/ConversionMonitor.java index 594c2154..860f0ed1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/ConversionMonitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/ConversionMonitor.java @@ -22,7 +22,7 @@ public class ConversionMonitor { private final Set errors = new HashSet<>(); - private volatile int progress = 0; + private volatile int progress; public int getProgress() { return progress; @@ -33,8 +33,8 @@ public void setProgress(int progress) { } public void addError(String error) { - synchronized (this.errors) { - this.errors.add(error); + synchronized(errors) { + errors.add(error); } } @@ -45,8 +45,8 @@ public void addErrors(Collection errors) { } public Set getErrors() { - synchronized (this.errors) { - return Collections.unmodifiableSet(this.errors); + synchronized(errors) { + return Collections.unmodifiableSet(errors); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/IMatrixConverterSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/IMatrixConverterSettings.java index 8a351184..f7ef6d8b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/IMatrixConverterSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/IMatrixConverterSettings.java @@ -20,12 +20,12 @@ import com.exactpro.sf.common.util.ICommonSettings; public interface IMatrixConverterSettings extends ICommonSettings { - public File getInputFile(); - public void setInputFile(File inputFile); + File getInputFile(); + void setInputFile(File inputFile); - public File getOutputFile(); - public void setOutputFile(File outputFile); + File getOutputFile(); + void setOutputFile(File outputFile); - public String getEnvironment(); - public void setEnvironment(String environment); + String getEnvironment(); + void setEnvironment(String environment); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterContext.java index 97dec92c..e3cb288b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterContext.java @@ -37,18 +37,18 @@ public MatrixConverterContext(IWorkspaceDispatcher workspaceDispatcher, IDiction @Override public IWorkspaceDispatcher getWorkspaceDispatcher() { - return this.workspaceDispatcher; + return workspaceDispatcher; } @Override public IDictionaryManager getDictionaryManager() { - return this.dictionaryManager; + return dictionaryManager; } @Override public boolean isServiceExists(String environment, String service) { ServiceName serviceName = new ServiceName(environment, service); - return this.connectionManager.getService(serviceName) != null; + return connectionManager.getService(serviceName) != null; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterLoader.java index e3b8ee10..9280b85b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterLoader.java @@ -70,8 +70,8 @@ public void load(ILoadableManagerContext context) throws Exception { for (String alias : classAliases) { SailfishURI converterURI = new SailfishURI(version.getAlias(), null, alias); - this.uriToClass.put(converterURI, converterClass); - this.uriToSettingsClass.put(converterURI, settingsClass); + uriToClass.put(converterURI, converterClass); + uriToSettingsClass.put(converterURI, settingsClass); } logger.info("MatrixConverter {} has been loaded", converterClass.getCanonicalName()); @@ -85,7 +85,7 @@ public void load(ILoadableManagerContext context) throws Exception { public void finalize(ILoadableManagerContext context) throws Exception { } public MatrixConverterManager create(IWorkspaceDispatcher workspaceDispatcher, IDictionaryManager dictionaryManager, IConnectionManager connectionManager) { - return new MatrixConverterManager(workspaceDispatcher, dictionaryManager, connectionManager, this.uriToClass, this.uriToSettingsClass); + return new MatrixConverterManager(workspaceDispatcher, dictionaryManager, connectionManager, uriToClass, uriToSettingsClass); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterManager.java index 7a062e6e..51408cd6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/converter/MatrixConverterManager.java @@ -44,7 +44,7 @@ public IMatrixConverter getMatrixConverter(SailfishURI converterURI) { try { Class clazz = SailfishURIUtils.getMatchingValue(converterURI, uriToClass, SailfishURIRule.REQUIRE_RESOURCE); IMatrixConverter converter = clazz.newInstance(); - converter.init(this.context); + converter.init(context); return converter; } catch (InstantiationException | IllegalAccessException e) { throw new EPSCommonException("Failed to initialize matrix converter" + converterURI, e); @@ -61,6 +61,6 @@ public IMatrixConverterSettings getMatrixConverterSettings(SailfishURI converter } public Set getMatrixConverters() { - return Collections.unmodifiableSet(this.uriToClass.keySet()); + return Collections.unmodifiableSet(uriToClass.keySet()); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AbstractAlert.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AbstractAlert.java index d9eb5b1b..f8aef217 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AbstractAlert.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AbstractAlert.java @@ -68,10 +68,10 @@ public boolean equals(Object o) { AbstractAlert that = (AbstractAlert)o; EqualsBuilder builder = new EqualsBuilder(); - - builder.append(this.type, that.type); - builder.append(this.column, that.column); - builder.append(this.message, that.message); + + builder.append(type, that.type); + builder.append(column, that.column); + builder.append(message, that.message); return builder.isEquals(); } @@ -79,10 +79,10 @@ public boolean equals(Object o) { @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); - - builder.append(this.type); - builder.append(this.column); - builder.append(this.message); + + builder.append(type); + builder.append(column); + builder.append(message); return builder.toHashCode(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AggregateAlert.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AggregateAlert.java index ded447bf..8fe3e5bc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AggregateAlert.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AggregateAlert.java @@ -43,7 +43,7 @@ protected AggregateAlert(Set lines, Set uids, String column, String } public String joinLines() { - return join(this.lines.stream()); + return join(lines.stream()); } public Set getLines() { @@ -57,17 +57,17 @@ public Set getUids() { @Override public String toString() { StringBuilder builder = new StringBuilder(); - if (this.lines.size() > 1) { + if(lines.size() > 1) { builder.append("Multiple ") - .append(this.type.getCapitalized()) + .append(type.getCapitalized()) .append(" in lines '").append(joinLines()).append('\''); } else { - builder.append(this.type.getCapitalized()) + builder.append(type.getCapitalized()) .append(" in line ").append(joinLines()); } - builder.append(" column '").append(this.column).append('\'') - .append(": ").append(this.message); + builder.append(" column '").append(column).append('\'') + .append(": ").append(message); return builder.toString(); } @@ -95,18 +95,18 @@ public AggregateAlert build() { } public AlertBuilder process(AbstractAlert alert) { - return this.setColumn(alert.column) + return setColumn(alert.column) .setMessage(alert.message) .setType(alert.type); } public AlertBuilder addLine(Long line) { - this.lines.add(Objects.requireNonNull(line, "Line number can't be empty")); + lines.add(Objects.requireNonNull(line, "Line number can't be empty")); return this; } public AlertBuilder addUid(Long uid) { - this.uids.add(Objects.requireNonNull(uid, "Unique identifier can't be empty")); + uids.add(Objects.requireNonNull(uid, "Unique identifier can't be empty")); return this; } @@ -127,7 +127,7 @@ public AlertBuilder setMessage(String message) { } public AlertBuilder setType(AlertType type) { - if (this.type != null && !this.type.equals(type)) { + if(this.type != null && this.type != type) { throw new IllegalArgumentException("New value '" + type + "' is not equals with current '" + this.type + "'"); } this.type = type; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/Alert.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/Alert.java index 18950f03..11e8d9cf 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/Alert.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/Alert.java @@ -120,9 +120,9 @@ public boolean equals(Object o) { Alert that = (Alert)o; EqualsBuilder builder = new EqualsBuilder(); - - builder.append(this.line, that.line); - builder.append(this.reference, that.reference); + + builder.append(line, that.line); + builder.append(reference, that.reference); return builder.isEquals(); } @@ -132,25 +132,25 @@ public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); builder.append(super.hashCode()); - builder.append(this.line); - builder.append(this.reference); + builder.append(line); + builder.append(reference); return builder.toHashCode(); } @Override public String toString() { - StringBuilder builder = new StringBuilder(this.type.getCapitalized()); - if (this.line != -1) { - builder.append(" in line ").append(this.line); + StringBuilder builder = new StringBuilder(type.getCapitalized()); + if(line != -1) { + builder.append(" in line ").append(line); } - if (StringUtils.isNotBlank(this.reference)) { - builder.append(" reference '").append(this.reference).append('\''); + if(StringUtils.isNotBlank(reference)) { + builder.append(" reference '").append(reference).append('\''); } - if (StringUtils.isNotBlank(this.column)) { - builder.append(" column '").append(this.column).append('\''); + if(StringUtils.isNotBlank(column)) { + builder.append(" column '").append(column).append('\''); } - builder.append(": ").append(this.message); + builder.append(": ").append(message); return builder.toString(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertCollector.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertCollector.java index fa1aafdc..10e209c5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertCollector.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertCollector.java @@ -76,15 +76,11 @@ public void add(Stream alerts) { } public void add(AlertCollector alertCollector) { - this.alerts.putAll(alertCollector.alerts); + alerts.putAll(alertCollector.alerts); } public Collection getAlerts(AlertType type) { - if (type != null) { - return this.alerts.get(type); - } - - return this.alerts.values(); + return type != null ? alerts.get(type) : alerts.values(); } public Collection getAlerts() { @@ -92,11 +88,7 @@ public Collection getAlerts() { } public int getCount(AlertType type) { - if (type != null) { - return this.alerts.get(type).size(); - } - - return this.alerts.values().size(); + return type != null ? alerts.get(type).size() : alerts.values().size(); } public int getCount() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertType.java index e56b1106..99e30de6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/AlertType.java @@ -22,9 +22,9 @@ public enum AlertType { WARNING; private final String capitalized; - - private AlertType() { - this.capitalized = StringUtils.capitalize(this.toString().toLowerCase()); + + AlertType() { + this.capitalized = StringUtils.capitalize(toString().toLowerCase()); } public String getCapitalized() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/GeneratedScript.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/GeneratedScript.java index 424db581..65135f27 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/GeneratedScript.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/GeneratedScript.java @@ -22,7 +22,7 @@ public class GeneratedScript { private File mainFile; - private List files; + private final List files; public GeneratedScript() { @@ -38,11 +38,11 @@ public void setMainFile(File file) { } public void addFile(File file) { - this.files.add(file); + files.add(file); } public List getFilesList() { - return this.files; + return files; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/IGetterSetterGenerator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/IGetterSetterGenerator.java index 168bbee6..3de0667d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/IGetterSetterGenerator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/IGetterSetterGenerator.java @@ -56,7 +56,7 @@ public interface IGetterSetterGenerator { * @param source for getting. * @return generated code for extracting value */ - public String getGetter(Class type, String parameterName, String source) throws AMLException; + String getGetter(Class type, String parameterName, String source) throws AMLException; ///** // * Find getter method in type class for parameter with @@ -103,7 +103,7 @@ public interface IGetterSetterGenerator { * false otherwise * @return generated code for setting value */ - public String getSetter(Class type, String parameterName, String value, boolean isReference) throws AMLException; + String getSetter(Class type, String parameterName, String value, boolean isReference) throws AMLException; ///** // * Find setter method in type class for parameter with @@ -131,7 +131,7 @@ public interface IGetterSetterGenerator { * @param paramClass parameter class (optional) * @return generated code for adding submessage or {@code null} if submessage not exists */ - public String addSubmessage(Class type, String parameterName, String value, Class paramClass) throws AMLException; + String addSubmessage(Class type, String parameterName, String value, Class paramClass) throws AMLException; /** * Find submessage class with name childClassName @@ -141,7 +141,7 @@ public interface IGetterSetterGenerator { * @param paramClass parameter class (optional) * @return submessage class or {@code null} if submessage not exists */ - public Class getSubmessageClass (Class type, String childClassName, Class paramClass) throws AMLException; + Class getSubmessageClass(Class type, String childClassName, Class paramClass) throws AMLException; // /** // * Find setter method in message class. @@ -159,5 +159,5 @@ public interface IGetterSetterGenerator { * for converting to tree using SimpleTreeEntity. * @return */ - public String getMethodForExtractingTreeEntity() throws AMLException; + String getMethodForExtractingTreeEntity() throws AMLException; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/JavaValidator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/JavaValidator.java index 40385756..a6543737 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/JavaValidator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/JavaValidator.java @@ -17,21 +17,17 @@ import java.util.Arrays; +import javax.lang.model.SourceVersion; + +import org.apache.commons.lang3.StringUtils; + /** * Collection of validations for Java language. * @author dmitry.guriev * */ public class JavaValidator { - - private static final String keywords[] = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", - "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", - "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", - "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", - "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", - "volatile", "while" }; - - private JavaValidator() + private JavaValidator() { // hide constructor } @@ -58,8 +54,8 @@ public static String validateTypeName(String typeName) if (typeName.contains("\t")) { return "Type '"+typeName+"' contain tab character"; } - - if (Arrays.binarySearch(keywords, typeName) >= 0) { + + if(SourceVersion.isKeyword(typeName)) { return "Type '"+typeName+"' is reserved java word"; } @@ -67,11 +63,11 @@ public static String validateTypeName(String typeName) for (int i=0; i= '0' && b <= '9') || (b >= 'a' && b <= 'z') - || (b >= 'A' && b <= 'Z')); - if (false == valid) { + || (b >= 'A' && b <= 'Z'); + if(!valid) { return "Type '"+typeName+"' contain invalid character"; } } @@ -105,8 +101,8 @@ public static String validateFunctionName(String function) if (function.contains("\t")) { return "Function '"+function+"' contain tab character"; } - - if (Arrays.binarySearch(keywords, function) >= 0) { + + if(SourceVersion.isKeyword(function)) { return "Function '"+function+"' is reserved java word"; } @@ -114,11 +110,11 @@ public static String validateFunctionName(String function) for (int i=0; i= '0' && b <= '9') || (b >= 'a' && b <= 'z') - || (b >= 'A' && b <= 'Z')); - if (false == valid) { + || (b >= 'A' && b <= 'Z'); + if(!valid) { return "Function '"+function+"' contain invalid character"; } } @@ -152,7 +148,7 @@ public static String validateVariableName(String variable) return "Variable '"+variable+"' contain tab character"; } - if (Arrays.binarySearch(keywords, variable) >= 0) { + if(SourceVersion.isKeyword(variable)) { return "Variable '"+variable+"' is reserved java word"; } @@ -160,11 +156,11 @@ public static String validateVariableName(String variable) for (int i=0; i= '0' && b <= '9') || (b >= 'a' && b <= 'z') - || (b >= 'A' && b <= 'Z')); - if (false == valid) { + || (b >= 'A' && b <= 'Z'); + if(!valid) { return "Variable '"+variable+"' contain invalid character"; } } @@ -185,7 +181,7 @@ public static String validateVariableName(String variable) * @param packageName tested package name */ public static String validatePackageName(String packageName) { - if (packageName == null || packageName.equals("")) { + if(StringUtils.isEmpty(packageName)) { return null; } @@ -203,7 +199,7 @@ public static String validatePackageName(String packageName) { String[] parts = packageName.split("\\."); for (String part: parts) { - if (Arrays.binarySearch(keywords, part) >= 0) { + if(SourceVersion.isKeyword(part)) { return "Invalid package name. Package name '"+packageName+"' contains reserved java word '"+part+"'"; } } @@ -212,13 +208,13 @@ public static String validatePackageName(String packageName) { for (int i=0; i= '0' && b <= '9') || (b >= 'a' && b <= 'z') - || (b >= 'A' && b <= 'Z')); - if (false == valid) { + || (b >= 'A' && b <= 'Z'); + if(!valid) { return "Invalid package name. Package name '"+packageName+"' is not valid java indentifier"; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/MVELInitializer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/MVELInitializer.java index 4496eaa2..c945022d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/MVELInitializer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/MVELInitializer.java @@ -26,10 +26,15 @@ import org.mvel2.math.MathProcessor; import org.mvel2.optimizers.OptimizerFactory; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.Map; +import java.util.Objects; public class MVELInitializer { - private ParserContext ctx; + private final ParserContext ctx; private static volatile MVELInitializer singleton; private MVELInitializer() { @@ -40,12 +45,12 @@ private MVELInitializer() { PropertyHandlerFactory.registerPropertyHandler(Map.class, new MapPropertyHandler()); ctx = new ParserContext(); - ctx.addImport(java.time.LocalDateTime.class); - ctx.addImport(java.time.LocalDate.class); - ctx.addImport(java.time.LocalTime.class); - ctx.addImport(java.math.BigDecimal.class); + ctx.addImport(LocalDateTime.class); + ctx.addImport(LocalDate.class); + ctx.addImport(LocalTime.class); + ctx.addImport(BigDecimal.class); ctx.addImport(SailfishURI.class); - ctx.addImport(java.util.Objects.class); + ctx.addImport(Objects.class); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/TypeConverter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/TypeConverter.java index 9ed7070c..55c9d2e0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/TypeConverter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/TypeConverter.java @@ -15,6 +15,8 @@ ******************************************************************************/ package com.exactpro.sf.aml.generator; +import static org.apache.commons.lang3.StringUtils.appendIfMissingIgnoreCase; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -39,7 +41,7 @@ */ public class TypeConverter { - private static Logger logger = LoggerFactory.getLogger(TypeConverter.class); + private static final Logger logger = LoggerFactory.getLogger(TypeConverter.class); private static final Pattern CAST_PATTERN = Pattern.compile("\\(\\s*\\w+(\\.\\w+\\s*)*\\)(?.+)"); private TypeConverter() @@ -80,7 +82,7 @@ public static String findConstant(Class type, String value, AtomicReference type, String value, AtomicReference type, String name, Class cons try { if (type.isEnum()) { - Method getValueMethod = null; - getValueMethod = type.getMethod("getValue", new Class[0]); + Method getValueMethod = type.getMethod("getValue", new Class[0]); for (Object constant : type.getEnumConstants()) { @@ -171,15 +173,14 @@ public static Object findConstantValue(Class type, String name, Class cons * otherwise - false */ public static boolean convert(Class type, AtomicReference value) { - boolean isConverted = false; - if (value!=null && value.get()!=null) { + if(value != null && value.get() != null) { String convertedValue = convert(type, value.get()); if (convertedValue != null) { value.set(convertedValue); - isConverted = true; + return true; } } - return isConverted; + return false; } /** @@ -218,18 +219,18 @@ public static String convert(Class type, String value) if (type.equals(boolean.class) || type.equals(Boolean.class)) { - if (value.equalsIgnoreCase("y") - || value.equalsIgnoreCase("yes") - || value.equalsIgnoreCase("t") - || value.equalsIgnoreCase("true") - || value.equalsIgnoreCase("1")) { + if("y".equalsIgnoreCase(value) + || "yes".equalsIgnoreCase(value) + || "t".equalsIgnoreCase(value) + || "true".equalsIgnoreCase(value) + || "1".equalsIgnoreCase(value)) { return "true"; } - if (value.equalsIgnoreCase("n") - || value.equalsIgnoreCase("no") - || value.equalsIgnoreCase("f") - || value.equalsIgnoreCase("false") - || value.equalsIgnoreCase("0")) { + if("n".equalsIgnoreCase(value) + || "no".equalsIgnoreCase(value) + || "f".equalsIgnoreCase(value) + || "false".equalsIgnoreCase(value) + || "0".equalsIgnoreCase(value)) { return "false"; } } @@ -237,34 +238,30 @@ public static String convert(Class type, String value) if (type.equals(long.class) || type.equals(Long.class)) { value = value.trim(); - - // backward capability: - if (value.startsWith("(")) // backward capability: (long) value - return value; - - if (value.endsWith("l") || value.endsWith("L")) - return "(long) " + value; - else - return "(long) " + value + "L"; - } + // backward capability: (long) value + return value.startsWith("(") ? value : appendIfMissingIgnoreCase(value, "L"); + } if (type.equals(double.class) || type.equals(Double.class)) { value = value.trim(); // backward capability: if (value.startsWith("(")) // backward capability: (float) value - return value; - - if (value.endsWith("d") || value.endsWith("D")) - return "(double) " + value; - else if (value.equalsIgnoreCase("NaN")) - return "Double.NaN"; - else if (value.equalsIgnoreCase("NEGATIVE_INFINITY")) - return "Double.NEGATIVE_INFINITY"; - else if (value.equalsIgnoreCase("POSITIVE_INFINITY")) - return "Double.POSITIVE_INFINITY"; - else - return "(double) " + value + "D"; + { + return value; + } + + if(value.endsWith("d") || value.endsWith("D")) { + return "(double) " + value; + } else if("NaN".equalsIgnoreCase(value)) { + return "Double.NaN"; + } else if("NEGATIVE_INFINITY".equalsIgnoreCase(value)) { + return "Double.NEGATIVE_INFINITY"; + } else if("POSITIVE_INFINITY".equalsIgnoreCase(value)) { + return "Double.POSITIVE_INFINITY"; + } else { + return "(double) " + value + "D"; + } } if (type.equals(float.class) || type.equals(Float.class)) { @@ -272,38 +269,36 @@ else if (value.equalsIgnoreCase("POSITIVE_INFINITY")) // backward capability: if (value.startsWith("(")) // backward capability: (float) value - return value; - - if (value.endsWith("f") || value.endsWith("F")) - return "(float) " + value; - else if (value.equalsIgnoreCase("NaN")) - return "Float.NaN"; - else if (value.equalsIgnoreCase("NEGATIVE_INFINITY")) - return "Float.NEGATIVE_INFINITY"; - else if (value.equalsIgnoreCase("POSITIVE_INFINITY")) - return "Float.POSITIVE_INFINITY"; - else - return "(float) " + value + "F"; + { + return value; + } + + if(value.endsWith("f") || value.endsWith("F")) { + return "(float) " + value; + } else if("NaN".equalsIgnoreCase(value)) { + return "Float.NaN"; + } else if("NEGATIVE_INFINITY".equalsIgnoreCase(value)) { + return "Float.NEGATIVE_INFINITY"; + } else if("POSITIVE_INFINITY".equalsIgnoreCase(value)) { + return "Float.POSITIVE_INFINITY"; + } else { + return "(float) " + value + "F"; + } } if (type.equals(byte.class) || type.equals(Byte.class)) { value = value.trim(); - // backward capability: - if (value.startsWith("(")) // backward capability: (byte) value - return value; - - return "(byte) "+value; - } + // backward capability: (byte) value + return value.startsWith("(") ? value : "(byte) " + value; + } if (type.equals(short.class) || type.equals(Short.class)) { value = value.trim(); - if (value.startsWith("(")) // backward capability: (short) value - return value; - else - return "(short) " + value; + // backward capability: (short) value + return value.startsWith("(") ? value : "(short) " + value; } if (type.equals(BigInteger.class)) @@ -311,7 +306,9 @@ else if (value.equalsIgnoreCase("POSITIVE_INFINITY")) value = value.trim(); if (value.endsWith("L") || value.endsWith("l")) // Testers adds 'L' to the number because Excel cut off all numbers bigger than 10^15 - value = value.substring(0, value.length()-1); + { + value = value.substring(0, value.length() - 1); + } return "new java.math.BigInteger(\"" + value + "\")"; } @@ -320,7 +317,9 @@ else if (value.equalsIgnoreCase("POSITIVE_INFINITY")) value = value.trim(); if (value.endsWith("B")) // Testers adds 'B' to the number because Excel cut off all numbers bigger than 10^15 + { value = value.substring(0, value.length()-1); + } return "new java.math.BigDecimal(\"" + value + "\")"; } @@ -364,7 +363,7 @@ public static String findConstByValue(Class type, String value, Class cons Method[] methods = type.getDeclaredMethods(); for (Method method : methods) { - if (method.getName().equals("getEnumValue")) { + if("getEnumValue".equals(method.getName())) { if (method.getParameterTypes().length == 1) { Matcher matcher = CAST_PATTERN.matcher(value); @@ -373,7 +372,7 @@ public static String findConstByValue(Class type, String value, Class cons } Object objArg = convertToObject(method.getParameterTypes()[0], value); Object objVal = method.invoke(null, objArg); - return type.getCanonicalName()+"."+objVal.toString(); + return type.getCanonicalName() + "." + objVal; } } } @@ -381,7 +380,7 @@ public static String findConstByValue(Class type, String value, Class cons { if (constant.toString().equals(value)) { - return type.getCanonicalName()+"."+constant.toString(); + return type.getCanonicalName() + "." + constant; } } return null; @@ -468,8 +467,9 @@ public static Constructor findConstructor(Class type, Class parameterTy Constructor[] constructors = type.getConstructors(); for (Constructor constructor : constructors) { Class[] parameterTypes = constructor.getParameterTypes(); - if (parameterTypes.length == 1 && parameterTypes[0].equals(parameterType)) - return constructor; + if(parameterTypes.length == 1 && parameterTypes[0].equals(parameterType)) { + return constructor; + } } return null; } @@ -482,9 +482,10 @@ public static Constructor findConstructor(Class type, Class parameterTy * if the class does not have any constructor. */ public static Constructor inferConstructor(Class type) { - if (type.equals(String.class)) - return null; - if (type.equals(BigDecimal.class) || type.equals((BigInteger.class))) { + if(type.equals(String.class)) { + return null; + } + if(type.equals(BigDecimal.class) || type.equals(BigInteger.class)) { try { return type.getConstructor(String.class); } catch (Exception e) { @@ -494,8 +495,9 @@ public static Constructor inferConstructor(Class type) { Constructor[] constructors = type.getConstructors(); for (Constructor constructor : constructors) { Class[] parameterTypes = constructor.getParameterTypes(); - if (parameterTypes.length == 1 && parameterTypes[0].equals(ClassUtils.wrapperToPrimitive(type))) - return constructor; + if(parameterTypes.length == 1 && parameterTypes[0].equals(ClassUtils.wrapperToPrimitive(type))) { + return constructor; + } } return null; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/BaseMessageGetterSetterGeneratorImpl.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/BaseMessageGetterSetterGeneratorImpl.java index bd1f4cb9..2fbb7054 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/BaseMessageGetterSetterGeneratorImpl.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/BaseMessageGetterSetterGeneratorImpl.java @@ -156,8 +156,11 @@ public String getSetter( Class type, String parameterName, String value, bool if (isReference) { String methodName = null; - if (methodWithEnum != null) methodName = methodWithEnum.getName(); - else if (methodWithPrimitive != null) methodName = methodWithPrimitive.getName(); + if(methodWithEnum != null) { + methodName = methodWithEnum.getName(); + } else if(methodWithPrimitive != null) { + methodName = methodWithPrimitive.getName(); + } return "."+methodName+"("+value+")"; } @@ -165,9 +168,8 @@ public String getSetter( Class type, String parameterName, String value, bool int flag = 0; if (methodWithEnum != null) { - String convertedValue = value; - Class valueType = methodWithEnum.getParameterTypes()[0]; - convertedValue = TypeConverter.findConstant(valueType, value); + Class valueType = methodWithEnum.getParameterTypes()[0]; + String convertedValue = TypeConverter.findConstant(valueType, value); String methodName = methodWithEnum.getName(); if (Convention.CONV_PRESENT_STRING.equals(value)){ @@ -221,7 +223,7 @@ public String getSetter( Class type, String parameterName, String value, bool String convertedValue = TypeConverter.findConstant(methodParameterType, value, constType); if (convertedValue != null) { - if ((TypeConverter.findConstructor(methodParameterType, constType.get()))!=null) { + if (TypeConverter.findConstructor(methodParameterType, constType.get()) !=null) { return "." + methodName + "( new "+ methodParameterType.getCanonicalName() + "(" + convertedValue + ")" + ")"; } else if (constType.get().equals(methodParameterType)){ return "." + methodName + "(" + convertedValue + ")"; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/HashMapGetterSetterGeneratorImpl.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/HashMapGetterSetterGeneratorImpl.java index b234dfdf..ad021207 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/HashMapGetterSetterGeneratorImpl.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/factory/HashMapGetterSetterGeneratorImpl.java @@ -53,12 +53,8 @@ public String getSetter(Class type, String parameterName, String value, @Override public Class getSubmessageClass(Class type, String childClassName, Class paramClass) { - if(paramClass == IMessage.class) { - return IMessage.class; - } - - return HashMap.class; - } + return paramClass == IMessage.class ? IMessage.class : HashMap.class; + } //@Override //private Method getGetterMethod(Class type, String parameterName) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/BoolExp.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/BoolExp.java index aec291ec..c8eb7504 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/BoolExp.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/BoolExp.java @@ -25,13 +25,13 @@ public enum BoolExp { GreaterOrEquals(">="), LessOrEquals("<="); - private String expression; + private final String expression; - private BoolExp(String exp) { + BoolExp(String exp) { this.expression = exp; } public String getName() { - return this.expression; + return expression; } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Column.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Column.java index ce5e35c9..00df14c1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Column.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Column.java @@ -23,53 +23,53 @@ */ public enum Column { - Reference(Constants.SYSTEM_PREFIX.concat("reference"), "action reference"), - ReferenceToFilter(Constants.SYSTEM_PREFIX.concat("reference_to_filter"), "reference to filter message"), - Template(Constants.SYSTEM_PREFIX.concat("template"), "Template message"), - ServiceName(Constants.SYSTEM_PREFIX.concat("service_name"), "service name"), - Action(Constants.SYSTEM_PREFIX.concat("action"), "action name"), - Execute(Constants.SYSTEM_PREFIX.concat("execute"), "Y or N to control from matrix whether this action to be executed"), - Timeout(Constants.SYSTEM_PREFIX.concat("timeout"), "wait action timeout"), - Id(Constants.SYSTEM_PREFIX.concat("id"), "action id"), - MessageType(Constants.SYSTEM_PREFIX.concat("message_type"), "message type"), - CheckPoint(Constants.SYSTEM_PREFIX.concat("check_point"), "action checkpoint"), - Description(Constants.SYSTEM_PREFIX.concat("description"), "some comments about action"), - Dictionary(Constants.SYSTEM_PREFIX.concat("dictionary"), "dictionary name"), - AddToReport(Constants.SYSTEM_PREFIX.concat("add_to_report"), "Y or N to control from matrix whether this action to be added to report"), - MessageCount(Constants.SYSTEM_PREFIX.concat("messages_count"), "Expected message count. Used to check how many messages received after specified checkpoint."), - DoublePrecision(Constants.SYSTEM_PREFIX.concat("double_precision"), "precision of double and float comparison"), - StaticType(Constants.SYSTEM_PREFIX.concat("static_type"), "type of static variable"), - StaticValue(Constants.SYSTEM_PREFIX.concat("static_value"), "value of static variable"), - ContinueOnFailed(Constants.SYSTEM_PREFIX.concat("continue_on_failed"), "Y or N to from matrix should script continue execution when error occurred or break test"), - BreakPoint(Constants.SYSTEM_PREFIX.concat("break_point"), "Y or N (default) to set break point before execute current action"), - SystemPrecision(Constants.SYSTEM_PREFIX.concat("system_precision"), "precision of double and float comparison"), - FailUnexpected(Constants.SYSTEM_PREFIX.concat("fail_unexpected"), "fail all unexpected fields in message"), - Outcome(Constants.SYSTEM_PREFIX.concat("outcome"), "group verifications by outcome parameter"), - FailOnUnexpectedMessage(Constants.SYSTEM_PREFIX.concat("fail_on_unexpected_message"), "TC should fail if unexpected by wait actions message received"), - CheckGroupsOrder(Constants.SYSTEM_PREFIX.concat("check_groups_order"), "Check order of group when comparing"), - Condition(Constants.SYSTEM_PREFIX.concat("condition"), "Used for conditional operator"), - ReorderGroups(Constants.SYSTEM_PREFIX.concat("reorder_groups"), "If Y then repeating groups in received message will be reordered according to message filter"), - IsStatic(Constants.SYSTEM_PREFIX.concat("is_static"), "If Y then action will be considered static and will be accessible in following test cases"), - Comment(Constants.SYSTEM_PREFIX.concat("comment"), "If Y then action will be ignored"), - Tag(Constants.SYSTEM_PREFIX.concat("tag"), "action tag for statistics"), - Dependencies(Constants.SYSTEM_PREFIX.concat("dependencies"), "list of references on which this action depends"), - VerificationsOrder(Constants.SYSTEM_PREFIX.concat("verifications_order"), "Field order for sorting verifications in report"), + Reference(Constants.SYSTEM_PREFIX + "reference", "action reference"), + ReferenceToFilter(Constants.SYSTEM_PREFIX + "reference_to_filter", "reference to filter message"), + Template(Constants.SYSTEM_PREFIX + "template", "Template message"), + ServiceName(Constants.SYSTEM_PREFIX + "service_name", "service name"), + Action(Constants.SYSTEM_PREFIX + "action", "action name"), + Execute(Constants.SYSTEM_PREFIX + "execute", "Y or N to control from matrix whether this action to be executed"), + Timeout(Constants.SYSTEM_PREFIX + "timeout", "wait action timeout"), + Id(Constants.SYSTEM_PREFIX + "id", "action id"), + MessageType(Constants.SYSTEM_PREFIX + "message_type", "message type"), + CheckPoint(Constants.SYSTEM_PREFIX + "check_point", "action checkpoint"), + Description(Constants.SYSTEM_PREFIX + "description", "some comments about action"), + Dictionary(Constants.SYSTEM_PREFIX + "dictionary", "dictionary name"), + AddToReport(Constants.SYSTEM_PREFIX + "add_to_report", "Y or N to control from matrix whether this action to be added to report"), + MessageCount(Constants.SYSTEM_PREFIX + "messages_count", "Expected message count. Used to check how many messages received after specified checkpoint."), + DoublePrecision(Constants.SYSTEM_PREFIX + "double_precision", "precision of double and float comparison"), + StaticType(Constants.SYSTEM_PREFIX + "static_type", "type of static variable"), + StaticValue(Constants.SYSTEM_PREFIX + "static_value", "value of static variable"), + ContinueOnFailed(Constants.SYSTEM_PREFIX + "continue_on_failed", "Y or N to from matrix should script continue execution when error occurred or break test"), + BreakPoint(Constants.SYSTEM_PREFIX + "break_point", "Y or N (default) to set break point before execute current action"), + SystemPrecision(Constants.SYSTEM_PREFIX + "system_precision", "precision of double and float comparison"), + FailUnexpected(Constants.SYSTEM_PREFIX + "fail_unexpected", "fail all unexpected fields in message"), + Outcome(Constants.SYSTEM_PREFIX + "outcome", "group verifications by outcome parameter"), + FailOnUnexpectedMessage(Constants.SYSTEM_PREFIX + "fail_on_unexpected_message", "TC should fail if unexpected by wait actions message received"), + CheckGroupsOrder(Constants.SYSTEM_PREFIX + "check_groups_order", "Check order of group when comparing"), + Condition(Constants.SYSTEM_PREFIX + "condition", "Used for conditional operator"), + ReorderGroups(Constants.SYSTEM_PREFIX + "reorder_groups", "If Y then repeating groups in received message will be reordered according to message filter"), + IsStatic(Constants.SYSTEM_PREFIX + "is_static", "If Y then action will be considered static and will be accessible in following test cases"), + Comment(Constants.SYSTEM_PREFIX + "comment", "If Y then action will be ignored"), + Tag(Constants.SYSTEM_PREFIX + "tag", "action tag for statistics"), + Dependencies(Constants.SYSTEM_PREFIX + "dependencies", "list of references on which this action depends"), + VerificationsOrder(Constants.SYSTEM_PREFIX + "verifications_order", "Field order for sorting verifications in report"), _no_columns_required(null, "Used only for annotations."); public String getHelpString() { return helpString; } - private String column; - private String helpString; + private final String column; + private final String helpString; - private Column(String colName, String helpString) { + Column(String colName, String helpString) { this.column = colName; this.helpString = helpString; } public String getName() { - return this.column; + return column; } public static Column value(String key) { @@ -91,7 +91,7 @@ public static String getIgnoredPrefix() { return Constants.IGNORED_PREFIX; } - private final static class Constants { + private static final class Constants { public static final String SYSTEM_PREFIX = "#"; private static final String IGNORED_PREFIX = "~"; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/JavaStatement.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/JavaStatement.java index a8517c2a..737e0266 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/JavaStatement.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/JavaStatement.java @@ -30,26 +30,26 @@ public enum JavaStatement { END_IF("ENDIF"), INCLUDE_BLOCK("IncludeBlock", Column.Template); - private String value; - private Column[] requiredColumns; - private SailfishURI uri; + private final String value; + private final Column[] requiredColumns; + private final SailfishURI uri; - private JavaStatement(String s, Column... requiredColumns) { + JavaStatement(String s, Column... requiredColumns) { this.value = s; this.requiredColumns = requiredColumns; this.uri = SailfishURI.unsafeParse(s); } public String getValue() { - return this.value; + return value; } public Column[] getRequiredColumns() { - return this.requiredColumns; + return requiredColumns; } public SailfishURI getURI() { - return this.uri; + return uri; } public static JavaStatement value(String s) { @@ -58,8 +58,9 @@ public static JavaStatement value(String s) { } for (JavaStatement e : JavaStatement.values()) { - if (e.value.equalsIgnoreCase(s)) - return e; + if(e.value.equalsIgnoreCase(s)) { + return e; + } } return null; @@ -77,6 +78,6 @@ public static JavaStatement value(SailfishURI uri) { @Override public String toString() { - return this.value; + return value; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/RefParameter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/RefParameter.java index cace1dd0..f95506ef 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/RefParameter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/RefParameter.java @@ -22,8 +22,8 @@ @SuppressWarnings("serial") public class RefParameter implements Serializable { - private String name; - private String value; + private final String name; + private final String value; public RefParameter(String name, String value) { this.name = name; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/TypeHelper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/TypeHelper.java index 8d7e494a..4cea6c57 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/TypeHelper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/TypeHelper.java @@ -30,7 +30,7 @@ public class TypeHelper { - private static Map> types = new HashMap>(); + private static final Map> TYPES = new HashMap>(); static { add(String.class); @@ -59,8 +59,8 @@ public class TypeHelper { } private static void add(Class keyClass, Class valueClass) { - types.put(keyClass.getCanonicalName(), valueClass); - types.put(keyClass.getSimpleName(), valueClass); + TYPES.put(keyClass.getCanonicalName(), valueClass); + TYPES.put(keyClass.getSimpleName(), valueClass); } private static void add(Class clazz) { @@ -72,7 +72,7 @@ private TypeHelper() { } public static Class getClass(String clazz) { - return types.get(clazz); + return TYPES.get(clazz); } public static String convertValue(String type, String value) throws AMLException diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Value.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Value.java index 5a982ed3..cb8c81c4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Value.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Value.java @@ -16,6 +16,7 @@ package com.exactpro.sf.aml.generator.matrix; import java.io.Serializable; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -32,26 +33,24 @@ @SuppressWarnings("serial") public class Value implements IField, Cloneable, Serializable { - private boolean isReference = false; - private boolean isJava = false; + private boolean isReference; + private boolean isJava; private String fieldName; private String value; private final String origValue; private boolean check = true; - private int index = 0; - private List parameters; + private int index; + private final List parameters = new ArrayList<>(); public Value(String value) { setValue(value); this.origValue = value; - this.parameters = new LinkedList(); - } + } public Value(String origValue, String newValue) { setValue(newValue); this.origValue = origValue; - this.parameters = new LinkedList(); - } + } /** * Return true if value referred to another message. @@ -129,7 +128,7 @@ public void setCheck(boolean check) { * Return true if value need to be checked by precompilation. */ public boolean isCheck() { - return this.check; + return check; } public void setFieldName(String name) { @@ -137,7 +136,7 @@ public void setFieldName(String name) { } public String getFieldName() { - return this.fieldName; + return fieldName; } public int nextIndex() { @@ -145,7 +144,7 @@ public int nextIndex() { } public void addParameter(RefParameter p) { - this.parameters.add(p); + parameters.add(p); } public List getParameters() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Variable.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Variable.java index 84aa477e..3cac6bcf 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Variable.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/generator/matrix/Variable.java @@ -27,8 +27,8 @@ */ public class Variable { - private String name; - private Class type; + private final String name; + private final Class type; public Variable(String name, Class type) { this.name = name; @@ -53,15 +53,16 @@ public Class getType() { @Override public boolean equals(Object o) { - if (o == null) - return false; + if(o == null) { + return false; + } if (o instanceof Variable) { Variable that = (Variable)o; List arr1 = new ArrayList(); List arr2 = new ArrayList(); - arr1.add(this.name); + arr1.add(name); arr2.add(that.name); - arr1.add(this.type); + arr1.add(type); arr2.add(that.type); return arr1.equals(arr2); } @@ -70,7 +71,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - return (this.name+this.type).hashCode(); + return (name + type).hashCode(); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReader.java index 569cb998..a9b866ab 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReader.java @@ -33,14 +33,14 @@ public class AdvancedMatrixReader implements AutoCloseable { - private final static String ACTION_FIELD = Column.Action.getName(); - private final static String DEFINE_HEADER = JavaStatement.DEFINE_HEADER.getValue(); - private final static String SYSTEM_FIELD_PREFIX = Column.getSystemPrefix(); + private static final String ACTION_FIELD = Column.Action.getName(); + private static final String DEFINE_HEADER = JavaStatement.DEFINE_HEADER.getValue(); + private static final String SYSTEM_FIELD_PREFIX = Column.getSystemPrefix(); private final IMatrixReader reader; private List header; private final MatrixFileTypes fileType; - private boolean positionFound = false; + private boolean positionFound; private int actionPosition = -1; private int rowNumber = 1; @@ -147,7 +147,7 @@ public boolean hasNext() { @Override public void close() throws Exception { - this.reader.close(); + reader.close(); } private void redefineHeaders(SimpleCell[] readedSimpleCells) throws AMLException { @@ -215,7 +215,7 @@ private boolean checkHeaders(List headers) throws AMLException { letterPositions.append(", "); } throw new AMLException("Invalid matrix structure. Detected duplicated fields at " - + letterPositions.toString() + " positions. Field name is " + header.get(i - 1).getValue()); + + letterPositions + " positions. Field name is " + header.get(i - 1).getValue()); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriter.java index 9a1d501a..39d87b3e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriter.java @@ -21,25 +21,26 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.aml.generator.matrix.Column; import com.exactpro.sf.aml.generator.matrix.JavaStatement; +import com.exactpro.sf.common.util.EPSCommonException; public class AdvancedMatrixWriter implements AutoCloseable { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final static String SYSTEM_FIELD_PREFIX = Column.getSystemPrefix(); - private final static String ACTION_FIELD = Column.Action.getName(); - private final static String DEFINE_HEADER = JavaStatement.DEFINE_HEADER.getValue(); + private final Logger logger = LoggerFactory.getLogger(getClass()); + private static final String SYSTEM_FIELD_PREFIX = Column.getSystemPrefix(); + private static final String ACTION_FIELD = Column.Action.getName(); + private static final String DEFINE_HEADER = JavaStatement.DEFINE_HEADER.getValue(); private final IMatrixWriter writer; private final List header; private final Map convertedHeaders; - private boolean isHeaderWrited = false; + private boolean isHeaderWrited; private int rowNumber = 1; public static IMatrixWriter getWriter(File matrixPath) throws IOException { @@ -81,7 +82,7 @@ public AdvancedMatrixWriter(File file, List mainHeaders) throws IOEx @Override public void close() throws Exception { - this.writer.close(); + writer.close(); } public void writeCells(Map line) throws IOException { @@ -93,7 +94,7 @@ public void writeCells(Map line) throws IOException { int unknownFieldsCount = 0; - for (Map.Entry cell : line.entrySet()) { + for(Entry cell : line.entrySet()) { if (!convertedHeaders.containsKey(cell.getKey())) { unknownFieldsCount++; } @@ -105,7 +106,7 @@ public void writeCells(Map line) throws IOException { SimpleCell[] cells = new SimpleCell[header.size() + unknownFieldsCount]; int additionalIndx = header.size(); - for (Map.Entry entry : line.entrySet()) { + for(Entry entry : line.entrySet()) { if (!convertedHeaders.containsKey(entry.getKey())) { convertedHeaders.put(entry.getKey(), additionalIndx); cells[additionalIndx++] = entry.getValue(); @@ -216,7 +217,7 @@ private boolean checkHeaders(List headers) throws IOException { } throw new IOException("Invalid matrix structure. Detected duplicated fields at " - + letterPositions.toString() + " positions. Field name is " + headers.get(counter).getValue()); + + letterPositions + " positions. Field name is " + headers.get(counter).getValue()); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVDelimiter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVDelimiter.java index ebec40cf..3c1bf88a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVDelimiter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVDelimiter.java @@ -21,11 +21,11 @@ public enum CSVDelimiter { COMMA(',', "\\,", ","), SEMICOLON(';', ";", ";"); - private char charValue; - private String escaped; - private String stringValue; + private final char charValue; + private final String escaped; + private final String stringValue; - private CSVDelimiter(char charValue, String escaped, String stringValue) { + CSVDelimiter(char charValue, String escaped, String stringValue) { this.charValue = charValue; this.escaped = escaped; this.stringValue = stringValue; @@ -45,14 +45,14 @@ public static CSVDelimiter valueOf(char charValue) { } public char getCharValue() { - return this.charValue; + return charValue; } public String getEscaped() { - return this.escaped; + return escaped; } public String getStringValue() { - return this.stringValue; + return stringValue; } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReader.java index f8d14bf6..e9f2449d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReader.java @@ -23,8 +23,8 @@ import java.util.Arrays; import java.util.NoSuchElementException; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; import com.csvreader.CsvReader; import com.exactpro.sf.util.UnicodeReader; @@ -74,8 +74,8 @@ public CSVMatrixReader(InputStream inputStream, char delimiter, String encoding) reader = new CsvReader(rdr); reader.setDelimiter(delimiter); - this.reader.setSkipEmptyRecords(false); - this.reader.setTrimWhitespace(true); + reader.setSkipEmptyRecords(false); + reader.setTrimWhitespace(true); readRecord(); } @@ -151,8 +151,9 @@ public boolean hasNext() { * @throws IOException */ public static char determineCSVDelimiter(InputStream is, boolean needClose) throws IOException { - if (is.markSupported()) + if(is.markSupported()) { is.mark(0); + } byte[] bytes = new byte[1024]; try { @@ -197,10 +198,6 @@ public static CSVDelimiter determineCSVDelimiter(byte[] bytes, int size) { } private static InputStream wrappedStream(InputStream in) { - if (in.markSupported()) { - return in; - } else { - return new BufferedInputStream(in); - } + return in.markSupported() ? in : new BufferedInputStream(in); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixReader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixReader.java index a694311d..f9c001ae 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixReader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixReader.java @@ -48,7 +48,7 @@ public class ExcelMatrixReader implements IMatrixReader { private Row currentRow; private Cell currentCell; private boolean hasNext; - private int sheetIndex = 0; + private final int sheetIndex; private int lastRowIndex = -1; public ExcelMatrixReader(String fileName, boolean useXlsx) throws IOException { @@ -76,7 +76,7 @@ public ExcelMatrixReader(InputStream inputStream, boolean useXlsx, int sheetNumb sheet = workbook.getSheetAt(sheetIndex); rowIterator = sheet.iterator(); this.dataFormatter = new DataFormatter(true); - this.dataFormatter.setDefaultNumberFormat(NumberFormat.getNumberInstance(Locale.US)); + dataFormatter.setDefaultNumberFormat(NumberFormat.getNumberInstance(Locale.US)); readRecord(); } @@ -109,7 +109,7 @@ public SimpleCell[] readCells() throws NoSuchElementException { cells.add(new SimpleCell("")); } - String value = this.dataFormatter.formatCellValue(currentCell,formulaEvaluator).trim(); + String value = dataFormatter.formatCellValue(currentCell, formulaEvaluator).trim(); allEmpty &= StringUtils.isEmpty(value); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriter.java index 3e40b400..4d17430c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriter.java @@ -33,11 +33,11 @@ public class ExcelMatrixWriter implements IMatrixWriter { private final Workbook workbook; private final Sheet sheet; - private OutputStream fileStream; - private int row = 0; - private int column = 0; - - private Map stylesCashe; + private final OutputStream fileStream; + private int row; + private int column; + + private final Map stylesCashe = new HashMap<>(); public ExcelMatrixWriter(String fileName, boolean useXlsx) throws IOException { @@ -61,8 +61,6 @@ public ExcelMatrixWriter(OutputStream outputStream, boolean useXlsx, String shee this.workbook = useXlsx ? new XSSFWorkbook() : new HSSFWorkbook(); sheet = workbook.createSheet(sheetName); - - stylesCashe = new HashMap<>(); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixReader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixReader.java index e9252cc1..abedfaa8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixReader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixReader.java @@ -19,10 +19,10 @@ public interface IMatrixReader extends AutoCloseable { - public SimpleCell[] readCells() throws IOException; + SimpleCell[] readCells() throws IOException; - public String[] read() throws IOException; + String[] read() throws IOException; - public boolean hasNext(); + boolean hasNext(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixWriter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixWriter.java index 68359332..a962c63d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixWriter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/IMatrixWriter.java @@ -19,9 +19,9 @@ public interface IMatrixWriter extends AutoCloseable { - public void writeCells(SimpleCell[] cells) throws IOException; + void writeCells(SimpleCell[] cells) throws IOException; - public void write(String[] strings) throws IOException; + void write(String[] strings) throws IOException; - public void flush() throws IOException; + void flush() throws IOException; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/MatrixFileTypes.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/MatrixFileTypes.java index c0a39b7c..6bf020f6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/MatrixFileTypes.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/MatrixFileTypes.java @@ -19,9 +19,9 @@ public enum MatrixFileTypes { CSV("csv"), XLS("xls"), XLSX("xlsx"), UNKNOWN("?"), JSON("json"); - private String fileType; + private final String fileType; - private MatrixFileTypes(String extension) { + MatrixFileTypes(String extension) { this.fileType = extension; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCell.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCell.java index d4a80a1d..fff278f7 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCell.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCell.java @@ -62,8 +62,8 @@ public boolean equals(Object obj){ SimpleCell that = (SimpleCell)obj; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.value, that.value); - builder.append(this.cellStyle, that.cellStyle); + builder.append(value, that.value); + builder.append(cellStyle, that.cellStyle); return builder.isEquals(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCellUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCellUtils.java index 46bbb8f6..5c1cc24f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCellUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/iomatrix/SimpleCellUtils.java @@ -19,6 +19,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; public class SimpleCellUtils { @@ -56,7 +57,7 @@ public static List addStyles(List line) { public static Map dropStyles(Map line) { Map result = new LinkedHashMap<>(); - for (Map.Entry entry : line.entrySet()) { + for (Entry entry : line.entrySet()) { result.put(entry.getKey(), entry.getValue().getValue()); } return result; @@ -64,7 +65,7 @@ public static Map dropStyles(Map line) { public static Map addStyles(Map line) { Map result = new LinkedHashMap<>(); - for (Map.Entry entry : line.entrySet()) { + for (Entry entry : line.entrySet()) { result.put(entry.getKey(), new SimpleCell(entry.getValue())); } return result; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/magic/IMessage2Action.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/magic/IMessage2Action.java index a485fcea..81af920f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/magic/IMessage2Action.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/magic/IMessage2Action.java @@ -26,7 +26,7 @@ public class IMessage2Action { - public static List convert(final IMessage message) { + public static List convert(IMessage message) { // dumb implementation: List result = convertImessageFields(message); @@ -43,7 +43,7 @@ public static List convert(final IMessage message) { return result; } - private static List convertImessageFields(final IMessage message) { + private static List convertImessageFields(IMessage message) { List result = new ArrayList<>(); AMLElement action = new AMLElement(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/DefaultSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/DefaultSettings.java index 42ca81fb..a997411f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/DefaultSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/DefaultSettings.java @@ -77,10 +77,10 @@ public class DefaultSettings implements IActionContext { private SailfishURI dictionaryURI; private Map messages = Collections.emptyMap(); private MetaContainer metaContainer; - private boolean checkGroupsOrder = false; + private boolean checkGroupsOrder; @Deprecated private Map negativeMap = Collections.emptyMap(); - private boolean reorderGroups = false; + private boolean reorderGroups; private Set uncheckedFields = Collections.emptySet(); private final IActionReport report; private final IActionServiceManager serviceManager; @@ -218,12 +218,8 @@ public String toString() sb.append("timeout=").append(getTimeout()).append(", "); } - if (sb.length() > 2) { - return sb.substring(0, sb.length()-2); - } - - return sb.toString(); - } + return sb.length() > 2 ? sb.substring(0, sb.length() - 2) : sb.toString(); + } public void setAddToReport(boolean addToReport) { this.addToReport = addToReport; @@ -240,7 +236,7 @@ public void setMessageCount(MessageCount messageCount) { @Override public MessageCount getMessageCount() { - return this.messageCount; + return messageCount; } @Override @@ -299,13 +295,8 @@ public void setDictionaryURI(SailfishURI dictionaryURI) { @Override public Object getMessage(String reference) { Object message = messages.get(reference); - - if(message instanceof IMessage) { - return ((IMessage)message).cloneMessage(); - } - - return message; - } + return message instanceof IMessage ? ((IMessage)message).cloneMessage() : message; + } public void setMessages(Map messages) { this.messages = messages; @@ -313,7 +304,7 @@ public void setMessages(Map messages) { @Override public MetaContainer getMetaContainer() { - return this.metaContainer; + return metaContainer; } public void setMetaContainer(MetaContainer metaContainer) { @@ -337,7 +328,7 @@ public void setNegativeMap(Map negativeMap) { @Override @Deprecated // In AML3 we use 'x != 2' public Map getNegativeMap() { - return this.negativeMap; + return negativeMap; } @Override @@ -361,12 +352,12 @@ public void putSystemColumn(String name, Object value) { @Override public IDataManager getDataManager() { - return this.dataManager; + return dataManager; } @Override public Set getUncheckedFields() { - return this.uncheckedFields; + return uncheckedFields; } public void setUncheckedFields(Set uncheckedFields) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/MetaContainer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/MetaContainer.java index aafcda84..f3749d6e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/MetaContainer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/MetaContainer.java @@ -22,6 +22,7 @@ import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import com.exactpro.sf.common.util.EPSCommonException; @@ -33,9 +34,9 @@ public class MetaContainer { private final Map systemPrecision = new HashMap<>(); private final Map systemColumns = new HashMap<>(); private String alternateValue; - private String failUnexpected = null; + private String failUnexpected; - private Map> children; + private final Map> children; private void propogateParentValues(MetaContainer parentMetaContainer) { @@ -53,8 +54,9 @@ private void propogateParentValues(MetaContainer parentMetaContainer) } } - if (failUnexpected == null) - failUnexpected = parentMetaContainer.getFailUnexpected(); + if(failUnexpected == null) { + failUnexpected = parentMetaContainer.getFailUnexpected(); + } for (Entry> fldChl : children.entrySet()) { for (MetaContainer child: fldChl.getValue()) { @@ -68,28 +70,22 @@ public MetaContainer() { } private Map getDoublePrecision() { - return this.doublePrecision; + return doublePrecision; } public Double getDoublePrecision(String field) { - if (this.doublePrecision != null) { - return this.doublePrecision.get(field); - } - return null; - } + return doublePrecision != null ? doublePrecision.get(field) : null; + } public void addDoublePrecision(String doublePrecision) { this.doublePrecision.putAll(parsePrecision(doublePrecision)); } private Map getSystemPrecision() { - return this.systemPrecision; + return systemPrecision; } public Double getSystemPrecision(String field) { - if (this.systemPrecision != null) { - return this.systemPrecision.get(field); - } - return null; - } + return systemPrecision != null ? systemPrecision.get(field) : null; + } public void addSystemPrecision(String systemPrecision) { this.systemPrecision.putAll(parsePrecision(systemPrecision)); @@ -111,7 +107,7 @@ public void add(String name, MetaContainer mc) { List obj = children.get(name); if (obj == null) { obj = new ArrayList<>(); - this.children.put(name, obj); + children.put(name, obj); } mc.propogateParentValues(this); obj.add(mc); @@ -123,7 +119,7 @@ public List get(String name) { private Map parsePrecision(String precision) { - if (precision == null || precision.equals("")) { + if(StringUtils.isEmpty(precision)) { return Collections.emptyMap(); } Map fieldVal = new HashMap<>(); @@ -132,7 +128,7 @@ private Map parsePrecision(String precision) { String[] arr = prec.trim().split("="); String field = arr[0].trim(); - if (field.equals("")) { + if(field.isEmpty()) { throw new EPSCommonException("Parameter name not specified: "+precision); } if (arr.length == 1) { @@ -173,10 +169,10 @@ public void putSystemColumn(String name, Object value) { public MetaContainer clone() { MetaContainer result = new MetaContainer(); - result.setFailUnexpected(this.failUnexpected); - result.setAlternateValue(this.alternateValue); - result.doublePrecision.putAll(this.doublePrecision); - result.systemPrecision.putAll(this.systemPrecision); + result.setFailUnexpected(failUnexpected); + result.setAlternateValue(alternateValue); + result.doublePrecision.putAll(doublePrecision); + result.systemPrecision.putAll(systemPrecision); return result; } @@ -185,8 +181,8 @@ public MetaContainer clone() { public String toString() { return new ToStringBuilder(this) .append("failUnexpected", failUnexpected) - .append("alternateValue", this.alternateValue) - .append("doublePrecision", this.doublePrecision) - .append("children", this.children).toString(); + .append("alternateValue", alternateValue) + .append("doublePrecision", doublePrecision) + .append("children", children).toString(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/Util.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/Util.java index 6272ebf2..e0936efd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/Util.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/Util.java @@ -22,7 +22,7 @@ */ public class Util { - public final static String EOL = System.getProperty("line.separator"); + public static final String EOL = System.getProperty("line.separator"); private Util() { @@ -36,7 +36,7 @@ private Util() * @return converted object */ @SuppressWarnings("unchecked") - public static T cast(Object o) + public static T cast(Object o) { return (T)o; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/actions/WaitAction.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/actions/WaitAction.java index dcc22a49..df9ba065 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/actions/WaitAction.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/script/actions/WaitAction.java @@ -15,35 +15,50 @@ ******************************************************************************/ package com.exactpro.sf.aml.script.actions; -import com.exactpro.sf.common.messages.IMessage; -import com.exactpro.sf.common.services.ServiceName; -import com.exactpro.sf.common.util.EPSCommonException; -import com.exactpro.sf.common.util.Pair; +import static com.exactpro.sf.services.ServiceHandlerRoute.FROM_ADMIN; +import static com.exactpro.sf.services.ServiceHandlerRoute.FROM_APP; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.actions.ActionUtil; import com.exactpro.sf.aml.script.CheckPoint; +import com.exactpro.sf.aml.scriptutil.ExpressionResult; import com.exactpro.sf.aml.scriptutil.LegReorder; import com.exactpro.sf.aml.scriptutil.MessageCount; import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; -import com.exactpro.sf.comparison.*; +import com.exactpro.sf.common.messages.IMessage; +import com.exactpro.sf.common.services.ServiceName; +import com.exactpro.sf.common.util.EPSCommonException; +import com.exactpro.sf.common.util.Pair; +import com.exactpro.sf.comparison.ComparatorSettings; +import com.exactpro.sf.comparison.ComparisonResult; +import com.exactpro.sf.comparison.ComparisonUtil; +import com.exactpro.sf.comparison.Formatter; +import com.exactpro.sf.comparison.IPostValidation; +import com.exactpro.sf.comparison.MessageComparator; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.scriptrunner.MessageLevel; import com.exactpro.sf.scriptrunner.StatusType; import com.exactpro.sf.scriptrunner.actionmanager.actioncontext.IActionContext; import com.exactpro.sf.scriptrunner.actionmanager.actioncontext.IActionReport; import com.exactpro.sf.scriptrunner.actionmanager.actioncontext.IGroupReport; -import com.exactpro.sf.services.*; +import com.exactpro.sf.services.CSHIterator; +import com.exactpro.sf.services.ICSHIterator; +import com.exactpro.sf.services.IInitiatorService; +import com.exactpro.sf.services.IService; +import com.exactpro.sf.services.IServiceHandler; +import com.exactpro.sf.services.ISession; +import com.exactpro.sf.services.ServiceHandlerRoute; import com.exactpro.sf.util.KnownBugException; import com.exactpro.sf.util.KnownBugPostValidation; import com.exactpro.sf.util.MessageKnownBugException; -import com.exactpro.sf.aml.scriptutil.ExpressionResult; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; public class WaitAction { @@ -139,14 +154,10 @@ public static final IMessage waitForMessage(IActionContext actionContext, List> results = null; - logger.debug("[{}] start wait for message in {} queue", serviceName, ((fromApp) ? "application" : "admin")); + logger.debug("[{}] start wait for message in {} queue", serviceName, fromApp ? "application" : "admin"); try { - if (fromApp) { - results = waitMessage(handler, isession, ServiceHandlerRoute.FROM_APP, checkPoint, waitTime, messageFilter, settings); - } else { - results = waitMessage(handler, isession, ServiceHandlerRoute.FROM_ADMIN, checkPoint, waitTime, messageFilter, settings); - } + results = waitMessage(handler, isession, fromApp ? FROM_APP : FROM_ADMIN, checkPoint, waitTime, messageFilter, settings); } catch (InterruptedException e) { logger.error("[{}] InterruptedException:{}", serviceName, e.getMessage(), e); throw e; @@ -267,12 +278,12 @@ public static void countMessages(IActionContext actionContext, String descriptio long waitUntil = System.currentTimeMillis() + actionContext.getTimeout(); List reportMessages = new ArrayList<>(); - CSHIterator messagesIterator = handler.getIterator(isession, ServiceHandlerRoute.FROM_ADMIN, actionContext.getCheckPoint()); + CSHIterator messagesIterator = handler.getIterator(isession, FROM_ADMIN, actionContext.getCheckPoint()); while(messagesIterator.hasNext(waitUntil - System.currentTimeMillis())) { IMessage msg = messagesIterator.next(); - if(!msg.getName().equals("UnitHeader")){ + if(!"UnitHeader".equals(msg.getName())) { reportMessages.add(msg); } } @@ -356,9 +367,9 @@ public static void countMessages(IActionContext actionContext, IMessage message, } if (message != null) { - WaitAction.countMessages(actionContext.getReport(), serviceName, message, messageCount, handler, isession, actionContext.getCheckPoint(), isApp, compSettings, description); + countMessages(actionContext.getReport(), serviceName, message, messageCount, handler, isession, actionContext.getCheckPoint(), isApp, compSettings, description); } else { - WaitAction.countMessages(actionContext.getReport(), serviceName, messageCount, handler, isession, actionContext.getCheckPoint(), isApp, description); + countMessages(actionContext.getReport(), serviceName, messageCount, handler, isession, actionContext.getCheckPoint(), isApp, description); } } @@ -412,15 +423,12 @@ public static final int countMessages(IActionReport report, String serviceName, log.debug("countMessages 1"); List> allResults = new ArrayList<>(); - CSHIterator messagesIterator = handler.getIterator(isession, fromApp - ? ServiceHandlerRoute.FROM_APP - : ServiceHandlerRoute.FROM_ADMIN, - checkPoint); + CSHIterator messagesIterator = handler.getIterator(isession, fromApp ? FROM_APP : FROM_ADMIN, checkPoint); - WaitAction.countMessages(messageFilter, messagesIterator, settings, allResults); + countMessages(messageFilter, messagesIterator, settings, allResults); int messageCount = allResults.size(); - WaitAction.addResultToReport(report, expectedMessageCount, description, allResults, messageCount, true); + addResultToReport(report, expectedMessageCount, description, allResults, messageCount, true); return messageCount; } @@ -439,7 +447,7 @@ public static boolean addResultToReport(IGroupReport report, int i = 1; for (Pair result : allResults) { - report.createVerification(status, "Message " + (i++), "", "", result.getSecond(), null); + report.createVerification(status, "Message " + i++, "", "", result.getSecond(), null); } if(status == StatusType.CONDITIONALLY_PASSED) { @@ -453,7 +461,7 @@ public static boolean addResultToReport(IGroupReport report, int i = 1; for (Pair result : allResults) { - report.createVerification(StatusType.PASSED, "Message " + (i++), description, "", result.getSecond(), null); + report.createVerification(StatusType.PASSED, "Message " + i++, description, "", result.getSecond(), null); } if(exceptionOnFail) { // was != throw new EPSCommonException("Expected messages quantity did not match actual messages quantity." @@ -479,12 +487,8 @@ public static final void countMessages(IMessage messageFilter, IServiceHandler h CheckPoint checkPoint, boolean fromApp, ComparatorSettings settings, List> allResults) { - CSHIterator messagesIterator = handler.getIterator(isession, fromApp - ? ServiceHandlerRoute.FROM_APP - : ServiceHandlerRoute.FROM_ADMIN, - checkPoint); - WaitAction.countMessages(messageFilter, messagesIterator, settings, allResults); - + CSHIterator messagesIterator = handler.getIterator(isession, fromApp ? FROM_APP : FROM_ADMIN, checkPoint); + countMessages(messageFilter, messagesIterator, settings, allResults); } public static void countMessages(IMessage messageFilter, ICSHIterator messagesIterator, @@ -542,7 +546,7 @@ public static final int countMessages(IActionReport report, String serviceName, Object mc, IServiceHandler handler, ISession isession, CheckPoint checkPoint, boolean fromApp, String description) { - List messages = handler.getMessages(isession, fromApp ? ServiceHandlerRoute.FROM_APP : ServiceHandlerRoute.FROM_ADMIN, checkPoint); + List messages = handler.getMessages(isession, fromApp ? FROM_APP : FROM_ADMIN, checkPoint); // add status to report int receivedMessages = messages.size(); @@ -584,7 +588,7 @@ public static void countMessages(IActionContext actionContext, List mess IServiceHandler handler = getServiceHandler(service); ISession session = getSession(service); - List messages = handler.getMessages(session, isApp ? ServiceHandlerRoute.FROM_APP : ServiceHandlerRoute.FROM_ADMIN, checkPoint); + List messages = handler.getMessages(session, isApp ? FROM_APP : FROM_ADMIN, checkPoint); Iterator it = messages.iterator(); while(it.hasNext()) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/ExpressionResult.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/ExpressionResult.java index 2922aca2..709828de 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/ExpressionResult.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/ExpressionResult.java @@ -112,20 +112,20 @@ public boolean equals(Object o) { ExpressionResult that = (ExpressionResult) o; return new EqualsBuilder() - .append(this.result, that.result) - .append(this.description, that.description) - .append(this.actualDescriptions, that.actualDescriptions) - .append(this.potentialDescriptions, that.potentialDescriptions) + .append(result, that.result) + .append(description, that.description) + .append(actualDescriptions, that.actualDescriptions) + .append(potentialDescriptions, that.potentialDescriptions) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() - .append(this.result) - .append(this.description) - .append(this.actualDescriptions) - .append(this.potentialDescriptions) + .append(result) + .append(description) + .append(actualDescriptions) + .append(potentialDescriptions) .toHashCode(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/IMessagePropertyHandler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/IMessagePropertyHandler.java index 8c47c4b1..5d8a6862 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/IMessagePropertyHandler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/IMessagePropertyHandler.java @@ -34,7 +34,7 @@ public Object getProperty( Object propertyValue = iMessage.getField(propName); if(propertyValue instanceof IFilter){ try { - propertyValue = ((IFilter) propertyValue).getValue(); + return ((IFilter) propertyValue).getValue(); } catch(MvelException e) { throw new EPSCommonException("Failed to get value: probably wrong filter type", e); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/LegReorder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/LegReorder.java index 2406173b..76377528 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/LegReorder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/LegReorder.java @@ -30,7 +30,7 @@ public class LegReorder { - private static Logger logger = LoggerFactory.getLogger(LegReorder.class); + private static final Logger logger = LoggerFactory.getLogger(LegReorder.class); private LegReorder() { // hide constructor @@ -38,28 +38,28 @@ private LegReorder() { // 1) message matches filter // 2) message is IMessage (so it mainly for AML3) - public static IMessage reorder(final IMessage message, final IMessage filter, ComparatorSettings settings) { + public static IMessage reorder(IMessage message, IMessage filter, ComparatorSettings settings) { logger.debug("start reorder legs"); logger.debug("message: {}", message); logger.debug("filter: {}", filter); for (String fieldName : message.getFieldNames()) { - final Object message_field = message.getField(fieldName); - final Object filter_field = filter.getField(fieldName); + Object message_field = message.getField(fieldName); + Object filter_field = filter.getField(fieldName); if (message_field == null || filter_field == null) { continue; } if (message_field instanceof List && filter_field instanceof List) { - @SuppressWarnings("unchecked") - final List message_legs = (List) message_field; + @SuppressWarnings("unchecked") + List message_legs = (List)message_field; - @SuppressWarnings("unchecked") - final List filter_legs = (List) filter_field; + @SuppressWarnings("unchecked") + List filter_legs = (List)filter_field; - final int m_size = message_legs.size(); - final int f_size = filter_legs.size(); + int m_size = message_legs.size(); + int f_size = filter_legs.size(); if (m_size == 0 || f_size == 0) { continue; @@ -73,10 +73,10 @@ public static IMessage reorder(final IMessage message, final IMessage filter, Co sb.append("\n"); sb.append("FILTER: ").append(filter_field); sb.append("\n"); - throw new IllegalArgumentException("Failed to found correct order of legs: " + sb.toString()); + throw new IllegalArgumentException("Failed to found correct order of legs: " + sb); } - final List new_legs = new ArrayList<>(message_legs.size()); + List new_legs = new ArrayList<>(message_legs.size()); for (int i = 0; i < order.length; i++) { IMessage msg = message_legs.get(order[i]); @@ -96,12 +96,12 @@ public static IMessage reorder(final IMessage message, final IMessage filter, Co return message; } - private static int[] findPermute(final List message_legs, final List filter_legs, final ComparatorSettings settings) { - final int m_size = message_legs.size(); - final int f_size = filter_legs.size(); + private static int[] findPermute(List message_legs, List filter_legs, ComparatorSettings settings) { + int m_size = message_legs.size(); + int f_size = filter_legs.size(); // cache for compare(msg[i], filter[j]) - final Boolean[][] equality = new Boolean[m_size][f_size]; + Boolean[][] equality = new Boolean[m_size][f_size]; // Mapping of legs: order[i]-th leg should be i-th in resulting list int[] permute = new int[m_size]; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/MessageCount.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/MessageCount.java index edea6bc6..243e6c9d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/MessageCount.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/MessageCount.java @@ -54,15 +54,15 @@ enum Operation { less("<"), lessOrEquals("<="); - private String value; + private final String value; - private Operation(String s) + Operation(String s) { this.value = s; } public String getValue() { - return this.value; + return value; } } @@ -88,12 +88,24 @@ public static MessageCount fromString(String value) { MessageCount mc; - if ((mc = parse(value, Operation.equals)) != null) return mc; - if ((mc = parse(value, Operation.notEquals)) != null) return mc; - if ((mc = parse(value, Operation.greaterOrEquals)) != null) return mc; - if ((mc = parse(value, Operation.greater)) != null) return mc; - if ((mc = parse(value, Operation.lessOrEquals)) != null) return mc; - if ((mc = parse(value, Operation.less)) != null) return mc; + if((mc = parse(value, Operation.equals)) != null) { + return mc; + } + if((mc = parse(value, Operation.notEquals)) != null) { + return mc; + } + if((mc = parse(value, Operation.greaterOrEquals)) != null) { + return mc; + } + if((mc = parse(value, Operation.greater)) != null) { + return mc; + } + if((mc = parse(value, Operation.lessOrEquals)) != null) { + return mc; + } + if((mc = parse(value, Operation.less)) != null) { + return mc; + } if (isInterval(value)){ Range range = Range.newInstance(value); return new MessageCount(range); @@ -101,7 +113,7 @@ public static MessageCount fromString(String value) { try { int i = Integer.parseInt(value); if(i >= 0) { - mc = new MessageCount(i, Operation.equals); + return new MessageCount(i, Operation.equals); } } catch (NumberFormatException ignore){} @@ -145,11 +157,11 @@ private static MessageCount parse(String s, Operation op) { * @return count or 0, if input value is interval */ public int getCount() { - return this.count; + return count; } public Operation getOperation() { - return this.operation; + return operation; } /** @@ -160,19 +172,19 @@ public Operation getOperation() { public boolean checkInt(int i) { if(range == null) { - switch (this.operation) { + switch(operation) { case equals: - return i == this.count; + return i == count; case greater: - return i > this.count; + return i > count; case greaterOrEquals: - return i >= this.count; + return i >= count; case less: - return i < this.count; + return i < count; case lessOrEquals: - return i <= this.count; + return i <= count; case notEquals: - return i != this.count; + return i != count; default: return false; } @@ -184,10 +196,6 @@ public boolean checkInt(int i) @Override public String toString() { - if(range == null){ - return (this.operation != Operation.equals ? operation.getValue() : "") + this.count; - } else{ - return range.toString(); - } + return range == null ? (operation != Operation.equals ? operation.getValue() : "") + count : range.toString(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/StaticUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/StaticUtil.java index f0d37426..19735831 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/StaticUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/scriptutil/StaticUtil.java @@ -15,6 +15,9 @@ ******************************************************************************/ package com.exactpro.sf.aml.scriptutil; +import static com.exactpro.sf.aml.scriptutil.ExpressionResult.EXPRESSION_RESULT_FALSE; +import static com.exactpro.sf.aml.scriptutil.ExpressionResult.create; + import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; @@ -40,9 +43,6 @@ import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.comparison.Convention; -import com.exactpro.sf.util.AbstractBugsChecker; -import com.exactpro.sf.util.FieldKnownBugException; -import com.exactpro.sf.util.KnownBugException; import com.exactpro.sf.util.LRUMap; import com.google.common.primitives.Doubles; import com.google.common.primitives.Floats; @@ -258,7 +258,7 @@ public MvelFilter(long line, String column, String condition, Map vars = new HashMap<>(this.variables); + Map vars = new HashMap<>(variables); vars.put("x", value); try { Object obj = MVEL.executeExpression(compiledCondition, vars); @@ -266,7 +266,7 @@ public ExpressionResult validate(Object value) { IKnownBug knownBug = (IKnownBug) obj; return knownBug.validate(value); } else if (obj instanceof Boolean) { - return ExpressionResult.create((boolean) obj); + return create((boolean)obj); } else if (obj instanceof ExpressionResult) { return (ExpressionResult) obj; } @@ -340,7 +340,7 @@ private String evaluateCondition(long line, String column, String condition, Map @Override public Object getValue() { - throw new MvelException(line, column, "Cannot get value from " + this.getClass().getSimpleName()); + throw new MvelException(line, column, "Cannot get value from " + getClass().getSimpleName()); } @Override @@ -360,7 +360,7 @@ public NullFilter(long line, String column) { @Override public ExpressionResult validate(Object value) { - return ExpressionResult.create(value == null); + return create(value == null); } @Override @@ -375,7 +375,7 @@ public String getCondition(Object value) { @Override public Object getValue() { - throw new MvelException(line, column, "Cannot get value from " + this.getClass().getSimpleName()); + throw new MvelException(line, column, "Cannot get value from " + getClass().getSimpleName()); } @Override @@ -400,7 +400,7 @@ public NotNullFilter(long line, String column) { @Override public ExpressionResult validate(Object value) { - return ExpressionResult.create(value != null); + return create(value != null); } @Override @@ -415,7 +415,7 @@ public String getCondition(Object value) { @Override public Object getValue() { - throw new MvelException(line, column, "Cannot get value from " + this.getClass().getSimpleName()); + throw new MvelException(line, column, "Cannot get value from " + getClass().getSimpleName()); } @Override @@ -444,7 +444,7 @@ public KnownBugFilter(long line, String column, IKnownBug checkable) { @Override public ExpressionResult validate(Object value) { try { - return this.knownBug.validate(value); + return knownBug.validate(value); } catch (RuntimeException e) { throw new MvelException(line, column, e); } @@ -452,7 +452,7 @@ public ExpressionResult validate(Object value) { @Override public String getCondition() { - return this.knownBug.getCondition(); + return knownBug.getCondition(); } @Override @@ -462,7 +462,7 @@ public String getCondition(Object value) { @Override public Object getValue() throws MvelException { - throw new MvelException(line, column, "Cannot get value from " + this.getClass().getSimpleName()); + throw new MvelException(line, column, "Cannot get value from " + getClass().getSimpleName()); } @Override @@ -487,11 +487,11 @@ public SimpleMvelFilter(long line, String column, String simpleCondition, Map(variables); - if((this.value instanceof Double && !Doubles.isFinite((Double)this.value)) - || (this.value instanceof Float && !Floats.isFinite((Float)this.value))) { + if((value instanceof Double && !Doubles.isFinite((Double)value)) + || (value instanceof Float && !Floats.isFinite((Float)value))) { expression = "Objects.equals(x, {})"; } @@ -504,7 +504,7 @@ public SimpleMvelFilter(long line, String column, String simpleCondition, Map vars = new HashMap<>(this.variables); + Map vars = new HashMap<>(variables); vars.put("x", value); @@ -523,7 +523,7 @@ public ExpressionResult validate(Object value) { logger.debug("variable: {}, value: {}, class: {}", var.getKey(), val, cls); } } - return ExpressionResult.create(MVEL.executeExpression(compiledCondition, vars, Boolean.class)); + return create(MVEL.executeExpression(compiledCondition, vars, Boolean.class)); } catch(PropertyAccessException e) { throw processPropertyAccessException(line, column, e); } catch (Exception e) { @@ -574,11 +574,7 @@ public MessageCountFilter(long line, MessageCount count) { @Override public ExpressionResult validate(Object value) { - if(value instanceof Integer) { - return ExpressionResult.create(count.checkInt((int)value)); - } - - return ExpressionResult.EXPRESSION_RESULT_FALSE; + return value instanceof Integer ? create(count.checkInt((int)value)) : EXPRESSION_RESULT_FALSE; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java index 70018478..e039f711 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLConverterVisitor.java @@ -27,7 +27,6 @@ import java.util.Map; import java.util.Set; -import com.exactpro.sf.aml.reader.struct.ExecutionMode; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -50,6 +49,7 @@ import com.exactpro.sf.aml.generator.matrix.Value; import com.exactpro.sf.aml.reader.struct.AMLBlock; import com.exactpro.sf.aml.reader.struct.AMLElement; +import com.exactpro.sf.aml.reader.struct.ExecutionMode; import com.exactpro.sf.aml.scriptutil.MessageCount; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.configuration.suri.SailfishURI; @@ -106,7 +106,7 @@ public void visit(AMLElement element) throws AMLException { } } else if(settings.isSuppressAskForContinue() && AMLLangConst.ASK_FOR_CONTINUE_ACTION_URI.matches(actionURI)) { return; - } else if(JavaStatement.DEFINE_HEADER == JavaStatement.value(actionURI)) { + } else if(JavaStatement.value(actionURI) == JavaStatement.DEFINE_HEADER) { return; } @@ -234,7 +234,7 @@ public void visit(AMLElement element) throws AMLException { addError(element, column, "Invalid value: %s", cellValue); break; } - } else if(JavaStatement.BEGIN_LOOP == JavaStatement.value(actionURI)) { + } else if(JavaStatement.value(actionURI) == JavaStatement.BEGIN_LOOP) { if(!isNumeric(cellValue) && !isFunction(cellValue) && !isReference(cellValue) && !isStaticVariableReference(cellValue)) { addError(element, column, "Invalid value: %s", cellValue); break; @@ -284,8 +284,8 @@ public void visit(AMLElement element) throws AMLException { if(cellValue.startsWith(AMLLangConst.SMART_CHECKPOINT_PREFIX)) { tempValue = cellValue.substring(AMLLangConst.SMART_CHECKPOINT_PREFIX.length()); } - } else if(JavaStatement.DEFINE_SERVICE_NAME == JavaStatement.value(actionURI)) { - if(AMLLangUtil.isStaticVariableReference(cellValue)) { + } else if(JavaStatement.value(actionURI) == JavaStatement.DEFINE_SERVICE_NAME) { + if(isStaticVariableReference(cellValue)) { tempValue = AMLLangUtil.getStaticVariableName(cellValue); } else { addError(element, column, "Invalid value: %s (expected: %sname%s)", cellValue, AMLLangConst.BEGIN_STATIC, AMLLangConst.END_STATIC); @@ -309,7 +309,7 @@ public void visit(AMLElement element) throws AMLException { case ServiceName: tempValue = cellValue; - if(AMLLangUtil.isStaticVariableReference(cellValue)) { + if(isStaticVariableReference(cellValue)) { tempValue = AMLLangUtil.getStaticVariableName(cellValue); } @@ -359,7 +359,7 @@ public void visit(AMLElement element) throws AMLException { break; } } catch(NumberFormatException e) { - if(AMLLangUtil.isStaticVariableReference(cellValue)) { + if(isStaticVariableReference(cellValue)) { String variableName = AMLLangUtil.getStaticVariableName(cellValue); if(!validateVariableName(element, column, variableName)) { break; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLHeadersVisitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLHeadersVisitor.java index 17adee71..6e36d962 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLHeadersVisitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/AMLHeadersVisitor.java @@ -29,7 +29,7 @@ public class AMLHeadersVisitor implements IAMLElementVisitor { private final List mainHeaders; - private AMLElement lastDefineHeader = null; + private AMLElement lastDefineHeader; public AMLHeadersVisitor(List mainHeaders) { this.mainHeaders = new ArrayList<>(mainHeaders); @@ -52,8 +52,9 @@ public void visit(AMLElement element) throws AMLException { break; } } - if (isNewField) + if(isNewField) { mainHeaders.add(new SimpleCell(fieldCaption)); + } } else { if (!lastDefineHeader.getCells().keySet().contains(fieldCaption)) { lastDefineHeader.setValue(fieldCaption, fieldCaption); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/IAMLElementVisitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/IAMLElementVisitor.java index a16edb21..09abf737 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/IAMLElementVisitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/aml/visitors/IAMLElementVisitor.java @@ -20,6 +20,6 @@ import com.exactpro.sf.aml.reader.struct.AMLElement; public interface IAMLElementVisitor { - public void visit(AMLElement element) throws AMLException; - public void visit(AMLBlock block) throws AMLException; + void visit(AMLElement element) throws AMLException; + void visit(AMLBlock block) throws AMLException; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/BigButtonSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/BigButtonSettings.java index 424b2124..4a94b7b9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/BigButtonSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/BigButtonSettings.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; @@ -134,19 +135,19 @@ public List getFinalRecipients(StatusType status) { if (StringUtils.isNotEmpty(emailRecipients)) { emailRecipients.append(EMailUtil.DELIMITER); } - emailRecipients.append(this.emailFailedRecipients); + emailRecipients.append(emailFailedRecipients); break; case CONDITIONALLY_PASSED: if (StringUtils.isNotEmpty(emailRecipients)) { emailRecipients.append(EMailUtil.DELIMITER); } - emailRecipients.append(this.emailCondPassedRecipients); + emailRecipients.append(emailCondPassedRecipients); break; case PASSED: if (StringUtils.isNotEmpty(emailRecipients)) { emailRecipients.append(EMailUtil.DELIMITER); } - emailRecipients.append(this.emailPassedRecipients); + emailRecipients.append(emailPassedRecipients); break; } @@ -160,7 +161,7 @@ public String settingsName() { @Override public void fillFromMap(Map options) throws Exception { - for (Map.Entry entry : options.entrySet()) { + for(Entry entry : options.entrySet()) { if (entry.getKey().startsWith(STORAGE_EMAIL_PREFIX)) { BeanUtils.setProperty(this, entry.getKey().replace(STORAGE_EMAIL_PREFIX, ""), entry.getValue()); } else if (entry.getKey().startsWith(STORAGE_PREFIX)) { @@ -175,7 +176,7 @@ public Map toMap() throws Exception { Map description = BeanUtils.describe(this); Map result = new HashMap<>(); - for (Map.Entry entry : description.entrySet()) { + for(Entry entry : description.entrySet()) { result.put(STORAGE_PREFIX + entry.getKey(), entry.getValue()); } return result; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/RegressionRunner.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/RegressionRunner.java index 88e9d74e..039333c4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/RegressionRunner.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/RegressionRunner.java @@ -19,8 +19,6 @@ import java.util.List; import java.util.concurrent.Semaphore; -import com.exactpro.sf.embedded.statistics.StatisticsService; -import com.exactpro.sf.embedded.statistics.entities.SfInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +37,8 @@ import com.exactpro.sf.configuration.workspace.WorkspaceSecurityException; import com.exactpro.sf.configuration.workspace.WorkspaceStructureException; import com.exactpro.sf.embedded.mail.EMailService; +import com.exactpro.sf.embedded.statistics.StatisticsService; +import com.exactpro.sf.embedded.statistics.entities.SfInstance; import com.exactpro.sf.services.ITaskExecutor; import com.exactpro.sf.storage.IOptionsStorage; @@ -54,19 +54,19 @@ public class RegressionRunner implements AutoCloseable { private volatile ExecutionProgressMonitor monitor; - private final static Semaphore lock = new Semaphore(1, true); + private static final Semaphore lock = new Semaphore(1, true); private volatile boolean free = true; - private volatile boolean pause = false; + private volatile boolean pause; private volatile Library library; - private volatile EMailService mailService; + private final EMailService mailService; - private volatile StatisticsService statisticsService; + private final StatisticsService statisticsService; - private BigButtonSettings settings; + private BigButtonSettings settings = new BigButtonSettings(); public RegressionRunner(ITaskExecutor taskExecutor, IWorkspaceDispatcher workspaceDispatcher, EMailService mailService, @@ -75,10 +75,9 @@ public RegressionRunner(ITaskExecutor taskExecutor, IWorkspaceDispatcher workspa this.taskExecutor = taskExecutor; this.mailService = mailService; this.statisticsService = statisticsService; - this.settings = new BigButtonSettings(); try { - this.settings.fillFromMap(optionsStorage.getAllOptions()); + settings.fillFromMap(optionsStorage.getAllOptions()); } catch (Exception e) { logger.error(e.getMessage(), e); } @@ -100,9 +99,9 @@ public void init() { private void cleanup() { - if(this.executorClients != null) { + if(executorClients != null) { - for(ExecutorClient client : this.executorClients) { + for(ExecutorClient client : executorClients) { client.cleanExecutorEnvironment(); client.tearDown(); } @@ -115,7 +114,7 @@ private void startInitThread(Library library) { RunInitTask task = new RunInitTask(library); - this.taskExecutor.addTask(task); + taskExecutor.addTask(task); } private void fillQueue(CombineQueue listsQueue) { @@ -142,7 +141,7 @@ public void reset() { try { - if(!this.free) { + if(!free) { throw new IllegalStateException("Reset not allowed in this state"); } @@ -169,7 +168,7 @@ public void prepare(LibraryImportResult importResult) { try { - if(!free || this.library != null) { + if(!free || library != null) { throw new IllegalStateException("Prepare not allowed in this state"); } @@ -228,14 +227,14 @@ public void run() { if(!free) { throw new IllegalStateException("Runner is already busy"); } - - if(this.library == null) { + + if(library == null) { throw new IllegalStateException("Library was not prepared"); } this.free = false; - - this.monitor.preparing(); + + monitor.preparing(); startInitThread(library); @@ -250,13 +249,13 @@ public void run() { } public ProgressView getProgressView(int inQueueLimit, int outQueueLimit) { - - return this.monitor.getCurrentProgressView(inQueueLimit, outQueueLimit); + + return monitor.getCurrentProgressView(inQueueLimit, outQueueLimit); } public void interrupt(String message) { - this.monitor.interrupt(message); + monitor.interrupt(message); } public boolean isFree() { @@ -282,33 +281,33 @@ public IWorkspaceDispatcher getWorkspaceDispatcher() { } private class RunInitTask implements Runnable { - - private Library library; + + private final Library library; public RunInitTask(Library library) { this.library = library; } private void checkReportsFolder() { - - if(this.library.getReportsFolder() == null) { + + if(library.getReportsFolder() == null) { return; } try { - RegressionRunner.this.workspaceDispatcher.createFolder(FolderType.REPORT, this.library.getReportsFolder()); + workspaceDispatcher.createFolder(FolderType.REPORT, library.getReportsFolder()); } catch (WorkspaceStructureException | WorkspaceSecurityException e) { throw new RuntimeException("Reports directory not created", e); } } private boolean registerTags(List clients) { - - if(this.library.getTagList() == null) { + + if(library.getTagList() == null) { return true; } - - List tags = this.library.getTagList().getTags(); + + List tags = library.getTagList().getTags(); if (tags.isEmpty()) { return true; @@ -385,7 +384,7 @@ public BigButtonSettings getSettings(){ } public SfInstance getCurrentSfInstance() { - return this.statisticsService.getThisSfInstance(); + return statisticsService.getThisSfInstance(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/CombineQueue.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/CombineQueue.java index 821d7f89..94585c97 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/CombineQueue.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/CombineQueue.java @@ -28,7 +28,7 @@ public class CombineQueue { private final Map> exeutorToQueue = new HashMap<>(); public void register(String name) { - if (this.exeutorToQueue.put(name, new LinkedBlockingQueue<>()) != null) { + if(exeutorToQueue.put(name, new LinkedBlockingQueue<>()) != null) { throw new IllegalArgumentException("Name '"+ name +"' is already registered"); } } @@ -51,7 +51,7 @@ public T poll(long timeout, TimeUnit unit) throws InterruptedException { private BlockingQueue getNamedOrCommonQueue(String name) { BlockingQueue result = getQueue(name); - return result.isEmpty() ? this.commonQueue : result; + return result.isEmpty() ? commonQueue : result; } private BlockingQueue getQueue(String name) { @@ -63,7 +63,7 @@ private BlockingQueue getQueue(String name) { throw new IllegalArgumentException("Name '"+ name +"' is unregistered"); } } - - return this.commonQueue; + + return commonQueue; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/DownloadsCompleteTask.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/DownloadsCompleteTask.java index a3537e00..e1cb5f3a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/DownloadsCompleteTask.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/DownloadsCompleteTask.java @@ -17,7 +17,7 @@ public class DownloadsCompleteTask implements Runnable { - private ExecutionProgressMonitor monitor; + private final ExecutionProgressMonitor monitor; public DownloadsCompleteTask(ExecutionProgressMonitor monitor) { @@ -27,8 +27,8 @@ public DownloadsCompleteTask(ExecutionProgressMonitor monitor) { @Override public void run() { - - this.monitor.reportsProcessingFinished(); + + monitor.reportsProcessingFinished(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionProgressMonitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionProgressMonitor.java index 9c7c0c5a..7e38308d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionProgressMonitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionProgressMonitor.java @@ -15,20 +15,6 @@ ******************************************************************************/ package com.exactpro.sf.bigbutton.execution; -import com.exactpro.sf.SFAPIClient; -import com.exactpro.sf.bigbutton.RegressionRunner; -import com.exactpro.sf.bigbutton.importing.ErrorType; -import com.exactpro.sf.bigbutton.importing.ImportError; -import com.exactpro.sf.bigbutton.importing.LibraryImportResult; -import com.exactpro.sf.bigbutton.library.Executor; -import com.exactpro.sf.bigbutton.library.Library; -import com.exactpro.sf.bigbutton.library.Script; -import com.exactpro.sf.bigbutton.library.ScriptList; -import com.exactpro.sf.scriptrunner.StatusType; -import com.exactpro.sf.embedded.statistics.entities.SfInstance; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; @@ -38,24 +24,40 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.exactpro.sf.SFAPIClient; +import com.exactpro.sf.bigbutton.RegressionRunner; +import com.exactpro.sf.bigbutton.importing.ErrorType; +import com.exactpro.sf.bigbutton.importing.ImportError; +import com.exactpro.sf.bigbutton.importing.LibraryImportResult; +import com.exactpro.sf.bigbutton.library.Executor; +import com.exactpro.sf.bigbutton.library.Library; +import com.exactpro.sf.bigbutton.library.Script; +import com.exactpro.sf.bigbutton.library.ScriptList; +import com.exactpro.sf.embedded.statistics.entities.SfInstance; +import com.exactpro.sf.scriptrunner.StatusType; + public class ExecutionProgressMonitor { private static final Logger logger = LoggerFactory.getLogger(ExecutionProgressMonitor.class); private final List allExecutors = new ArrayList<>(); - private List enqueued = new ArrayList<>(); + private final List enqueued = new ArrayList<>(); - private Map> executed = new HashMap<>(); + private final Map> executed = new HashMap<>(); - private List rejected = new ArrayList<>(); + private final List rejected = new ArrayList<>(); - private Map running = new HashMap<>(); + private final Map running = new HashMap<>(); private long totalListsCount; @@ -67,7 +69,7 @@ public class ExecutionProgressMonitor { private final RegressionRunner runner; - private volatile boolean finished = false; + private volatile boolean finished; private BigButtonExecutionStatus status = BigButtonExecutionStatus.Inactive; @@ -75,15 +77,15 @@ public class ExecutionProgressMonitor { private String errorText; - private List warns = new ArrayList<>(); + private final List warns = new ArrayList<>(); private ExecutionReportExporter reportExporter; - private int numExecutorsInError = 0; + private int numExecutorsInError; private ExecutorService taskExecutor; - private BbExecutionStatistics executionStatistics = new BbExecutionStatistics(); + private final BbExecutionStatistics executionStatistics = new BbExecutionStatistics(); private ExecutorsStatusChecker statusChecker; @@ -112,23 +114,23 @@ private void doTearDown() { writeReport(); identifyExecutionStatus(); - if(this.reportExporter != null) { - this.reportExporter.writeCompleted(); + if(reportExporter != null) { + reportExporter.writeCompleted(); } - if(this.taskExecutor != null) { - this.taskExecutor.shutdown(); + if(taskExecutor != null) { + taskExecutor.shutdown(); } - if(this.statusChecker != null) { - this.statusChecker.stop(); + if(statusChecker != null) { + statusChecker.stop(); } - this.executionStatistics.setFinished(new Date()); + executionStatistics.setFinished(new Date()); this.finished = true; this.importErrors = null; try { - this.runner.close(); + runner.close(); } catch (Exception e) { logger.error("Error while closing RegressionRunner", e); } @@ -142,7 +144,7 @@ public synchronized void preparing() { public synchronized void ready(LibraryImportResult importResult) { - if (this.status != BigButtonExecutionStatus.Error) { + if(status != BigButtonExecutionStatus.Error) { this.status = BigButtonExecutionStatus.Ready; } @@ -150,14 +152,14 @@ public synchronized void ready(LibraryImportResult importResult) { this.importErrors = new ConcurrentHashMap<>(); - this.importErrors.put(ErrorType.COMMON, importResult.getCommonErrors()); - this.importErrors.put(ErrorType.GLOBALS, importResult.getGlobalsErrors()); - this.importErrors.put(ErrorType.EXECUTOR, importResult.getExecutorErrors()); - this.importErrors.put(ErrorType.SCRIPTLIST, importResult.getScriptListErrors()); + importErrors.put(ErrorType.COMMON, importResult.getCommonErrors()); + importErrors.put(ErrorType.GLOBALS, importResult.getGlobalsErrors()); + importErrors.put(ErrorType.EXECUTOR, importResult.getExecutorErrors()); + importErrors.put(ErrorType.SCRIPTLIST, importResult.getScriptListErrors()); this.statusChecker = new ExecutorsStatusChecker(); - Thread statusCheckerThread = new Thread(this.statusChecker, "BB slaves status checker"); + Thread statusCheckerThread = new Thread(statusChecker, "BB slaves status checker"); statusCheckerThread.setDaemon(true); statusCheckerThread.start(); @@ -167,8 +169,8 @@ public synchronized void started() { try { - this.executionStatistics.setStarted(new Date()); - this.taskExecutor = Executors.newFixedThreadPool(this.allExecutors.size()); + executionStatistics.setStarted(new Date()); + this.taskExecutor = Executors.newFixedThreadPool(allExecutors.size()); this.reportExporter = new ExecutionReportExporter(); } catch (IOException e) { @@ -187,12 +189,12 @@ public synchronized void error(String text) { } public synchronized void warn(String text) { - this.warns.add(text); + warns.add(text); } public synchronized void listEnqueued(ScriptList list) { - this.enqueued.add(list); + enqueued.add(list); this.totalListsCount++; @@ -210,11 +212,11 @@ public synchronized void listTaken(ScriptList list, Executor executor) { for(int i = enqueued.size() -1; i >= 0; i--) { - if(this.enqueued.get(i).equals(list) ) { + if(enqueued.get(i).equals(list)) { - this.enqueued.remove(i); + enqueued.remove(i); - this.running.put(executor, list); + running.put(executor, list); return; @@ -228,24 +230,24 @@ public synchronized void listTaken(ScriptList list, Executor executor) { public synchronized void listExecuted(Executor executor, ScriptList list) { - this.running.remove(executor); + running.remove(executor); - if(!this.executed.containsKey(executor)) { - this.executed.put(executor, new ArrayList()); + if(!executed.containsKey(executor)) { + executed.put(executor, new ArrayList()); } - this.executed.get(executor).add(0, list); + executed.get(executor).add(0, list); this.executedListsCount++; - if(this.finished) { + if(finished) { return; } - if(this.executedListsCount == this.totalListsCount) { + if(executedListsCount == totalListsCount) { this.status = BigButtonExecutionStatus.DownloadingReports; //doTearDown(); - this.taskExecutor.submit(new DownloadsCompleteTask(this)); + taskExecutor.submit(new DownloadsCompleteTask(this)); } @@ -282,7 +284,7 @@ public synchronized ProgressView getCurrentProgressView(int inQueueLimit, int ou Map> executedView = new HashMap<>(); Map executedSizes = new HashMap<>(); - for(Map.Entry> entry : this.executed.entrySet()) { + for(Entry> entry : executed.entrySet()) { List fullList = entry.getValue(); List listView = getLimitedListView(fullList, outQueueLimit); @@ -296,7 +298,7 @@ public synchronized ProgressView getCurrentProgressView(int inQueueLimit, int ou result.setExecuted(executedView); result.setNumExecuted(executedSizes); - result.setRunning(new HashMap<>(this.running)); + result.setRunning(new HashMap<>(running)); result.setCurrentTotalProgressPercent( RegressionRunnerUtils.calcPercent(executedScriptsCount, totalScriptsCount)); @@ -307,23 +309,23 @@ public synchronized ProgressView getCurrentProgressView(int inQueueLimit, int ou result.setStatus(status); result.setExecutionStatus(executionStatus); - result.setErrorText(this.errorText); - result.setWarns(this.warns); + result.setErrorText(errorText); + result.setWarns(warns); if(library != null) { result.setLibraryFileName(library.getDescriptorFileName()); } result.setLibrary(library); - result.setImportErrors(this.importErrors); + result.setImportErrors(importErrors); - if(this.finished && this.reportExporter != null) { - result.setReportFile(this.reportExporter.getFile()); + if(finished && reportExporter != null) { + result.setReportFile(reportExporter.getFile()); } - if(this.finished) { + if(finished) { - result.setExecutionStatistics(new BbExecutionStatistics(this.executionStatistics)); + result.setExecutionStatistics(new BbExecutionStatistics(executionStatistics)); } @@ -335,7 +337,7 @@ public synchronized void executorClientEncounteredError(ExecutorClient client) { this.numExecutorsInError++; - if(numExecutorsInError == this.allExecutors.size()) { + if(numExecutorsInError == allExecutors.size()) { error("All executors gone to 'Error' state"); } @@ -343,8 +345,8 @@ public synchronized void executorClientEncounteredError(ExecutorClient client) { public synchronized void interrupt(String message) { - if(this.status == BigButtonExecutionStatus.Inactive - || this.status == BigButtonExecutionStatus.Finished) { + if(status == BigButtonExecutionStatus.Inactive + || status == BigButtonExecutionStatus.Finished) { return; @@ -375,26 +377,24 @@ public synchronized void scriptExecuted(Script script, int scriptRunId, Executor ScriptExecutionStatistics statistics = script.getStatistics(); - this.executionStatistics.incNumPassedTcs(statistics.getNumPassed()); - this.executionStatistics.incNumCondPassedTcs(statistics.getNumConditionallyPassed()); - this.executionStatistics.incNumFailedTcs(statistics.getNumFailed()); + executionStatistics.incNumPassedTcs(statistics.getNumPassed()); + executionStatistics.incNumCondPassedTcs(statistics.getNumConditionallyPassed()); + executionStatistics.incNumFailedTcs(statistics.getNumFailed()); if (statistics.isExecutionFailed()) { - this.executionStatistics.incNumInitFailed(); + executionStatistics.incNumInitFailed(); } - if(this.finished) { + if(finished) { return; } - SFAPIClient apiClient = null; - - apiClient = new SFAPIClient(URI.create(executor.getHttpUrl() + "/sfapi").normalize().toString()); + SFAPIClient apiClient = new SFAPIClient(URI.create(executor.getHttpUrl() + "/sfapi").normalize().toString()); - SfInstance currentSfInstance = this.runner.getCurrentSfInstance(); + SfInstance currentSfInstance = runner.getCurrentSfInstance(); Long sfCurrentID = currentSfInstance == null ? null : currentSfInstance.getId(); - ReportDownloadTask task = new ReportDownloadTask(this.runner.getWorkspaceDispatcher(), scriptRunId, reportsFolder, + ReportDownloadTask task = new ReportDownloadTask(runner.getWorkspaceDispatcher(), scriptRunId, reportsFolder, apiClient, downloadNeded, sfCurrentID); taskExecutor.submit(task); @@ -407,7 +407,7 @@ public synchronized void rejectScriptList(ScriptList list) { for (Script script : list.getScripts()) { script.getStatistics().setStatus("REJECTED"); } - this.rejected.add(list); + rejected.add(list); } public List getAllExecutors() { @@ -471,7 +471,7 @@ private boolean pingUrl(URI url, int timeout) { connection.setReadTimeout(timeout); connection.setRequestMethod("HEAD"); int responseCode = connection.getResponseCode(); - return (200 <= responseCode && responseCode <= 399); + return responseCode >= 200 && responseCode <= 399; } catch (IOException e) { return false; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionReportExporter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionReportExporter.java index 45094d3a..b0b5d8f9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionReportExporter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutionReportExporter.java @@ -15,22 +15,22 @@ ******************************************************************************/ package com.exactpro.sf.bigbutton.execution; +import java.io.File; +import java.io.IOException; + import com.csvreader.CsvWriter; import com.exactpro.sf.bigbutton.library.Script; import com.exactpro.sf.bigbutton.library.ScriptList; -import java.io.File; -import java.io.IOException; - public class ExecutionReportExporter { - private static final String[] headers = new String[] { "Script List", "Status", "Num. Passed", "Num. Cond. Passed", "Num. Failed" }; - - private File resultFile; - - private CsvWriter writer; + private static final String[] headers = { "Script List", "Status", "Num. Passed", "Num. Cond. Passed", "Num. Failed" }; + + private final File resultFile; + + private final CsvWriter writer; - private boolean closed = false; + private boolean closed; public ExecutionReportExporter() throws IOException { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutorClient.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutorClient.java index 3081af70..a14a3744 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutorClient.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ExecutorClient.java @@ -48,6 +48,7 @@ import org.slf4j.LoggerFactory; import com.exactpro.sf.SFAPIClient; +import com.exactpro.sf.Service.Status; import com.exactpro.sf.ServiceImportResult; import com.exactpro.sf.bigbutton.BigButtonSettings; import com.exactpro.sf.bigbutton.RegressionRunner; @@ -75,6 +76,7 @@ import com.exactpro.sf.scriptrunner.TestScriptDescription; import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptStatus; import com.exactpro.sf.testwebgui.restapi.xml.XmlMatrixUploadResponse; +import com.exactpro.sf.testwebgui.restapi.xml.XmlResponse; import com.exactpro.sf.testwebgui.restapi.xml.XmlTestScriptShortReport; import com.exactpro.sf.testwebgui.restapi.xml.XmlTestscriptActionResponse; import com.exactpro.sf.util.EMailUtil; @@ -106,10 +108,10 @@ public class ExecutorClient { private ClientWorker worker; private final Set errorText = Collections.synchronizedSet(new HashSet()); - - private ObjectMapper mapper = new ObjectMapper(); - - private volatile Boolean executorReady = null; + + private final ObjectMapper mapper = new ObjectMapper(); + + private volatile Boolean executorReady; private final Map executorServicesUploaded = new LinkedHashMap<>(); @@ -148,7 +150,7 @@ public void toErrorState(String errMessage) { String execErrMessage = String.format("Executor \"%s\" : error. Cause: %s", executor.getName(), errMessage); logger.error(execErrMessage); - this.errorText.add(errMessage); + errorText.add(errMessage); this.state = ExecutorState.Error; monitor.executorClientEncounteredError(this); monitor.warn(execErrMessage); @@ -161,7 +163,7 @@ public void toErrorStatePreparing(ImportError errMessage) { logger.error(String.format("Executor \"%s\" error because of parsing errors", executor.getName())); for (ImportError error : errMessage.getCause()) { - this.errorText.add(error.getMessage()); + errorText.add(error.getMessage()); } this.state = ExecutorState.Error; monitor.executorClientEncounteredError(this); @@ -172,20 +174,20 @@ public void toWarnState(Throwable t) { String message = String.format("Executor \"%s\" : error. Cause: %s", executor.getName(), RegressionRunnerUtils.createErrorText(t)); logger.warn(message); - this.errorText.add(RegressionRunnerUtils.createErrorText(t)); + errorText.add(RegressionRunnerUtils.createErrorText(t)); monitor.warn(message); } public void start() { - - if(this.apiClient == null) { - createApiClient(); + + if(apiClient == null) { + createApiClient(); } this.worker = new ClientWorker(); - - Thread workerThread = new Thread(worker, "BB Executor " + this.executor.getName()); + + Thread workerThread = new Thread(worker, "BB Executor " + executor.getName()); workerThread.setDaemon(true); @@ -195,16 +197,16 @@ public void start() { private void createApiClient() { try { - this.apiClient = new SFAPIClient(URI.create(this.executor.getHttpUrl() + "/sfapi").normalize().toString()); + this.apiClient = new SFAPIClient(URI.create(executor.getHttpUrl() + "/sfapi").normalize().toString()); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } public void tearDown() { - - if (this.worker != null) { - this.worker.stop(); + + if(worker != null) { + worker.stop(); } } @@ -214,7 +216,7 @@ public ExecutorState getState() { } public boolean prepareExecutor(String xmlConfig) { - if (this.state == ExecutorState.Error) { + if(state == ExecutorState.Error) { return false; } try { @@ -262,7 +264,7 @@ private void uploadService(Service service, Map uploadResult) t for (ServiceImportResult result : importResult) { - if (result.getStatus().equals(com.exactpro.sf.Service.Status.ERROR)) { + if(result.getStatus() == Status.ERROR) { String errMessage = String.format("Service <%s> import failed. Cause: <%s>", service.getPath(), result.getProblem()); @@ -318,7 +320,11 @@ private void serviceCommand(Stream services, APIServiceConsumer command if(!serviceExceptions.isEmpty()) { RuntimeException e = new EPSCommonException(String.format("Command '%s' was not executed for services: %s", commandName, serviceExceptions.keySet())); - serviceExceptions.values().forEach(e::addSuppressed); + + for(Exception exception : serviceExceptions.values()) { + e.addSuppressed(exception); + } + throw e; } } @@ -344,8 +350,8 @@ private Set prepareExecutorServices() { } public void cleanExecutorEnvironment() { - if (this.state == ExecutorState.Error) { - logger.warn(String.format("Executor \"%s\" : can not clean environment, executor is in Error state ", this.executor.getName())); + if(state == ExecutorState.Error) { + logger.warn(String.format("Executor \"%s\" : can not clean environment, executor is in Error state ", executor.getName())); return; } try { @@ -367,20 +373,20 @@ public void registerTags(List tags) { Set knownGroups = new HashSet<>(); try { - - if(this.apiClient == null) { - createApiClient(); + + if(apiClient == null) { + createApiClient(); } for(Tag tag : tags) { - com.exactpro.sf.testwebgui.restapi.xml.XmlResponse response; + XmlResponse response; if(StringUtils.isNotEmpty(tag.getGroup())) { if(!knownGroups.contains(tag.getGroup())) { - - response = this.apiClient.registerTagGroup(tag.getGroup()); + + response = apiClient.registerTagGroup(tag.getGroup()); logger.debug("Group registration response {}: {}", response.getMessage(), response.getRootCause()); @@ -391,12 +397,12 @@ public void registerTags(List tags) { knownGroups.add(tag.getGroup()); } - - response = this.apiClient.registerTagInGroup(tag.getName(), tag.getGroup()); + + response = apiClient.registerTagInGroup(tag.getName(), tag.getGroup()); } else { - - response = this.apiClient.registerTag(tag.getName()); + + response = apiClient.registerTag(tag.getName()); } @@ -565,7 +571,7 @@ private void executeScript(Script script) throws InterruptedException { String targetReportFolder = null; if(library.getReportsFolder() != null) { - targetReportFolder = this.relativeListReportsFolder; + targetReportFolder = relativeListReportsFolder; } XmlTestscriptActionResponse response = apiClient.performMatrixAction((int)matrix.getId(), @@ -620,7 +626,7 @@ private void executeScript(Script script) throws InterruptedException { } executeOnFinishScript(script); - monitor.scriptExecuted(script, (int)scriptRunId, executor, this.relativeListReportsFolder, reportDownloadNeeded); + monitor.scriptExecuted(script, (int)scriptRunId, executor, relativeListReportsFolder, reportDownloadNeeded); apiClient.deleteMatrix((int)matrix.getId()); } @@ -645,9 +651,9 @@ private XmlTestScriptShortReport waitForScriptExecutionFinish(Script script, int while(true) { try { - - if(!this.running) { - logger.info("Invoking stop"); + + if(!running) { + logger.info("Invoking stop"); apiClient.stopTestScriptRun(id); return null; } @@ -725,7 +731,7 @@ private void runList() throws InterruptedException { for(int i =0; i< currentList.getScripts().size(); i++) {//Script script : currentList.getScripts()) { - if(!this.running) { + if(!running) { return; } @@ -751,7 +757,7 @@ private void runList() throws InterruptedException { script.setFinished(true); statistics.incNumFailed(); try { - monitor.scriptExecuted(script, 0, executor, this.relativeListReportsFolder, false); + monitor.scriptExecuted(script, 0, executor, relativeListReportsFolder, false); } catch (Exception e) { logger.error("scriptExecuted error", e); } @@ -773,13 +779,8 @@ private void runList() throws InterruptedException { } private String createRelativeListRepotsFolder() { - - if(library.getReportsFolder() == null) { - return null; - } - - return Paths.get(library.getReportsFolder(), currentList.getName()).toString(); - } + return library.getReportsFolder() == null ? null : Paths.get(library.getReportsFolder(), currentList.getName()).toString(); + } @Override public void run() { @@ -790,8 +791,8 @@ public void run() { long msTimeout = executor.getTimeout() * 1000; RuntimeException possibleEx = null; - - while(this.running) { + + while(running) { try { @@ -932,8 +933,8 @@ public void run() { } catch (IOException e) { logger.error(e.getMessage(), e); } - - if (!state.equals(ExecutorState.Error)) { + + if(state != ExecutorState.Error) { state = ExecutorState.Inactive; @@ -945,9 +946,9 @@ public void run() { private boolean restartNode() throws IOException { state = ExecutorState.Restarting; - - HttpURLConnection con = (HttpURLConnection) (new URL(executor.getDaemon().getHttpUrl() + "/" + - "restart?alias=" + executor.getDaemon().getName())).openConnection(); + + HttpURLConnection con = (HttpURLConnection)new URL(executor.getDaemon().getHttpUrl() + "/" + + "restart?alias=" + executor.getDaemon().getName()).openConnection(); con.setConnectTimeout(executor.getDaemon().getTimeout() * 1000); @@ -968,7 +969,7 @@ private void transferScriptListToAnotherNode() { script.getStatistics().setStatus("CONNECTION_FAILED"); script.getStatistics().setNumFailed(script.getStatistics().getNumFailed() + 1); try { - monitor.scriptExecuted(script, 0, executor, this.relativeListReportsFolder, false); + monitor.scriptExecuted(script, 0, executor, relativeListReportsFolder, false); } catch (Exception e) { logger.error("scriptExecuted error", e); } @@ -994,7 +995,7 @@ private void transferScriptListToAnotherNode() { script.getStatistics().setStatus("CONNECTION_FAILED"); script.getStatistics().setNumFailed(script.getStatistics().getNumFailed() + 1); try { - monitor.scriptExecuted(script, 0, executor, this.relativeListReportsFolder, false); + monitor.scriptExecuted(script, 0, executor, relativeListReportsFolder, false); } catch (Exception e) { logger.error("scriptExecuted error", e); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/RegressionRunnerUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/RegressionRunnerUtils.java index 170af42c..9efba7da 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/RegressionRunnerUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/RegressionRunnerUtils.java @@ -37,7 +37,7 @@ public class RegressionRunnerUtils { - private final static Logger logger = LoggerFactory.getLogger(RegressionRunnerUtils.class); + private static final Logger logger = LoggerFactory.getLogger(RegressionRunnerUtils.class); private RegressionRunnerUtils() { @@ -51,12 +51,7 @@ public static int calcPercent(long actual, long total) { int result = (int) ((actual * 100.0f) / total); - if (result > 100) { - return 100; - } - - return result; - + return result > 100 ? 100 : result; } public static String createErrorText(Throwable t) { @@ -80,7 +75,7 @@ public static String getStatisticsDBSettings() { dbSettings.setConnectionOptionsQuery(settings.getStorageSettings().getConnectionOptionsQuery()); dbSettings.setUsername(settings.getStorageSettings().getUsername()); dbSettings.setPassword(settings.getStorageSettings().getPassword()); - final StringBuilder xml = new StringBuilder(); + StringBuilder xml = new StringBuilder(); try { JAXBContext.newInstance(XmlStatisticsDBSettings.class).createMarshaller().marshal(dbSettings, new OutputStream() { @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ReportDownloadTask.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ReportDownloadTask.java index 7e91446d..af2b977a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ReportDownloadTask.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ReportDownloadTask.java @@ -37,13 +37,13 @@ public class ReportDownloadTask implements Runnable { private final IWorkspaceDispatcher workspaceDispatcher; - private int scriptRunId; - - private SFAPIClient apiClient; + private final int scriptRunId; + + private final SFAPIClient apiClient; private final String reportsFolderPath; - - private boolean downloadNeded; + + private final boolean downloadNeded; private final Long sfCurrentID; @@ -60,13 +60,12 @@ public ReportDownloadTask(IWorkspaceDispatcher workspaceDispatcher, int scriptRu } private FileDownloadWrapper downloadReport() throws APICallException, IOException, APIResponseException { - - FileDownloadWrapper fileDownload; - fileDownload = apiClient.getTestScriptRunReportZip(scriptRunId); + + FileDownloadWrapper fileDownload = apiClient.getTestScriptRunReportZip(scriptRunId); File reportFile; try { - reportFile = this.workspaceDispatcher.createFile(FolderType.REPORT, true, reportsFolderPath, fileDownload.getFileName()); + reportFile = workspaceDispatcher.createFile(FolderType.REPORT, true, reportsFolderPath, fileDownload.getFileName()); } catch (WorkspaceLayerException e) { throw new RuntimeException("Error while creating report file " + fileDownload.getFileName(), e); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ScriptExecutionStatistics.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ScriptExecutionStatistics.java index 8aaeeb12..d319b96b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ScriptExecutionStatistics.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/execution/ScriptExecutionStatistics.java @@ -31,7 +31,7 @@ public class ScriptExecutionStatistics implements Serializable { private volatile String status; public boolean isExecutionFailed() { - return (status != null && (status.equals("INIT_FAILED") || status.equals("RUN_FAILED") || status.equals("CONNECTION_FAILED"))); + return status != null && ("INIT_FAILED".equals(status) || "RUN_FAILED".equals(status) || "CONNECTION_FAILED".equals(status)); } public long getNumPassed() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/CsvLibraryBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/CsvLibraryBuilder.java index 3ab8b2b4..75240eae 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/CsvLibraryBuilder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/CsvLibraryBuilder.java @@ -93,19 +93,19 @@ public class CsvLibraryBuilder { private final IWorkspaceDispatcher workspaceDispatcher; - private InputStream libraryFile; + private final InputStream libraryFile; - private Library library = new Library(); + private final Library library = new Library(); private AbstractLibraryItem currentList; - private LibraryImportResult importResult = new LibraryImportResult(); + private final LibraryImportResult importResult = new LibraryImportResult(); private static final Set booleanTrue = new HashSet<>(); private static final Set booleanFalse = new HashSet<>(); - private Map executorDaemonMap = new HashMap<>(); + private final Map executorDaemonMap = new HashMap<>(); static { @@ -121,9 +121,9 @@ public class CsvLibraryBuilder { } - private ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); - private TypeReference> typeRef = new TypeReference>() {}; + private final TypeReference> typeRef = new TypeReference>() {}; public CsvLibraryBuilder(InputStream libraryFile, IWorkspaceDispatcher workspaceDispatcher, IStaticServiceManager serviceManager, IDictionaryManager dictionaryManager) { @@ -151,7 +151,7 @@ private void parseCsv() throws IOException { try { - reader = new CsvReader(this.libraryFile, Charset.forName("UTF-8")); + reader = new CsvReader(libraryFile, Charset.forName("UTF-8")); DocumentBuilder domBuilder; @@ -179,7 +179,7 @@ private void parseCsv() throws IOException { } catch(Exception e) { - this.importResult.getCommonErrors().add(new ImportError(currentRecordNumber, e.getMessage())); + importResult.getCommonErrors().add(new ImportError(currentRecordNumber, e.getMessage())); } @@ -219,7 +219,7 @@ private void postParse() { .filter(scriptList -> scriptList.getExecutor() != null) .filter(scriptList -> !executorNames.contains(scriptList.getExecutor())) .forEach(scriptList -> { - this.importResult.getCommonErrors().add(new ImportError(scriptList.getLineNumber(), + importResult.getCommonErrors().add(new ImportError(scriptList.getLineNumber(), "Unknown executor '" + scriptList.getExecutor() + "' in script list '" + scriptList.getName() + "\'")); }); @@ -328,7 +328,7 @@ private Executor parseExecutor(Map row, long lineNumber) throws result.setApiOptions( parseApiOptions(row) ); if (!StringUtils.isEmpty(daemon)) { - this.executorDaemonMap.put(result, daemon); + executorDaemonMap.put(result, daemon); } result.setLineNumber(lineNumber); @@ -361,8 +361,8 @@ private Daemon parseDaemon(Map row) throws InvalidRowException { result.setPath(path); result.setTimeout(timeout); - for (Executor executor : this.executorDaemonMap.keySet()) { - String daemonName = this.executorDaemonMap.get(executor); + for(Executor executor : executorDaemonMap.keySet()) { + String daemonName = executorDaemonMap.get(executor); if (daemonName.equals(name)) { executor.setDaemon(result); } @@ -445,15 +445,9 @@ private void parseServiceOptions(Map row, Service service) { } private StartMode parseServiceOptions(Map row) { - String tmp = row.get(CsvHeader.StartMode.getFieldKey()); - - if (StringUtils.isEmpty(tmp)) { - return null; - } - - return StartMode.valueOf(tmp); - } + return StringUtils.isEmpty(tmp) ? null : StartMode.valueOf(tmp); + } private Set parseServiceListReferences(String services) { @@ -559,37 +553,37 @@ private SfApiOptions parseApiOptions(Map row) throws InvalidRowE SfApiOptions result = new SfApiOptions(); if(row.containsKey(CsvHeader.Range.getFieldKey())) { - result.setRange((row.get(CsvHeader.Range.getFieldKey()))); + result.setRange(row.get(CsvHeader.Range.getFieldKey())); } if(row.containsKey(CsvHeader.Language.getFieldKey())) { if(StringUtils.isNotEmpty(row.get(CsvHeader.Language.getFieldKey()))) { - result.setLanguage((row.get(CsvHeader.Language.getFieldKey()))); + result.setLanguage(row.get(CsvHeader.Language.getFieldKey())); } } if(row.containsKey(CsvHeader.ContinueIfFailed.getFieldKey())) { - result.setContinueIfFailed(parseBoolean((row.get(CsvHeader.ContinueIfFailed.getFieldKey())))); + result.setContinueIfFailed(parseBoolean(row.get(CsvHeader.ContinueIfFailed.getFieldKey()))); } if(row.containsKey(CsvHeader.AutoStart.getFieldKey())) { - result.setAutoStart(parseBoolean((row.get(CsvHeader.AutoStart.getFieldKey())))); + result.setAutoStart(parseBoolean(row.get(CsvHeader.AutoStart.getFieldKey()))); } if(row.containsKey(CsvHeader.IgnoreAskForContinue.getFieldKey())) { - result.setIgnoreAskForContinue(parseBoolean((row.get(CsvHeader.IgnoreAskForContinue.getFieldKey())))); + result.setIgnoreAskForContinue(parseBoolean(row.get(CsvHeader.IgnoreAskForContinue.getFieldKey()))); } if(row.containsKey(CsvHeader.RunNetDumper.getFieldKey())){ - result.setRunNetDumper(parseBoolean((row.get(CsvHeader.RunNetDumper.getFieldKey())))); + result.setRunNetDumper(parseBoolean(row.get(CsvHeader.RunNetDumper.getFieldKey()))); } if (row.containsKey(CsvHeader.SkipOptional.getFieldKey())) { - result.setSkipOptional(parseBoolean((row.get(CsvHeader.SkipOptional.getFieldKey())))); + result.setSkipOptional(parseBoolean(row.get(CsvHeader.SkipOptional.getFieldKey()))); } if(row.containsKey(CsvHeader.Tags.getFieldKey())) { - result.setTags(parseTags((row.get(CsvHeader.Tags.getFieldKey())))); + result.setTags(parseTags(row.get(CsvHeader.Tags.getFieldKey()))); } if(row.containsKey(CsvHeader.ExecuteOnFailed.getFieldKey())){ @@ -732,25 +726,25 @@ private void handleCsvRow(Map row, long currentRecordNumber, case "library folder": - this.library.setRootFolder(parseLibraryFolder(row)); + library.setRootFolder(parseLibraryFolder(row)); break; case "reports folder": - this.library.setReportsFolder(parseLibraryFolder(row)); + library.setReportsFolder(parseLibraryFolder(row)); break; case "variable sets file": - this.library.setVariableSetsFile(parseVariableSetsFile(row)); + library.setVariableSetsFile(parseVariableSetsFile(row)); break; case "globals": - this.library.setGlobals(Optional.ofNullable(parseGlobals(row, currentRecordNumber))); + library.setGlobals(Optional.ofNullable(parseGlobals(row, currentRecordNumber))); break; @@ -758,7 +752,7 @@ private void handleCsvRow(Map row, long currentRecordNumber, ExecutorList list = new ExecutorList(); - this.library.setExecutors(list); + library.setExecutors(list); this.currentList = list; @@ -768,9 +762,9 @@ private void handleCsvRow(Map row, long currentRecordNumber, Executor executor = parseExecutor(row, currentRecordNumber); - this.currentList.addNested(executor); + currentList.addNested(executor); - this.importResult.incNumExecutors(); + importResult.incNumExecutors(); break; @@ -778,7 +772,7 @@ private void handleCsvRow(Map row, long currentRecordNumber, DaemonList daemonList = new DaemonList(); - this.library.setDaemons(daemonList); + library.setDaemons(daemonList); this.currentList = daemonList; @@ -788,7 +782,7 @@ private void handleCsvRow(Map row, long currentRecordNumber, Daemon daemon = parseDaemon(row); - this.currentList.addNested(daemon); + currentList.addNested(daemon); break; @@ -796,11 +790,11 @@ private void handleCsvRow(Map row, long currentRecordNumber, ServiceList sList = parseServiceList(row, currentRecordNumber); - if(this.library.getServiceLists().containsKey(sList.getName())) { + if(library.getServiceLists().containsKey(sList.getName())) { throw new InvalidRowException("Service List with name " + sList.getName() + " is already defined"); } - this.library.getServiceLists().put(sList.getName(), sList); + library.getServiceLists().put(sList.getName(), sList); this.currentList = sList; @@ -810,8 +804,8 @@ private void handleCsvRow(Map row, long currentRecordNumber, Service service = parseService(row, currentRecordNumber, domBuilder); - this.currentList.addNested(service); - this.importResult.incNumServices(); + currentList.addNested(service); + importResult.incNumServices(); break; @@ -819,7 +813,7 @@ private void handleCsvRow(Map row, long currentRecordNumber, ScriptList scriptList = parseScriptList(row, currentRecordNumber); - this.library.getScriptLists().add(scriptList); + library.getScriptLists().add(scriptList); this.currentList = scriptList; @@ -829,12 +823,12 @@ private void handleCsvRow(Map row, long currentRecordNumber, Script script = parseScript(row, currentRecordNumber); - this.currentList.addNested(script); + currentList.addNested(script); - this.importResult.incNumScripts(); + importResult.incNumScripts(); if (script.isRejected()) { - ScriptList current = (ScriptList) this.currentList; + ScriptList current = (ScriptList)currentList; current.addRejectCause(script.getRejectCause()); } @@ -844,11 +838,11 @@ private void handleCsvRow(Map row, long currentRecordNumber, TagList tList = parseTagList(row); - if(this.library.getTagList() != null) { + if(library.getTagList() != null) { throw new InvalidRowException("Tag List is already defined"); } - this.library.setTagList(tList); + library.setTagList(tList); this.currentList = tList; @@ -858,7 +852,7 @@ private void handleCsvRow(Map row, long currentRecordNumber, Tag tag = parseTag(row); - this.currentList.addNested(tag); + currentList.addNested(tag); break; @@ -873,23 +867,23 @@ private void doPostImportChecks() throws FileNotFoundException, WorkspaceSecurit checkServiceLists(); - if (this.library.getGlobals().isPresent()) { + if(library.getGlobals().isPresent()) { checkGlobalsServices(); } - if(this.library.getExecutors() == null || - this.library.getExecutors().getExecutors().size() == 0) { + if(library.getExecutors() == null || + library.getExecutors().getExecutors().isEmpty()) { - this.importResult.getCommonErrors().add(new ImportError(0, "At least one executor is required")); + importResult.getCommonErrors().add(new ImportError(0, "At least one executor is required")); } else { checkExecutors(); } - if(this.library.getScriptLists().size() == 0) { + if(library.getScriptLists().isEmpty()) { - this.importResult.getCommonErrors().add( + importResult.getCommonErrors().add( new ImportError(0, "No script lists defined. Nothing to execute")); } else { @@ -904,7 +898,7 @@ private void doPostImportChecks() throws FileNotFoundException, WorkspaceSecurit } private void checkServiceLists() { - for (ServiceList sList : this.library.getServiceLists().values()) { + for(ServiceList sList : library.getServiceLists().values()) { ImportError error = new ImportError(sList.getLineNumber(), String.format("Service List \"%s\" error", sList.getName())); for (Service service : sList.getServices()) { if (service.isRejected()) { @@ -918,7 +912,7 @@ private void checkServiceLists() { } private void checkGlobalsServices() { - Globals globals = this.library.getGlobals().get(); + Globals globals = library.getGlobals().get(); for (String serviceList : globals.getServiceLists()) { if (!library.getServiceLists().containsKey(serviceList)) { @@ -927,7 +921,7 @@ private void checkGlobalsServices() { importResult.getGlobalsErrors().add(error); continue; } - ServiceList sList = this.library.getServiceLists().get(serviceList); + ServiceList sList = library.getServiceLists().get(serviceList); if (sList.isRejected()) { globals.addRejectCause(sList.getRejectCause()); importResult.getGlobalsErrors().add(sList.getRejectCause()); @@ -948,14 +942,14 @@ private void checkExecutors() { if (!library.getServiceLists().containsKey(serviceList)) { exec.addRejectCause(new ImportError(0, "Service List '" + serviceList + "' is not declared")); } else { - ServiceList sList = this.library.getServiceLists().get(serviceList); + ServiceList sList = library.getServiceLists().get(serviceList); if (sList.isRejected()) { exec.addRejectCause(sList.getRejectCause()); } } } if (exec.isRejected()) { - this.importResult.getExecutorErrors().add(exec.getRejectCause()); + importResult.getExecutorErrors().add(exec.getRejectCause()); } } } @@ -969,7 +963,7 @@ private void checkScriptListServices() { if (!library.getServiceLists().containsKey(serviceList)) { list.addRejectCause(new ImportError(0, "Service List '" + serviceList + "' is not declared")); } else { - ServiceList sList = this.library.getServiceLists().get(serviceList); + ServiceList sList = library.getServiceLists().get(serviceList); if (sList.isRejected()) { list.addRejectCause(sList.getRejectCause()); } @@ -986,7 +980,7 @@ private void checkScriptListServices() { Set declaredIn = new HashSet<>(); for (String serviceList : list.getServiceLists()) { - ServiceList sList = this.library.getServiceLists().get(serviceList); + ServiceList sList = library.getServiceLists().get(serviceList); for (Service service : sList.getServices()) { if (!service.isRejected() && service.getName().equals(duplicateService)) { declaredIn.add(serviceList); @@ -999,7 +993,7 @@ private void checkScriptListServices() { } if (list.isRejected()) { - this.importResult.getScriptListErrors().add(list.getRejectCause()); + importResult.getScriptListErrors().add(list.getRejectCause()); } } @@ -1055,37 +1049,37 @@ private void copyGlobalsErrorsToExecutors() { } for(Executor exec : executorList.getExecutors()) { - if (this.library.getGlobals().isPresent() && !this.importResult.getGlobalsErrors().isEmpty()) { - ImportError globalsError = new ImportError(this.library.getGlobals().get().getLineNumber(), "Globals error"); + if(library.getGlobals().isPresent() && !importResult.getGlobalsErrors().isEmpty()) { + ImportError globalsError = new ImportError(library.getGlobals().get().getLineNumber(), "Globals error"); globalsError.addCause(importResult.getGlobalsErrors()); exec.addRejectCause(globalsError); } if (exec.isRejected()) { - this.importResult.getExecutorErrors().add(exec.getRejectCause()); + importResult.getExecutorErrors().add(exec.getRejectCause()); } } } private void checkExecutorsReady() { - int executorsReady = this.library.getExecutors().getExecutors().size(); + int executorsReady = library.getExecutors().getExecutors().size(); if (executorsReady == 0) { return; } - for (Executor executor : this.library.getExecutors().getExecutors()) { + for(Executor executor : library.getExecutors().getExecutors()) { if (executor.isRejected()) { executorsReady--; } } if (executorsReady == 0) { - this.importResult.getCommonErrors().add(new ImportError(0, "All executors gone to error state")); + importResult.getCommonErrors().add(new ImportError(0, "All executors gone to error state")); } } private ImportError checkFileExisting(String path, long lineNumber) { - String libraryPath = this.library.getRootFolder(); + String libraryPath = library.getRootFolder(); if (libraryPath != null) { @@ -1097,7 +1091,7 @@ private ImportError checkFileExisting(String path, long lineNumber) { String zipPath = relativePath.substring(0, zipIndex + 4); try { - File zipFile = this.workspaceDispatcher.getFile(FolderType.TEST_LIBRARY, zipPath); + File zipFile = workspaceDispatcher.getFile(FolderType.TEST_LIBRARY, zipPath); String restPath = relativePath.substring(zipIndex + 5); @@ -1112,7 +1106,7 @@ private ImportError checkFileExisting(String path, long lineNumber) { return new ImportError(lineNumber, "File " + zipPath + " not found"); } } else { - if (!this.workspaceDispatcher.exists(FolderType.TEST_LIBRARY, relativePath)) { + if(!workspaceDispatcher.exists(FolderType.TEST_LIBRARY, relativePath)) { return new ImportError(lineNumber, "File not exists: " + relativePath); } } @@ -1129,7 +1123,7 @@ private boolean checkFileExistingInZip(File zipFile, String entryToCheck) throws try (ZipFile zif = new ZipFile(zipFile)) { - final Enumeration entries = zif.entries(); + Enumeration entries = zif.entries(); while (entries.hasMoreElements()) { @@ -1148,16 +1142,16 @@ private boolean checkFileExistingInZip(File zipFile, String entryToCheck) throws private void mergeApiOptionsForScripts() { - SfApiOptions defaultsAndGlobals = this.library.getDefaultApiOptions(); + SfApiOptions defaultsAndGlobals = library.getDefaultApiOptions(); - if(this.library.getGlobals().isPresent()) { + if(library.getGlobals().isPresent()) { - SfApiOptions globals = this.library.getGlobals().get().getApiOptions(); + SfApiOptions globals = library.getGlobals().get().getApiOptions(); defaultsAndGlobals = defaultsAndGlobals.mergeOptions(globals); } - for(ScriptList list : this.library.getScriptLists()) { + for(ScriptList list : library.getScriptLists()) { SfApiOptions mergedListOptions = defaultsAndGlobals.mergeOptions(list.getApiOptions()); @@ -1186,9 +1180,9 @@ public LibraryImportResult buildFromCsv(String fileName) throws IOException { library.setDescriptorFileName(fileName); - this.importResult.setLibrary(library); + importResult.setLibrary(library); - return this.importResult; + return importResult; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/ImportError.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/ImportError.java index abff3dd0..e0ea3496 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/ImportError.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/ImportError.java @@ -31,7 +31,7 @@ public class ImportError implements Serializable { private String message; - private Set cause = new HashSet<>(); + private final Set cause = new HashSet<>(); public ImportError() { @@ -66,11 +66,11 @@ public Set getCause() { } public void addCause(ImportError error) { - this.cause.add(error); + cause.add(error); } public void addCause(Collection errors) { - this.cause.addAll(errors); + cause.addAll(errors); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/LibraryImportResult.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/LibraryImportResult.java index 0476db19..8271ff73 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/LibraryImportResult.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/importing/LibraryImportResult.java @@ -31,11 +31,11 @@ public class LibraryImportResult implements Serializable { @XmlTransient private Library library; - private long numExecutors = 0; + private long numExecutors; - private long numScripts = 0; + private long numScripts; - private long numServices = 0; + private long numServices; private long id; @@ -43,9 +43,9 @@ public class LibraryImportResult implements Serializable { private Set globalsErrors = new HashSet<>(); - private Set executorErrors = new HashSet<>(); + private final Set executorErrors = new HashSet<>(); - private Set scriptListErrors = new HashSet<>(); + private final Set scriptListErrors = new HashSet<>(); public void incNumExecutors() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/AbstractLibraryItem.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/AbstractLibraryItem.java index 2bcaa13b..29c75106 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/AbstractLibraryItem.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/AbstractLibraryItem.java @@ -23,8 +23,8 @@ public abstract class AbstractLibraryItem implements Serializable { private void reportNotAllowed(Object item) { throw new IllegalNestedItemException(item.getClass().getSimpleName() - + " is not allowed under " - + this.getClass().getSimpleName()); + + " is not allowed under " + + getClass().getSimpleName()); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/BigButtonAction.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/BigButtonAction.java index 81e3fd9b..7a90050d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/BigButtonAction.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/BigButtonAction.java @@ -27,7 +27,7 @@ public enum BigButtonAction { private final String action; - private BigButtonAction(String action) { + BigButtonAction(String action) { this.action = action; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/CsvHeader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/CsvHeader.java index 6039c8aa..e7227aff 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/CsvHeader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/CsvHeader.java @@ -44,7 +44,7 @@ public enum CsvHeader { private final String fieldKey; - private CsvHeader(String fieldKey) { + CsvHeader(String fieldKey) { this.fieldKey = fieldKey; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Daemon.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Daemon.java index c1d67ea8..e50d9349 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Daemon.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Daemon.java @@ -24,17 +24,12 @@ public class Daemon { private int timeout; public String getHttpUrl() { - - String result = this.path; - - if(!result.startsWith("http")) { - - result = "http://" + result; - - } - - return result; - } + + String result = path; + + return !result.startsWith("http") ? "http://" + result : result; + + } public String getName() { return name; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/DaemonList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/DaemonList.java index da1643d5..7fd67a30 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/DaemonList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/DaemonList.java @@ -25,8 +25,8 @@ public class DaemonList extends AbstractLibraryItem implements Serializable { private final List daemons = new ArrayList<>(); public void addNested(Daemon item) { - - this.daemons.add(item); + + daemons.add(item); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Executor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Executor.java index 37992aa0..05e044bd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Executor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Executor.java @@ -42,17 +42,12 @@ public class Executor implements Serializable { private String variableSet; public String getHttpUrl() { - - String result = this.path; - - if(!result.startsWith("http")) { - - result = "http://" + result; - - } - - return result; - } + + String result = path; + + return !result.startsWith("http") ? "http://" + result : result; + + } public String getName() { return name; @@ -103,14 +98,14 @@ public void setDaemon(Daemon daemon) { } public boolean isRejected() { - return this.rejectCause != null; + return rejectCause != null; } public void addRejectCause(ImportError cause) { if (!isRejected()) { - setRejectCause(new ImportError(this.lineNumber, String.format("Executor \"%s\" : error", this.name))); + setRejectCause(new ImportError(lineNumber, String.format("Executor \"%s\" : error", name))); } - this.rejectCause.addCause(cause); + rejectCause.addCause(cause); } public ImportError getRejectCause() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ExecutorList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ExecutorList.java index 3457a5b8..f9c229ce 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ExecutorList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ExecutorList.java @@ -25,8 +25,8 @@ public class ExecutorList extends AbstractLibraryItem implements Serializable { private final List executors = new ArrayList<>(); public void addNested(Executor item) { - - this.executors.add(item); + + executors.add(item); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Globals.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Globals.java index ebdfe60a..7915b6a8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Globals.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Globals.java @@ -52,11 +52,11 @@ public void setServiceLists(Set serviceLists) { } public boolean isRejected() { - return !this.rejectCause.isEmpty(); + return !rejectCause.isEmpty(); } public void addRejectCause(ImportError error) { - this.rejectCause.add(error); + rejectCause.add(error); } public Set getRejectCause() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Library.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Library.java index f75003d0..7ba51bfc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Library.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Library.java @@ -52,19 +52,16 @@ public class Library implements Serializable /*extends AbstractLibraryItem*/ { private String variableSetsFile; - private SfApiOptions defaultApiOptions; + private final SfApiOptions defaultApiOptions = new SfApiOptions(); public Library() { - - this.defaultApiOptions = new SfApiOptions(); - - this.defaultApiOptions.setLanguage("Auto"); - this.defaultApiOptions.setContinueIfFailed(false); - this.defaultApiOptions.setIgnoreAskForContinue(false); - this.defaultApiOptions.setContinueIfFailed(false); - this.defaultApiOptions.setAutoStart(false); - this.defaultApiOptions.setRunNetDumper(false); - this.defaultApiOptions.setSkipOptional(false); + defaultApiOptions.setLanguage("Auto"); + defaultApiOptions.setContinueIfFailed(false); + defaultApiOptions.setIgnoreAskForContinue(false); + defaultApiOptions.setContinueIfFailed(false); + defaultApiOptions.setAutoStart(false); + defaultApiOptions.setRunNetDumper(false); + defaultApiOptions.setSkipOptional(false); } public Optional getGlobals() { @@ -210,7 +207,6 @@ public void normalize() { } } - - this.reportsFolder = substitutor.replace(this.reportsFolder); + this.reportsFolder = substitutor.replace(reportsFolder); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Script.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Script.java index 3c4a9593..9cd64677 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Script.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Script.java @@ -15,25 +15,26 @@ ******************************************************************************/ package com.exactpro.sf.bigbutton.library; -import com.exactpro.sf.bigbutton.execution.ScriptExecutionStatistics; -import com.exactpro.sf.bigbutton.importing.ImportError; -import com.exactpro.sf.scriptrunner.StatusType; -import com.exactpro.sf.util.EMailUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.exactpro.sf.bigbutton.execution.ScriptExecutionStatistics; +import com.exactpro.sf.bigbutton.importing.ImportError; +import com.exactpro.sf.scriptrunner.StatusType; +import com.exactpro.sf.util.EMailUtil; + @SuppressWarnings("serial") public class Script implements Serializable, IBBActionExecutor { private static final Logger logger = LoggerFactory.getLogger(Script.class); - public final static String UNCLOSED_TABLE_HEADER = ""; - public final static String OPTIONAL_TABLE_HEADER = ""; + public static final String UNCLOSED_TABLE_HEADER = "
ScriptStatusPassedConditionally PassedFailedCause
"; + public static final String OPTIONAL_TABLE_HEADER = ""; private long lineNumber; private String path; @@ -46,7 +47,7 @@ public class Script implements Serializable, IBBActionExecutor { private ImportError rejectCause; - private boolean finished = false; + private boolean finished; private final ScriptExecutionStatistics statistics = new ScriptExecutionStatistics(); @@ -120,9 +121,9 @@ public void setRejectCause(ImportError rejectCause) { public void addRejectCause(ImportError cause) { if (!isRejected()) { - setRejectCause(new ImportError(this.lineNumber, String.format("Script \"%s\" : error", this.shortName))); + setRejectCause(new ImportError(lineNumber, String.format("Script \"%s\" : error", shortName))); } - this.rejectCause.addCause(cause); + rejectCause.addCause(cause); } public void addRejectCause(Collection errors) { @@ -131,9 +132,9 @@ public void addRejectCause(Collection errors) { } if (!isRejected()) { - setRejectCause(new ImportError(this.lineNumber, String.format("Script List \"%s\" : error", this.shortName))); + setRejectCause(new ImportError(lineNumber, String.format("Script List \"%s\" : error", shortName))); } - this.rejectCause.addCause(errors); + rejectCause.addCause(errors); } public long getLineNumber() { @@ -161,21 +162,19 @@ public Set getActions() { case FAILED: actions = originalApiOptions.getOnFailed(); logger.info("Use failed script actions {}", actions); - break; + return actions; case CONDITIONALLY_PASSED: actions = originalApiOptions.getOnCondPassed(); logger.info("Use conditionally passed script actions {}", actions); - break; + return actions; case PASSED: actions = originalApiOptions.getOnPassed(); logger.info("Use passed script actions {}", actions); - break; + return actions; default: - actions = Collections.emptySet(); - break; + return Collections.emptySet(); } - return actions; } public StatusType getStatusType() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ScriptList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ScriptList.java index be274016..6ac2222f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ScriptList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ScriptList.java @@ -33,7 +33,7 @@ public class ScriptList extends AbstractLibraryItem implements Comparable, IBBActionExecutor { private static final Logger logger = LoggerFactory.getLogger(ScriptList.class); - private final static String TABLE_HEADER = ""; + private static final String TABLE_HEADER = ""; private final String name; @@ -68,18 +68,17 @@ public enum ScriptListStatus{ EXECUTED; public boolean isSkipped(){ - return this.equals(SKIPPED); + return this == SKIPPED; } public boolean isExecuted(){ - return this.equals(EXECUTED); + return this == EXECUTED; } } public ScriptList(String name, String executor, Set serviceLists, SfApiOptions apiOptions, long priority, long lineNumber, String variableSet) { - super(); - this.executor = executor; + this.executor = executor; this.name = name; this.serviceLists = serviceLists; this.apiOptions = apiOptions; @@ -92,7 +91,7 @@ public ScriptList(String name, String executor, Set serviceLists, @Override public void addNested(Script item) { - this.scripts.add(item); + scripts.add(item); } @@ -158,9 +157,9 @@ public boolean isRejected() { public void addRejectCause(ImportError cause) { if (!isRejected()) { - setRejectCause(new ImportError(this.lineNumber, String.format("Script List \"%s\" : error", this.name))); + setRejectCause(new ImportError(lineNumber, String.format("Script List \"%s\" : error", name))); } - this.rejectCause.addCause(cause); + rejectCause.addCause(cause); } public void addRejectCause(Collection errors) { @@ -169,9 +168,9 @@ public void addRejectCause(Collection errors) { } if (!isRejected()) { - setRejectCause(new ImportError(this.lineNumber, String.format("Script List \"%s\" : error", this.name))); + setRejectCause(new ImportError(lineNumber, String.format("Script List \"%s\" : error", name))); } - this.rejectCause.addCause(errors); + rejectCause.addCause(errors); } public ImportError getRejectCause() { @@ -207,21 +206,19 @@ public Set getActions() { case FAILED: actions = apiOptions.getOnFailed(); logger.info("Use failed script list actions {}", actions); - break; + return actions; case CONDITIONALLY_PASSED: actions = apiOptions.getOnCondPassed(); logger.info("Use conditionally passed script list actions {}", actions); - break; + return actions; case PASSED: actions = apiOptions.getOnPassed(); logger.info("Use passed script list actions {}", actions); - break; + return actions; default: - actions = Collections.emptySet(); - break; + return Collections.emptySet(); } - return actions; } public StatusType getStatusType() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Service.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Service.java index ee0edc08..c0d5703c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Service.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Service.java @@ -50,7 +50,7 @@ public void setName(String name) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((path == null) ? 0 : path.hashCode()); return result; @@ -58,18 +58,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } Service other = (Service) obj; if (path == null) { - if (other.path != null) - return false; - } else if (!path.equals(other.path)) - return false; + if(other.path != null) { + return false; + } + } else if(!path.equals(other.path)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ServiceList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ServiceList.java index 607fc9a7..18a607f9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ServiceList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/ServiceList.java @@ -15,14 +15,14 @@ ******************************************************************************/ package com.exactpro.sf.bigbutton.library; -import com.exactpro.sf.bigbutton.importing.ImportError; - import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import com.exactpro.sf.bigbutton.importing.ImportError; + @SuppressWarnings("serial") public class ServiceList extends AbstractLibraryItem implements Serializable { @@ -35,18 +35,18 @@ public class ServiceList extends AbstractLibraryItem implements Serializable { private ImportError rejectCause; private List services = new ArrayList<>(); - private Set serviceNames = new LinkedHashSet<>(); + private final Set serviceNames = new LinkedHashSet<>(); @Override public void addNested(Service item) { if ( !serviceNames.add(item.getName())) { if (!isRejected()) { - this.rejectCause = new ImportError(this.lineNumber, String.format("Service List \"%s\" error", this.name)); + this.rejectCause = new ImportError(lineNumber, String.format("Service List \"%s\" error", name)); } addRejectCause(new ImportError(item.getRecordNumber(), "Duplicate service with [" + item.getName() + "] name")); } - this.services.add(item); + services.add(item); } public String getName() { @@ -82,11 +82,11 @@ public void setLineNumber(long lineNumber) { } public boolean isRejected() { - return this.rejectCause != null; + return rejectCause != null; } public void addRejectCause(ImportError error) { - this.rejectCause.addCause(error); + rejectCause.addCause(error); } public ImportError getRejectCause() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/SfApiOptions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/SfApiOptions.java index 12aa6de7..e00fbeb9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/SfApiOptions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/SfApiOptions.java @@ -50,30 +50,26 @@ public class SfApiOptions implements Serializable { private Set onFailed = new LinkedHashSet<>(); - public SfApiOptions() { - - } - - public SfApiOptions mergeOptions(SfApiOptions child) { + public SfApiOptions mergeOptions(SfApiOptions child) { SfApiOptions result = new SfApiOptions(); - - result.continueIfFailed = (child.continueIfFailed != null ? child.continueIfFailed : this.continueIfFailed); - result.language = (child.language != null ? child.language : this.language ); - result.range = (child.range != null ? child.range : this.range ); - result.autoStart = (child.autoStart != null ? child.autoStart : this.autoStart ); - result.ignoreAskForContinue = (child.ignoreAskForContinue != null ? child.ignoreAskForContinue : this.ignoreAskForContinue); - result.runNetDumper = (child.runNetDumper != null ? child.runNetDumper : this.runNetDumper); - result.skipOptional = (child.skipOptional != null ? child.skipOptional : this.skipOptional); - - result.staticVariables.putAll(this.staticVariables); + + result.continueIfFailed = child.continueIfFailed != null ? child.continueIfFailed : continueIfFailed; + result.language = child.language != null ? child.language : language; + result.range = child.range != null ? child.range : range; + result.autoStart = child.autoStart != null ? child.autoStart : autoStart; + result.ignoreAskForContinue = child.ignoreAskForContinue != null ? child.ignoreAskForContinue : ignoreAskForContinue; + result.runNetDumper = child.runNetDumper != null ? child.runNetDumper : runNetDumper; + result.skipOptional = child.skipOptional != null ? child.skipOptional : skipOptional; + + result.staticVariables.putAll(staticVariables); result.staticVariables.putAll(child.staticVariables); result.setOnPassed(child.onPassed); // BigButtonActions not inherited result.setOnFailed(child.onFailed); result.setOnCondPassed(child.onCondPassed); - result.tags.addAll(this.tags); + result.tags.addAll(tags); result.tags.addAll(child.tags); return result; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/StartMode.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/StartMode.java index 7ebbb9d5..77b8df4a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/StartMode.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/StartMode.java @@ -23,7 +23,7 @@ public enum StartMode { private final String name; - private StartMode(String name) { + StartMode(String name) { this.name = name; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Tag.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Tag.java index fd7b6de6..05ebf8b5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Tag.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/Tag.java @@ -35,7 +35,7 @@ public Tag(String name) { } public void normalize(StringSubstitutor substitutor) { - this.name = substitutor.replace(this.name); + this.name = substitutor.replace(name); } public String getName() { @@ -56,7 +56,7 @@ public void setGroup(String group) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; @@ -64,18 +64,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } Tag other = (Tag) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; + if(other.name != null) { + return false; + } + } else if(!name.equals(other.name)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/TagList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/TagList.java index 2a479006..d387c04c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/TagList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/library/TagList.java @@ -24,7 +24,7 @@ public class TagList extends AbstractLibraryItem { @Override public void addNested(Tag item) { - this.tags.add(item); + tags.add(item); } public List getTags() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/util/BigButtonUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/util/BigButtonUtil.java index 29c9ad4e..327212dc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/util/BigButtonUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/bigbutton/util/BigButtonUtil.java @@ -39,7 +39,7 @@ public static String recognizeSeparatorInZipAndChangePath(File zipFile, String p ZipEntry ze; try (ZipFile zif = new ZipFile(zipFile)) { - final Enumeration entries = zif.entries(); + Enumeration entries = zif.entries(); while (entries.hasMoreElements()) { @@ -55,9 +55,9 @@ public static String recognizeSeparatorInZipAndChangePath(File zipFile, String p } } + return path; } - return path; } public static InputStream getStream(String rootFolder, String relativePath, @@ -85,12 +85,12 @@ public static InputStream getStream(String rootFolder, String relativePath, public static void getEntryFromReportZip(File zipFile, String entryToWrite, OutputStream out) throws IOException { - entryToWrite = BigButtonUtil.recognizeSeparatorInZipAndChangePath(zipFile, entryToWrite); + entryToWrite = recognizeSeparatorInZipAndChangePath(zipFile, entryToWrite); ZipEntry ze = null; try (ZipFile zif = new ZipFile(zipFile)) { - final Enumeration entries = zif.entries(); + Enumeration entries = zif.entries(); while (entries.hasMoreElements()) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/IVersion.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/IVersion.java index 1d270d95..24da555c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/IVersion.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/IVersion.java @@ -17,9 +17,9 @@ public interface IVersion { - public static final String CORE_VERSION_PROPERTY = "core_version"; + String CORE_VERSION_PROPERTY = "core_version"; - public static final String GENERAL = "General"; + String GENERAL = "General"; String buildShortVersion(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/SFContextSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/SFContextSettings.java index 40f9a7d5..e71fbd4d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/SFContextSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/SFContextSettings.java @@ -16,6 +16,7 @@ package com.exactpro.sf.center; import org.apache.commons.configuration.HierarchicalConfiguration; +import org.apache.commons.configuration.HierarchicalConfiguration.Node; public class SFContextSettings { private static final String ENVIRONMENT_KEY = "Environment"; @@ -31,21 +32,21 @@ public class SFContextSettings { public HierarchicalConfiguration getEnvironmentConfig() { if (config.configurationsAt(ENVIRONMENT_KEY).isEmpty()) { - config.getRootNode().addChild(new HierarchicalConfiguration.Node(ENVIRONMENT_KEY)); + config.getRootNode().addChild(new Node(ENVIRONMENT_KEY)); } return config.configurationAt(ENVIRONMENT_KEY); } public HierarchicalConfiguration getLoggingConfig() { if (config.configurationsAt(LOGGING_KEY).isEmpty()) { - config.getRootNode().addChild(new HierarchicalConfiguration.Node(LOGGING_KEY)); + config.getRootNode().addChild(new Node(LOGGING_KEY)); } return config.configurationAt(LOGGING_KEY); } public HierarchicalConfiguration getUpdateServiceConfiguration() { if (config.configurationsAt(UPDATER_KEY).isEmpty()) { - config.getRootNode().addChild(new HierarchicalConfiguration.Node(UPDATER_KEY)); + config.getRootNode().addChild(new Node(UPDATER_KEY)); } return config.configurationAt(UPDATER_KEY); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/AbstractVersion.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/AbstractVersion.java index a98e6fed..a6ba7694 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/AbstractVersion.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/AbstractVersion.java @@ -58,7 +58,7 @@ public String buildVersion() { @Override public boolean isGeneral() { - return GENERAL.equals(this.getAlias()); + return GENERAL.equals(getAlias()); } @Override @@ -98,11 +98,11 @@ public boolean equals(Object o) { AbstractVersion that = (AbstractVersion) o; return new EqualsBuilder() - .append(this.getMajor(), that.getMajor()) - .append(this.getMinor(), that.getMinor()) - .append(this.getMaintenance(), that.getMaintenance()) - .append(this.getBuild(), that.getBuild()) - .append(this.getAlias(), that.getAlias()).isEquals(); + .append(getMajor(), that.getMajor()) + .append(getMinor(), that.getMinor()) + .append(getMaintenance(), that.getMaintenance()) + .append(getBuild(), that.getBuild()) + .append(getAlias(), that.getAlias()).isEquals(); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/LoadInfo.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/LoadInfo.java index 0f8c2559..4a479a38 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/LoadInfo.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/LoadInfo.java @@ -26,8 +26,8 @@ */ public class LoadInfo { - private StringBuilder classPath = new StringBuilder(); - private Set classLoaders = new HashSet<>(); + private final StringBuilder classPath = new StringBuilder(); + private final Set classLoaders = new HashSet<>(); public String getClassPath() { return classPath.toString(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java index f2b83e47..b7075f5b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/PluginLoader.java @@ -42,7 +42,7 @@ import com.exactpro.sf.center.IVersion; import com.exactpro.sf.center.SFException; import com.exactpro.sf.common.util.EPSCommonException; -import com.exactpro.sf.common.util.Utils; +import com.exactpro.sf.common.util.Utils.FileExtensionFilter; import com.exactpro.sf.configuration.ILoadableManager; import com.exactpro.sf.configuration.LoadableManagerContext; import com.exactpro.sf.configuration.suri.SailfishURIException; @@ -108,20 +108,20 @@ public class PluginLoader { private final List pluginVersions; public PluginLoader( - final IWorkspaceDispatcher wd, - final ILoadableManager staticServiceManager, - final ILoadableManager actionManager, - final ILoadableManager dictionaryManager, - final PreprocessorLoader preprocessorLoader, - final ValidatorLoader validatorLoader, - final ILoadableManager adapterManager, - final ILoadableManager dataManager, - final ILoadableManager languageManager, - final MatrixProviderHolder matrixProviderHolder, - final ILoadableManager matrixConverterManager, - final ILoadableManager statisticsReportsLoader, - final PluginServiceLoader pluginServiceLoader, - final IVersion coreVersion) { + IWorkspaceDispatcher wd, + ILoadableManager staticServiceManager, + ILoadableManager actionManager, + ILoadableManager dictionaryManager, + PreprocessorLoader preprocessorLoader, + ValidatorLoader validatorLoader, + ILoadableManager adapterManager, + ILoadableManager dataManager, + ILoadableManager languageManager, + MatrixProviderHolder matrixProviderHolder, + ILoadableManager matrixConverterManager, + ILoadableManager statisticsReportsLoader, + PluginServiceLoader pluginServiceLoader, + IVersion coreVersion) { if (wd == null) { throw new NullPointerException("IWorkspaceDispatcher can't be null"); } @@ -215,7 +215,7 @@ private ClassLoader loadPluginFrom(FolderType folderType, String pluginPath, Loa try { StringBuilder classPath = new StringBuilder(); - Set libs = wd.listFiles(new Utils.FileExtensionFilter("jar"), folderType, pluginPath, "libs"); + Set libs = wd.listFiles(new FileExtensionFilter("jar"), folderType, pluginPath, "libs"); URL[] urls = new URL[libs.size()]; Iterator libsIterator = libs.iterator(); for (int i=0; i this.coreVersion.getMaintenance()) { + if(version.getMinCoreRevision() > coreVersion.getMaintenance()) { throw new SFException(String.format("Plugin '%s' need newer core revision: %s.%s.%s (expected: %s.%s.%s or higher)", pluginPath, - this.coreVersion.getMajor(), this.coreVersion.getMinor(), this.coreVersion.getMaintenance(), + coreVersion.getMajor(), coreVersion.getMinor(), coreVersion.getMaintenance(), version.getMajor(), version.getMinor(), version.getMaintenance())); } @@ -256,8 +256,8 @@ private ClassLoader loadPluginFrom(FolderType folderType, String pluginPath, Loa logger.error("Failed to load version file '{{}}/{}/{}': ", folderType, pluginPath, VERSION_FILE_NAME, e); } } else { - version = this.coreVersion; - this.pluginVersions.add(version); + version = coreVersion; + pluginVersions.add(version); } if (version == null) { @@ -268,7 +268,7 @@ private ClassLoader loadPluginFrom(FolderType folderType, String pluginPath, Loa logger.info("Loading {}", version); // root = {resolved folderType} / {pluginPath} - final String root = new File(DefaultWorkspaceLayout.getInstance().getPath(new File("."), folderType), pluginPath).getPath(); + String root = new File(DefaultWorkspaceLayout.getInstance().getPath(new File("."), folderType), pluginPath).getPath(); // // Load log.properties @@ -277,7 +277,7 @@ private ClassLoader loadPluginFrom(FolderType folderType, String pluginPath, Loa File file = wd.getFile(folderType, pluginPath, LOG4J_PROPERTIES_FILE_NAME); logger.info("Loading logger configuration: {{}}/{}/{}", folderType, pluginPath, LOG4J_PROPERTIES_FILE_NAME); try { - (new PropertyConfigurator()).doConfigure(file.getPath(), LogManager.getLoggerRepository()); + new PropertyConfigurator().doConfigure(file.getPath(), LogManager.getLoggerRepository()); } catch (Throwable e) { throw new EPSCommonException("Failed to configure logger. {" + folderType + "}/" + pluginPath + "/" + LOG4J_PROPERTIES_FILE_NAME, e); } @@ -289,13 +289,11 @@ private ClassLoader loadPluginFrom(FolderType folderType, String pluginPath, Loa // LoadableContext // LoadableManagerContext loadableContext = new LoadableManagerContext(); - { - loadableContext.setResourceFolder(root); - loadableContext.setVersion(version); - loadableContext.setClassLoaders(classLoader); - } + loadableContext.setResourceFolder(root); + loadableContext.setVersion(version); + loadableContext.setClassLoaders(classLoader); - // + // // load services (Services + ServiceSettings) // if (staticServiceManager != null) { @@ -533,7 +531,7 @@ private void loadCustomDictionaries() { logger.info("Loading dictionaries: {{}}/{}/cfg/{}", FolderType.ROOT, ",", CUSTOM_DICTIONARIES_XML); String pathToDictionaries = Paths.get("././.", "cfg", "dictionaries").toString(); try (InputStream stream = new FileInputStream(file)) { - LoadableManagerContext context = new LoadableManagerContext(this.coreVersion, pathToDictionaries, stream, PluginLoader.class.getClassLoader()); + LoadableManagerContext context = new LoadableManagerContext(coreVersion, pathToDictionaries, stream, PluginLoader.class.getClassLoader()); dictionaryManager.load(context); } catch (Exception e) { throw new EPSCommonException( diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/SFLocalContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/SFLocalContext.java index 40183510..0bba3ca2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/SFLocalContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/center/impl/SFLocalContext.java @@ -118,7 +118,7 @@ public class SFLocalContext implements ISFContext { private static final Logger logger = LoggerFactory.getLogger(SFLocalContext.class); - private static volatile SFLocalContext context = null; + private static volatile SFLocalContext context; private final IWorkspaceDispatcher workspaceDispatcher; @@ -149,14 +149,14 @@ public class SFLocalContext implements ISFContext { private final StatisticsService statisticsService; private final MachineLearningService machineLearningService; private final UpdateService updateService; - private EMailService mailService; - private RegressionRunner regressionRunner; + private final EMailService mailService; + private final RegressionRunner regressionRunner; private final Queue embeddedServices = new LinkedList<>(); - private FlightRecorderService flightRecorderService; + private final FlightRecorderService flightRecorderService; - private NetDumperService netDumperService; + private final NetDumperService netDumperService; // Other: private final EnvironmentManager environmentManager; @@ -230,7 +230,7 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro IStorage storage = null; if(envSettings.getStorageType() == StorageType.DB) { - sessionFactory = HibernateFactory.getInstance().getSessionFactory(this.workspaceDispatcher); + sessionFactory = HibernateFactory.getInstance().getSessionFactory(workspaceDispatcher); Session session = null; try { @@ -259,7 +259,7 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro optionsStorage = createOptionsStorage(envSettings, storage, workspaceDispatcher); taskExecutor = new TaskExecutor(); - this.disposables.add(taskExecutor); + disposables.add(taskExecutor); loggingConfigurator = new LoggingConfigurator(wd, loggingConfiguration); @@ -283,10 +283,10 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro ValidatorLoader validatorLoader = new ValidatorLoader(); this.statisticsService = new StatisticsService(); - this.embeddedServices.add(statisticsService); + embeddedServices.add(statisticsService); this.updateService = new UpdateService(workspaceDispatcher, settings.getUpdateServiceConfiguration(), taskExecutor); - this.embeddedServices.add(updateService); + embeddedServices.add(updateService); PluginServiceLoader pluginServiceLoader = new PluginServiceLoader(); @@ -305,17 +305,17 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro matrixConverterLoader, statisticsService, pluginServiceLoader, - this.version); + version); LoadInfo loadInfo = pluginLoader.load(); loadInfo.appendClassPath(compilerClassPath); compilerClassPath = loadInfo.getClassPath(); messageStorage = createMessageStorage(envSettings, sessionFactory, dictionaryManager); - this.disposables.add(this.messageStorage); + disposables.add(messageStorage); serviceStorage = createServiceStorage(envSettings, sessionFactory, workspaceDispatcher, staticServiceManager, dictionaryManager, messageStorage); - this.disposables.add(serviceStorage); + disposables.add(serviceStorage); this.serviceContext = new DefaultServiceContext(dictionaryManager, messageStorage, serviceStorage, loggingConfigurator, taskExecutor, dataManager, wd); @@ -325,8 +325,8 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro serviceStorage, createEnvironmentStorage(envSettings, storage, workspaceDispatcher), createVariableSetStorage(envSettings, storage, workspaceDispatcher), - this.serviceContext); - this.disposables.add(this.connectionManager); + serviceContext); + disposables.add(connectionManager); pluginServiceLoader.load(connectionManager, new ServiceMarshalManager(staticServiceManager, dictionaryManager)); @@ -344,19 +344,19 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro this.scriptRunner = envSettings.isAsyncRunMatrix() ? new AsyncScriptRunner(workspaceDispatcher, dictionaryManager, actionManager, utilityManager, languageManager, preprocessorLoader, validatorLoader, runnerSettings, statisticsService, environmentManager, testScriptStorage, adapterManager, staticServiceManager, compilerClassPath) : new SyncScriptRunner(workspaceDispatcher, dictionaryManager, actionManager, utilityManager, languageManager, preprocessorLoader, validatorLoader, runnerSettings, statisticsService, environmentManager, testScriptStorage, adapterManager, staticServiceManager, compilerClassPath); - this.disposables.add(this.scriptRunner); + disposables.add(scriptRunner); this.mailService = new EMailService(); - this.embeddedServices.add(mailService); + embeddedServices.add(mailService); - this.flightRecorderService = new FlightRecorderService(taskExecutor, this.optionsStorage); + this.flightRecorderService = new FlightRecorderService(taskExecutor, optionsStorage); this.netDumperService = new NetDumperService(connectionManager, workspaceDispatcher, optionsStorage); - this.netDumperService.init(); + netDumperService.init(); this.regressionRunner = new RegressionRunner(taskExecutor, workspaceDispatcher, mailService, optionsStorage, statisticsService); - this.regressionRunner.init(); + regressionRunner.init(); this.validators = Collections.unmodifiableList(validatorLoader.getValidators()); this.pluginToValidators = validatorLoader.getPluginToValidatorsMap(); @@ -366,7 +366,7 @@ private SFLocalContext(IWorkspaceDispatcher wd, SFContextSettings settings) thro this.pluginClassLoaders = pluginVersions.stream().collect(Collectors.collectingAndThen(Collectors.toMap(IVersion::getAlias, x -> x.getClass().getClassLoader()), Collections::unmodifiableMap)); this.machineLearningService = new MachineLearningService(workspaceDispatcher, dictionaryManager, dataManager, pluginClassLoaders); - this.embeddedServices.add(machineLearningService); + embeddedServices.add(machineLearningService); } private IMessageStorage createMessageStorage(EnvironmentSettings envSettings, SessionFactory sessionFactory, DictionaryManager dictionaryManager) throws WorkspaceStructureException, FileNotFoundException { @@ -460,7 +460,7 @@ public IServiceContext getServiceContext() { @Override public IConnectionManager getConnectionManager() { - return this.connectionManager; + return connectionManager; } @Override @@ -470,17 +470,17 @@ public IStaticServiceManager getStaticServiceManager() { @Override public IMessageStorage getMessageStorage() { - return this.messageStorage; + return messageStorage; } @Override public IWorkspaceDispatcher getWorkspaceDispatcher() { - return this.workspaceDispatcher; + return workspaceDispatcher; } @Override public IMatrixStorage getMatrixStorage() { - return this.matrixStorage; + return matrixStorage; } @Override @@ -490,7 +490,7 @@ public IDictionaryManager getDictionaryManager() { @Override public IAuthStorage getAuthStorage() { - return this.authStorage; + return authStorage; } @Override @@ -505,17 +505,17 @@ public AbstractScriptRunner getScriptRunner() { @Override public void dispose() { - while (!this.disposables.isEmpty()) { + while(!disposables.isEmpty()) { try { - this.disposables.remove().dispose(); + disposables.remove().dispose(); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } } - while (!this.embeddedServices.isEmpty()) { + while(!embeddedServices.isEmpty()) { try { - this.embeddedServices.remove().tearDown(); + embeddedServices.remove().tearDown(); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } @@ -624,17 +624,17 @@ public String getBranchName() { @Override public ListMultimap getPluginToValidatorsMap() { - return this.pluginToValidators; + return pluginToValidators; } @Override public ListMultimap getPluginToPreprocessorsMap() { - return this.pluginToPreprocessors; + return pluginToPreprocessors; } @Override public Map getPluginClassLoaders() { - return this.pluginClassLoaders; + return pluginClassLoaders; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterFactory.java index 8fc039ec..b54edf91 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterFactory.java @@ -42,7 +42,7 @@ public interface IAdapterFactory { * does not have an adapter of the given type for the * given object */ - public Object getAdapter(Object adaptableObject, Class adapterType); + Object getAdapter(Object adaptableObject, Class adapterType); /** * Returns the collection of adapter types handled by this @@ -55,5 +55,5 @@ public interface IAdapterFactory { * * @return the collection of adapter types */ - public Class[] getAdapterList(); + Class[] getAdapterList(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterManager.java index 49e139c3..53dbd114 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/IAdapterManager.java @@ -74,20 +74,20 @@ public interface IAdapterManager { * was found. * @since org.eclipse.equinox.common 3.3 */ - public static final int NONE = 0; + int NONE = 0; /** * This value can be returned to indicate that an adapter factory was found, * but has not been loaded. * @since org.eclipse.equinox.common 3.3 */ - public static final int NOT_LOADED = 1; + int NOT_LOADED = 1; /** * This value can be returned to indicate that an adapter factory is loaded. * @since org.eclipse.equinox.common 3.3 */ - public static final int LOADED = 2; + int LOADED = 2; /** * Returns the types that can be obtained by converting adaptableClass @@ -106,7 +106,7 @@ public interface IAdapterManager { * is returned if there are none. * @since 3.1 */ - public String[] computeAdapterTypes(Class adaptableClass); + String[] computeAdapterTypes(Class adaptableClass); /** * Returns the class search order for a given class. The search order from a @@ -126,7 +126,7 @@ public interface IAdapterManager { * search order will minimally contain the target class. * @since 3.1 */ - public Class[] computeClassOrder(Class clazz); + Class[] computeClassOrder(Class clazz); /** * Returns an object which is an instance of the given class associated @@ -143,9 +143,9 @@ public interface IAdapterManager { * if the given adaptable object does not have an available adapter of the * given type */ - public Object getAdapter(Object adaptable, Class adapterType); + Object getAdapter(Object adaptable, Class adapterType); - public Object getAdapter(Class clazz, Class adapterType); + Object getAdapter(Class clazz, Class adapterType); /** * Returns whether there is an adapter factory registered that may be able @@ -165,7 +165,7 @@ public interface IAdapterManager { * and false otherwise. * @since 3.0 */ - public boolean hasAdapter(Object adaptable, Class adapterType); + boolean hasAdapter(Object adaptable, Class adapterType); /** * Returns a status of an adapter factory registered that may be able @@ -182,7 +182,7 @@ public interface IAdapterManager { * @return a status of the adapter * @since org.eclipse.equinox.common 3.3 */ - public int queryAdapter(Object adaptable, Class adapterType); + int queryAdapter(Object adaptable, Class adapterType); /** * Registers the given adapter factory as extending objects of the given @@ -199,7 +199,7 @@ public interface IAdapterManager { * @see #unregisterAdapters(IAdapterFactory) * @see #unregisterAdapters(IAdapterFactory, Class) */ - public void registerAdapters(IAdapterFactory factory, Class adaptable); + void registerAdapters(IAdapterFactory factory, Class adaptable); /** * Removes the given adapter factory completely from the list of registered @@ -210,7 +210,7 @@ public interface IAdapterManager { * @param factory the adapter factory to remove * @see #registerAdapters(IAdapterFactory, Class) */ - public void unregisterAdapters(IAdapterFactory factory); + void unregisterAdapters(IAdapterFactory factory); /** * Removes the given adapter factory from the list of factories registered @@ -222,5 +222,5 @@ public interface IAdapterManager { * registered * @see #registerAdapters(IAdapterFactory, Class) */ - public void unregisterAdapters(IAdapterFactory factory, Class adaptable); + void unregisterAdapters(IAdapterFactory factory, Class adaptable); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/impl/DefaultAdapterFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/impl/DefaultAdapterFactory.java index cad7f3f5..3fc8b750 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/impl/DefaultAdapterFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/adapting/impl/DefaultAdapterFactory.java @@ -24,8 +24,8 @@ public class DefaultAdapterFactory implements IAdapterFactory { - private Class[] adapterList; - private Map, Class> adapterMap; + private final Class[] adapterList; + private final Map, Class> adapterMap; public DefaultAdapterFactory(Class[] adapterList, Map, Class> adapterMap) { this.adapterList = adapterList; @@ -36,10 +36,11 @@ public DefaultAdapterFactory(Class[] adapterList, Map, Class> ada @Override public Object getAdapter(Object adaptableObject, Class adapterType) { - Class adapterClass = this.adapterMap.get(adapterType); + Class adapterClass = adapterMap.get(adapterType); - if ( adapterClass == null ) - throw new EPSCommonException("Could not find adapterClass for adapter [" + adapterType + "]"); + if(adapterClass == null) { + throw new EPSCommonException("Could not find adapterClass for adapter [" + adapterType + "]"); + } Constructor[] constructors = adapterClass.getConstructors(); Constructor constructor = constructors[0]; @@ -81,7 +82,7 @@ public Object getAdapter(Object adaptableObject, Class adapterType) @Override public Class[] getAdapterList() { - return this.adapterList; + return adapterList; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/AbstractCodec.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/AbstractCodec.java index 72e724bd..b1d34d01 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/AbstractCodec.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/AbstractCodec.java @@ -25,6 +25,6 @@ public abstract class AbstractCodec extends CumulativeProtocolDecoder implements ProtocolEncoder { - public abstract void init(IServiceContext serviceContext, ICommonSettings settings, final IMessageFactory msgFactory, final IDictionaryStructure dictionary); + public abstract void init(IServiceContext serviceContext, ICommonSettings settings, IMessageFactory msgFactory, IDictionaryStructure dictionary); } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/CodecFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/CodecFactory.java index b94cebc9..07a2e046 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/CodecFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/codecs/CodecFactory.java @@ -38,7 +38,7 @@ public class CodecFactory implements ProtocolCodecFactory { private final ICommonSettings codecSettings; private final ConcurrentMap codecs = new ConcurrentHashMap<>(); - public CodecFactory(IServiceContext serviceContext, final IMessageFactory msgFactory, final IDictionaryStructure dictionary, Class codecClass, ICommonSettings codecSettings) { + public CodecFactory(IServiceContext serviceContext, IMessageFactory msgFactory, IDictionaryStructure dictionary, Class codecClass, ICommonSettings codecSettings) { this.serviceContext = Objects.requireNonNull(serviceContext, "Service context is not specified"); @@ -61,7 +61,7 @@ public ProtocolDecoder getDecoder(IoSession session) throws Exception { } codec = codecClass.newInstance(); - codec.init(this.serviceContext, this.codecSettings, this.msgFactory, this.msgDictionary); + codec.init(serviceContext, codecSettings, msgFactory, msgDictionary); codecs.putIfAbsent(session, codec); return codecs.get(session); @@ -77,7 +77,7 @@ public ProtocolEncoder getEncoder(IoSession session) throws Exception { } codec = codecClass.newInstance(); - codec.init(this.serviceContext, this.codecSettings, this.msgFactory, this.msgDictionary); + codec.init(serviceContext, codecSettings, msgFactory, msgDictionary); codecs.putIfAbsent(session, codec); return codecs.get(session); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/IMessageTimestampComparator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/IMessageTimestampComparator.java index 092bb784..efa6edb9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/IMessageTimestampComparator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/IMessageTimestampComparator.java @@ -22,26 +22,26 @@ public class IMessageTimestampComparator implements Comparator { - public final static IMessageTimestampComparator instance = new IMessageTimestampComparator(); + public static final IMessageTimestampComparator instance = new IMessageTimestampComparator(); @Override public int compare(IMessage m1, IMessage m2) { - if (m1 == null || m2 == null) - throw new NullPointerException("Can't compere: IMessage is null"); + if(m1 == null || m2 == null) { + throw new NullPointerException("Can't compere: IMessage is null"); + } - if (m1.getMetaData() == null || m2.getMetaData() == null) - throw new NullPointerException("Can't compere IMessages: metadata is null"); + if(m1.getMetaData() == null || m2.getMetaData() == null) { + throw new NullPointerException("Can't compere IMessages: metadata is null"); + } Date d1 = m1.getMetaData().getMsgTimestamp(); Date d2 = m2.getMetaData().getMsgTimestamp(); - if (d1 == null || d2 == null) - throw new NullPointerException("Timestamp is null. Comparing... " + m1.getNamespace() + "@" + m1.getName() + "; " + m2.getNamespace() + "@" + m2.getName()); + if(d1 == null || d2 == null) { + throw new NullPointerException("Timestamp is null. Comparing... " + m1.getNamespace() + "@" + m1.getName() + "; " + m2.getNamespace() + "@" + m2.getName()); + } - if (d1.equals(d2)) - return 0; - - return d1.before(d2) ? -1 : 1; + return d1.compareTo(d2); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/StrictMessageWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/StrictMessageWrapper.java index d71f4e96..fea7722b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/StrictMessageWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/impl/messages/StrictMessageWrapper.java @@ -112,26 +112,26 @@ public void addField(String name, Object value) { if (fieldStructure.isComplex()) { if (fieldStructure.isCollection()) { - this.message.addField(name, castValueToCollection(value, StrictMessageWrapper.class)); + message.addField(name, castValueToCollection(value, StrictMessageWrapper.class)); } else { Object element = value; if (value instanceof List) { element = extractValueFromCollection((List)value); } - this.message.addField(name, checkElement(requiredNotNull(element, fieldStructure), StrictMessageWrapper.class)); + message.addField(name, checkElement(requiredNotNull(element, fieldStructure), StrictMessageWrapper.class)); } } else { try { - Class clazz = this.getClass().getClassLoader().loadClass(fieldStructure.getJavaType().value()); + Class clazz = getClass().getClassLoader().loadClass(fieldStructure.getJavaType().value()); if (fieldStructure.isCollection()) { - this.message.addField(name, castValueToCollection(value, clazz)); + message.addField(name, castValueToCollection(value, clazz)); } else { Object element = value; if (value instanceof List) { element = extractValueFromCollection((List)value); } - this.message.addField(name, checkElement(requiredNotNull(element, fieldStructure), clazz)); + message.addField(name, checkElement(requiredNotNull(element, fieldStructure), clazz)); } } catch (ClassNotFoundException e) { throw new EPSCommonException("Unknown field type: " + fieldStructure.getJavaType().value(), e); @@ -146,7 +146,7 @@ public void addField(String name, Object value) { */ @Override public String getName() { - return this.message.getName(); + return message.getName(); } /* @@ -156,7 +156,7 @@ public String getName() { */ @Override public String getNamespace() { - return this.message.getNamespace(); + return message.getNamespace(); } /* @@ -166,7 +166,7 @@ public String getNamespace() { */ @Override public MsgMetaData getMetaData() { - return this.message.getMetaData(); + return message.getMetaData(); } /* @@ -177,7 +177,7 @@ public MsgMetaData getMetaData() { */ @Override public Object removeField(String name) { - return this.message.removeField(name); + return message.removeField(name); } /* @@ -187,7 +187,7 @@ public Object removeField(String name) { */ @Override public T getField(String name) { - return this.message.getField(name); + return message.getField(name); } /* @@ -198,7 +198,7 @@ public T getField(String name) { */ @Override public FieldMetaData getFieldMetaData(String name) { - return this.message.getFieldMetaData(name); + return message.getFieldMetaData(name); } /* @@ -209,7 +209,7 @@ public FieldMetaData getFieldMetaData(String name) { */ @Override public boolean isFieldSet(String name) { - return this.message.isFieldSet(name); + return message.isFieldSet(name); } /* @@ -219,7 +219,7 @@ public boolean isFieldSet(String name) { */ @Override public Set getFieldNames() { - return this.message.getFieldNames(); + return message.getFieldNames(); } /* @@ -230,7 +230,7 @@ public Set getFieldNames() { */ @Override public IFieldInfo getFieldInfo(String name) { - return this.message.getFieldInfo(name); + return message.getFieldInfo(name); } /* @@ -240,7 +240,7 @@ public IFieldInfo getFieldInfo(String name) { */ @Override public IMessage cloneMessage() { - return new StrictMessageWrapper(message.cloneMessage(), this.messageStructure); + return new StrictMessageWrapper(message.cloneMessage(), messageStructure); } /* @@ -260,20 +260,20 @@ public boolean compare(IMessage message) { */ @Override public int getFieldCount() { - return this.message.getFieldCount(); + return message.getFieldCount(); } @Override public String toString() { StringBuilder toString = new StringBuilder(1024); - for(String fldName : this.getFieldNames()) { + for(String fldName : getFieldNames()) { if(toString.length() > 0) { toString.append('|'); } - if(this.getField(fldName) instanceof IMessage) { - toString.append(((StrictMessageWrapper)this.getField(fldName)).toString()); + if(getField(fldName) instanceof IMessage) { + toString.append((StrictMessageWrapper)getField(fldName)); } else { toString.append(fldName); toString.append('='); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java index 8b694691..cd80d75e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/logging/DailyMaxRollingFileAppender.java @@ -344,7 +344,7 @@ void rollOver() throws IOException { } // close current file, and rename it to datedFilename - this.closeFile(); + closeFile(); File target = new File(scheduledFilename); if (target.exists()) { @@ -362,8 +362,9 @@ void rollOver() throws IOException { // Delete the oldest file, to keep Windows happy. file = new File(fileName + dateBefore()); - if (file.exists()) + if(file.exists()) { file.delete(); + } // this function invocation has been added to original file deleteOldFiles(); @@ -376,7 +377,7 @@ void rollOver() throws IOException { try { // This will also close the file. This is OK since multiple // close operations are safe. - this.setFile(fileName, false, this.bufferedIO, this.bufferSize); + setFile(fileName, false, bufferedIO, bufferSize); } catch (IOException e) { errorHandler.error("setFile(" + fileName + ", false) call failed."); } @@ -414,15 +415,14 @@ private void deleteOldFiles() { } private String dateBefore() { - String dataAnte = ""; if (datePattern != null) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern); - dataAnte = simpleDateFormat.format(new Date(rpc.getPastCheckMillis(new Date(), maxBackupIndex))); + return simpleDateFormat.format(new Date(rpc.getPastCheckMillis(new Date(), maxBackupIndex))); } - return dataAnte; + return ""; } /** @@ -454,7 +454,7 @@ protected void subAppend(LoggingEvent event) { /* * DEBUG */ - public static void main(String args[]) { + public static void main(String[] args) { DailyMaxRollingFileAppender dmrfa = new DailyMaxRollingFileAppender(); dmrfa.setDatePattern("'.'yyyy-MM-dd-HH-mm"); @@ -490,7 +490,6 @@ class RollingPastCalendar extends RollingCalendar { private static final long serialVersionUID = -903139157006143644L; RollingPastCalendar() { - super(); } RollingPastCalendar(TimeZone tz, Locale locale) { @@ -502,63 +501,59 @@ public long getPastCheckMillis(Date now, int maxBackupIndex) { } public Date getPastDate(Date now, int maxBackupIndex) { - this.setTime(now); + setTime(now); switch (type) { case DailyMaxRollingFileAppender.TOP_OF_MINUTE: - this.set(Calendar.SECOND, this.get(Calendar.SECOND)); - this.set(Calendar.MILLISECOND, this.get(Calendar.MILLISECOND)); - this.set(Calendar.MINUTE, this.get(Calendar.MINUTE) + set(Calendar.SECOND, get(Calendar.SECOND)); + set(Calendar.MILLISECOND, get(Calendar.MILLISECOND)); + set(Calendar.MINUTE, get(Calendar.MINUTE) - maxBackupIndex); break; case DailyMaxRollingFileAppender.TOP_OF_HOUR: - this.set(Calendar.MINUTE, this.get(Calendar.MINUTE)); - this.set(Calendar.SECOND, this.get(Calendar.SECOND)); - this.set(Calendar.MILLISECOND, this.get(Calendar.MILLISECOND)); - this.set(Calendar.HOUR_OF_DAY, this.get(Calendar.HOUR_OF_DAY) + set(Calendar.MINUTE, get(Calendar.MINUTE)); + set(Calendar.SECOND, get(Calendar.SECOND)); + set(Calendar.MILLISECOND, get(Calendar.MILLISECOND)); + set(Calendar.HOUR_OF_DAY, get(Calendar.HOUR_OF_DAY) - maxBackupIndex); break; case DailyMaxRollingFileAppender.HALF_DAY: - this.set(Calendar.MINUTE, this.get(Calendar.MINUTE)); - this.set(Calendar.SECOND, this.get(Calendar.SECOND)); - this.set(Calendar.MILLISECOND, this.get(Calendar.MILLISECOND)); + set(Calendar.MINUTE, get(Calendar.MINUTE)); + set(Calendar.SECOND, get(Calendar.SECOND)); + set(Calendar.MILLISECOND, get(Calendar.MILLISECOND)); int hour = get(Calendar.HOUR_OF_DAY); - if (hour < 12) { - this.set(Calendar.HOUR_OF_DAY, 12); - } else { - this.set(Calendar.HOUR_OF_DAY, 0); - } - this.set(Calendar.DAY_OF_MONTH, this.get(Calendar.DAY_OF_MONTH) + set(Calendar.HOUR_OF_DAY, hour < 12 ? 12 : 0); + set(Calendar.DAY_OF_MONTH, get(Calendar.DAY_OF_MONTH) - maxBackupIndex); break; case DailyMaxRollingFileAppender.TOP_OF_DAY: - this.set(Calendar.HOUR_OF_DAY, this.get(Calendar.HOUR_OF_DAY)); - this.set(Calendar.MINUTE, this.get(Calendar.MINUTE)); - this.set(Calendar.SECOND, this.get(Calendar.SECOND)); - this.set(Calendar.MILLISECOND, this.get(Calendar.MILLISECOND)); - this.set(Calendar.DATE, this.get(Calendar.DATE) - maxBackupIndex); + set(Calendar.HOUR_OF_DAY, get(Calendar.HOUR_OF_DAY)); + set(Calendar.MINUTE, get(Calendar.MINUTE)); + set(Calendar.SECOND, get(Calendar.SECOND)); + set(Calendar.MILLISECOND, get(Calendar.MILLISECOND)); + set(Calendar.DATE, get(Calendar.DATE) - maxBackupIndex); break; case DailyMaxRollingFileAppender.TOP_OF_WEEK: - this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek()); - this.set(Calendar.HOUR_OF_DAY, this.get(Calendar.HOUR_OF_DAY)); - this.set(Calendar.MINUTE, this.get(Calendar.MINUTE)); - this.set(Calendar.SECOND, this.get(Calendar.SECOND)); - this.set(Calendar.MILLISECOND, this.get(Calendar.MILLISECOND)); - this.set(Calendar.WEEK_OF_YEAR, this.get(Calendar.WEEK_OF_YEAR) + set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek()); + set(Calendar.HOUR_OF_DAY, get(Calendar.HOUR_OF_DAY)); + set(Calendar.MINUTE, get(Calendar.MINUTE)); + set(Calendar.SECOND, get(Calendar.SECOND)); + set(Calendar.MILLISECOND, get(Calendar.MILLISECOND)); + set(Calendar.WEEK_OF_YEAR, get(Calendar.WEEK_OF_YEAR) - maxBackupIndex); break; case DailyMaxRollingFileAppender.TOP_OF_MONTH: - this.set(Calendar.DATE, this.get(Calendar.DATE)); - this.set(Calendar.HOUR_OF_DAY, this.get(Calendar.HOUR_OF_DAY)); - this.set(Calendar.MINUTE, this.get(Calendar.MINUTE)); - this.set(Calendar.SECOND, this.get(Calendar.SECOND)); - this.set(Calendar.MILLISECOND, this.get(Calendar.MILLISECOND)); - this.set(Calendar.MONTH, this.get(Calendar.MONTH) - maxBackupIndex); + set(Calendar.DATE, get(Calendar.DATE)); + set(Calendar.HOUR_OF_DAY, get(Calendar.HOUR_OF_DAY)); + set(Calendar.MINUTE, get(Calendar.MINUTE)); + set(Calendar.SECOND, get(Calendar.SECOND)); + set(Calendar.MILLISECOND, get(Calendar.MILLISECOND)); + set(Calendar.MONTH, get(Calendar.MONTH) - maxBackupIndex); break; default: @@ -583,7 +578,6 @@ class RollingCalendar extends GregorianCalendar { int type = DailyMaxRollingFileAppender.TOP_OF_TROUBLE; RollingCalendar() { - super(); } RollingCalendar(TimeZone tz, Locale locale) { @@ -599,54 +593,54 @@ public long getNextCheckMillis(Date now) { } public Date getNextCheckDate(Date now) { - this.setTime(now); + setTime(now); switch (type) { case DailyMaxRollingFileAppender.TOP_OF_MINUTE: - this.set(Calendar.SECOND, 0); - this.set(Calendar.MILLISECOND, 0); - this.add(Calendar.MINUTE, 1); + set(Calendar.SECOND, 0); + set(Calendar.MILLISECOND, 0); + add(Calendar.MINUTE, 1); break; case DailyMaxRollingFileAppender.TOP_OF_HOUR: - this.set(Calendar.MINUTE, 0); - this.set(Calendar.SECOND, 0); - this.set(Calendar.MILLISECOND, 0); - this.add(Calendar.HOUR_OF_DAY, 1); + set(Calendar.MINUTE, 0); + set(Calendar.SECOND, 0); + set(Calendar.MILLISECOND, 0); + add(Calendar.HOUR_OF_DAY, 1); break; case DailyMaxRollingFileAppender.HALF_DAY: - this.set(Calendar.MINUTE, 0); - this.set(Calendar.SECOND, 0); - this.set(Calendar.MILLISECOND, 0); + set(Calendar.MINUTE, 0); + set(Calendar.SECOND, 0); + set(Calendar.MILLISECOND, 0); int hour = get(Calendar.HOUR_OF_DAY); if (hour < 12) { - this.set(Calendar.HOUR_OF_DAY, 12); + set(Calendar.HOUR_OF_DAY, 12); } else { - this.set(Calendar.HOUR_OF_DAY, 0); - this.add(Calendar.DAY_OF_MONTH, 1); + set(Calendar.HOUR_OF_DAY, 0); + add(Calendar.DAY_OF_MONTH, 1); } break; case DailyMaxRollingFileAppender.TOP_OF_DAY: - this.set(Calendar.HOUR_OF_DAY, 0); - this.set(Calendar.MINUTE, 0); - this.set(Calendar.SECOND, 0); - this.set(Calendar.MILLISECOND, 0); - this.add(Calendar.DATE, 1); + set(Calendar.HOUR_OF_DAY, 0); + set(Calendar.MINUTE, 0); + set(Calendar.SECOND, 0); + set(Calendar.MILLISECOND, 0); + add(Calendar.DATE, 1); break; case DailyMaxRollingFileAppender.TOP_OF_WEEK: - this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek()); - this.set(Calendar.HOUR_OF_DAY, 0); - this.set(Calendar.MINUTE, 0); - this.set(Calendar.SECOND, 0); - this.set(Calendar.MILLISECOND, 0); - this.add(Calendar.WEEK_OF_YEAR, 1); + set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek()); + set(Calendar.HOUR_OF_DAY, 0); + set(Calendar.MINUTE, 0); + set(Calendar.SECOND, 0); + set(Calendar.MILLISECOND, 0); + add(Calendar.WEEK_OF_YEAR, 1); break; case DailyMaxRollingFileAppender.TOP_OF_MONTH: - this.set(Calendar.DATE, 1); - this.set(Calendar.HOUR_OF_DAY, 0); - this.set(Calendar.MINUTE, 0); - this.set(Calendar.SECOND, 0); - this.set(Calendar.MILLISECOND, 0); - this.add(Calendar.MONTH, 1); + set(Calendar.DATE, 1); + set(Calendar.HOUR_OF_DAY, 0); + set(Calendar.MINUTE, 0); + set(Calendar.SECOND, 0); + set(Calendar.MILLISECOND, 0); + add(Calendar.MONTH, 1); break; default: throw new IllegalStateException("Unknown periodicity type."); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/messages/structures/DictionaryComparator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/messages/structures/DictionaryComparator.java index 516cd42f..0ff3c014 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/messages/structures/DictionaryComparator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/messages/structures/DictionaryComparator.java @@ -15,7 +15,9 @@ ******************************************************************************/ package com.exactpro.sf.common.messages.structures; +import static com.exactpro.sf.common.messages.structures.StructureUtils.castValueToJavaType; import static com.exactpro.sf.common.messages.structures.StructureUtils.getAttributeValue; +import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.indexOf; @@ -36,7 +38,6 @@ import com.exactpro.sf.common.messages.structures.loaders.IDictionaryStructureLoader; import com.exactpro.sf.common.messages.structures.loaders.XmlDictionaryStructureLoader; import com.google.common.base.Objects; -import com.google.common.collect.Iterables; public class DictionaryComparator { @@ -92,7 +93,7 @@ private static void displayDifference(DistinctionType distinctionType, Object fi if (distinctionType != null) { builder.append(" - ").append(distinctionType); } - System.out.println(builder.toString()); + System.out.println(builder); } public void compare(IDiffListener listener, IDictionaryStructure one, IDictionaryStructure two, boolean compareOrder, boolean checkByFirst, boolean deepCheck) { @@ -101,12 +102,10 @@ public void compare(IDiffListener listener, IDictionaryStructure one, IDictionar path = new DictionaryPath(one.getNamespace()); equal(listener, one.getDescription(), two.getDescription(), path, DistinctionType.Description); - Iterable iterable; - if (checkByFirst) { - iterable = one.getMessages().values(); - } else { - iterable = Iterables.concat(one.getMessages().values(), two.getMessages().values()); - } + Iterable iterable = checkByFirst + ? one.getMessages().values() + : concat(one.getMessages().values(), two.getMessages().values()); + Set names = getNames(iterable); for (String name : names) { compare(listener, one.getMessages().get(name), two.getMessages().get(name), new DictionaryPath(path).setMessage(name), @@ -114,11 +113,7 @@ public void compare(IDiffListener listener, IDictionaryStructure one, IDictionar } - if (checkByFirst) { - iterable = one.getFields().values(); - } else { - iterable = Iterables.concat(one.getFields().values(), two.getFields().values()); - } + iterable = checkByFirst ? one.getFields().values() : concat(one.getFields().values(), two.getFields().values()); names = getNames(iterable); for (String name : names) { compare(listener, one.getFields().get(name), two.getFields().get(name), new DictionaryPath(path).setField(name), @@ -247,11 +242,7 @@ private JavaType safeJavaType(IFieldStructure fieldStructure) { private Object safeCastValue(IAttributeStructure attributeStructure) { if (attributeStructure != null) { - if (this.typedCheck) { - return attributeStructure.getCastValue(); - } else { - return attributeStructure.getValue(); - } + return typedCheck ? attributeStructure.getCastValue() : attributeStructure.getValue(); } return null; } @@ -275,10 +266,7 @@ private String safeField(IFieldStructure fieldStructure, int subFieldIndex){ private int safeFieldIndex(IFieldStructure fieldStructureOne, IFieldStructure fieldStructureTwo, String subFieldName) { try { int result = indexOf(fieldStructureOne.getFields().keySet(), subFieldName::equals); - if(result == -1){ - result = indexOf(fieldStructureTwo.getFields().keySet(), subFieldName::equals); - } - return result; + return result == -1 ? indexOf(fieldStructureTwo.getFields().keySet(), subFieldName::equals) : result; } catch (UnsupportedOperationException e) { return -1; } @@ -301,10 +289,7 @@ private Set safeFieldNames(IFieldStructure fieldStructure) { } private Object tryToCast(IFieldStructure fieldStructure, Object value) { - if (!this.typedCheck && value instanceof String) { - value = StructureUtils.castValueToJavaType((String)value, fieldStructure.getJavaType()); - } - return value; + return !typedCheck && value instanceof String ? castValueToJavaType((String)value, fieldStructure.getJavaType()) : value; } public static class DictionaryPath { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/profiler/Profiler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/profiler/Profiler.java index 8803d296..706a64fa 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/profiler/Profiler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/profiler/Profiler.java @@ -19,6 +19,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.time.StopWatch; @@ -28,7 +29,7 @@ public class Profiler { - private static Logger logger = LoggerFactory.getLogger(Profiler.class); + private static final Logger logger = LoggerFactory.getLogger(Profiler.class); private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static Profiler instance; @@ -52,26 +53,27 @@ public static Profiler getInstance() { public void startTrace(String... tracesNames) { - if (tracesNames != null) + if(tracesNames != null) { for (String traceName : tracesNames) { - synchronized (this.traceMap) { - if (!this.traceMap.containsKey(traceName)) { + synchronized(traceMap) { + if(!traceMap.containsKey(traceName)) { Trace trace = new Trace(traceName); trace.startMethod(); - this.traceMap.put(traceName, trace); + traceMap.put(traceName, trace); } else { logger.debug("Trace {} already started", traceName); } } } + } } public void endTrace(String... tracesNames) { - if (tracesNames != null) + if(tracesNames != null) { for (String traceName : tracesNames) { - synchronized (this.traceMap) { - Trace trace = this.traceMap.remove(traceName); + synchronized(traceMap) { + Trace trace = traceMap.remove(traceName); if (trace != null) { trace.stop(); trace.stopMethod(); @@ -81,31 +83,34 @@ public void endTrace(String... tracesNames) { } } } + } } public void startMethod(String... tracesNames) { - if (tracesNames != null) + if(tracesNames != null) { for (String traceName : tracesNames) { - Trace trace = this.traceMap.get(traceName); + Trace trace = traceMap.get(traceName); if (trace != null) { trace.startMethod(); } else { logger.debug("Trace {} is absent", traceName); } } + } } public void stopMethod(String... tracesNames) { - if (tracesNames != null) + if(tracesNames != null) { for (String traceName : tracesNames) { - Trace trace = this.traceMap.get(traceName); + Trace trace = traceMap.get(traceName); if (trace != null) { trace.stopMethod(); } else { logger.debug("Trace {} is absent", traceName); } } + } } private class Trace extends Method { @@ -119,10 +124,10 @@ public Trace(String name) { public void startMethod() { synchronized (this) { Thread thread = Thread.currentThread(); - List methodList = this.methodMap.get(thread.getId()); + List methodList = methodMap.get(thread.getId()); if (methodList == null) { methodList = new ArrayList<>(); - this.methodMap.put(thread.getId(), methodList); + methodMap.put(thread.getId(), methodList); } StackTraceElement stackTraceElement = thread.getStackTrace()[3]; String name = stackTraceElement.getClassName() + "." +stackTraceElement.getMethodName(); @@ -141,7 +146,7 @@ public void startMethod() { public void stopMethod() { synchronized (this) { Thread thread = Thread.currentThread(); - List methodList = this.methodMap.get(thread.getId()); + List methodList = methodMap.get(thread.getId()); if (methodList != null) { StackTraceElement stackTraceElement = thread.getStackTrace()[3]; String name = stackTraceElement.getClassName() + "." +stackTraceElement.getMethodName(); @@ -163,15 +168,15 @@ public void stopMethod() { public String toString() { synchronized (this) { StringBuilder builder = new StringBuilder("Trace : "); - builder.append(this.name); + builder.append(name); builder.append(LINE_SEPARATOR); - for (Map.Entry> threadList : this.methodMap.entrySet()) { + for(Entry> threadList : methodMap.entrySet()) { builder.append("Thread : "); builder.append(threadList.getKey()); builder.append(LINE_SEPARATOR); for (Method method : threadList.getValue()) { builder.append(String.format("%" + (method.getLevel() + 1) + "s", "")); - builder.append(method.toString()); + builder.append(method); builder.append(LINE_SEPARATOR); } } @@ -188,30 +193,26 @@ private class Method { public Method(String name, int level) { this.stopWatch = new StopWatch(); - this.stopWatch.start(); + stopWatch.start(); this.name = name; this.level = level; } public void stop() { - this.stopWatch.stop(); + stopWatch.stop(); } public boolean isStopped() { - return this.stopWatch.isStopped(); + return stopWatch.isStopped(); } public int getLevel() { - return this.level; + return level; } @Override public String toString() { - if (this.stopWatch.isStopped()) { - return this.name + " " + this.stopWatch.getTime(); - } else { - return this.name + " progress ..."; - } + return name + " " + (stopWatch.isStopped() ? stopWatch.getTime() : "progress ..."); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/BeanConfigurator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/BeanConfigurator.java index face3e72..71c422db 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/BeanConfigurator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/BeanConfigurator.java @@ -17,7 +17,6 @@ import java.beans.PropertyDescriptor; - import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.PropertyUtilsBean; @@ -40,9 +39,10 @@ public static void loadBean(HierarchicalConfiguration context, Object beanObject if ( descr.getWriteMethod() != null ) { String value = context.getString(descr.getName()); - - if ( converter.lookup(descr.getPropertyType()) != null ) - BeanUtils.setProperty(beanObject, descr.getName(), converter.convert(value, descr.getPropertyType())); + + if(converter.lookup(descr.getPropertyType()) != null) { + BeanUtils.setProperty(beanObject, descr.getName(), converter.convert(value, descr.getPropertyType())); + } } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ErrorUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ErrorUtil.java index cd1ab730..74fa8b73 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ErrorUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ErrorUtil.java @@ -34,7 +34,7 @@ public static String formatException(Throwable e) StringBuilder sb = new StringBuilder(); sb - .append(e.toString()) + .append(e) .append(EOL); sb.append(formatStackTrace(e.getStackTrace())); @@ -55,7 +55,7 @@ public static String formatStackTrace(StackTraceElement[] stackTraceElements) { { sb .append("\tat ") - .append(element.toString()) + .append(element) .append(EOL); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/GenericConverter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/GenericConverter.java index c392870f..61864b2a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/GenericConverter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/GenericConverter.java @@ -23,16 +23,11 @@ public final class GenericConverter { - private static Charset charsetISO_8859 = Charset.forName("ISO-8859-1"); + private static final Charset charsetISO_8859 = Charset.forName("ISO-8859-1"); //private static CharsetDecoder charsetDecoder = charsetISO_8859.newDecoder(); //private static CharsetEncoder charsetEncoder = charsetISO_8859.newEncoder(); - public GenericConverter() - { - } - - - /** + /** * Convert String to byte array. * Characters in result byte array will be left aligned. * Missed characters will be filled by ' '(space). @@ -44,11 +39,7 @@ public GenericConverter() public static byte[] convertStringToArray(int length, String value) { byte[] byteArray = String.format( "%-" + length + "s", value == null ? "" : value ).getBytes(charsetISO_8859); - - if (byteArray.length != length) - return Arrays.copyOf(byteArray, length); // truncate array - else - return byteArray; + return byteArray.length != length ? Arrays.copyOf(byteArray, length) : byteArray; // truncate array } public static byte[] convertSignedNumericToArray(int length, T value ) @@ -59,9 +50,8 @@ public static byte[] convertSignedNumericToArray(int length, public static byte[] convertSignedNumericToArray(int length, T value, int precision ) { - byte[] byteArray = new byte[length]; - // Pattern for fractional part + // Pattern for fractional part char[] arrFractional = new char[precision]; Arrays.fill(arrFractional, '0'); @@ -77,8 +67,7 @@ public static byte[] convertSignedNumericToArray(int length, String formattedValue = formatter.format(value); DecimalFormatSymbols decimalFormatSymbol = formatter.getDecimalFormatSymbols(); formattedValue = formattedValue.replace(String.valueOf(decimalFormatSymbol.getDecimalSeparator()), ""); - byteArray = formattedValue.getBytes(charsetISO_8859); - return byteArray; + return formattedValue.getBytes(charsetISO_8859); } @@ -90,9 +79,8 @@ public static byte[] convertUnsignedNumericToArray(int length public static byte[] convertUnsignedNumericToArray(int length, T value, int precision ) { - byte[] byteArray = new byte[length]; - // Pattern for fractional part + // Pattern for fractional part char[] arrFractional = new char[precision]; Arrays.fill(arrFractional, '0'); @@ -108,8 +96,7 @@ public static byte[] convertUnsignedNumericToArray(int length String formattedValue = formatter.format(value); DecimalFormatSymbols decimalFormatSymbol = formatter.getDecimalFormatSymbols(); formattedValue = formattedValue.replace(String.valueOf(decimalFormatSymbol.getDecimalSeparator()), ""); - byteArray = formattedValue.getBytes(charsetISO_8859); - return byteArray; + return formattedValue.getBytes(charsetISO_8859); } @@ -155,9 +142,9 @@ public static Double convertByteArrayToAnyDouble( int length, byte[] byteArray, { String stringValue = convertByteArrayToString( length, byteArray ); - if(0 != precision) + if(precision != 0) { - stringValue = ((new StringBuffer(stringValue )).insert(length - precision, ".")).toString(); + stringValue = new StringBuilder(stringValue).insert(length - precision, ".").toString(); } return Double.parseDouble( stringValue ); } @@ -166,9 +153,9 @@ public static BigDecimal convertByteArrayToAnyDecimal( int length, byte[] byteAr { String stringValue = convertByteArrayToString( length, byteArray ); - if(0 != precision) + if(precision != 0) { - stringValue = ((new StringBuffer(stringValue )).insert(length - precision, ".")).toString(); + stringValue = new StringBuilder(stringValue).insert(length - precision, ".").toString(); } return new BigDecimal( stringValue ); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/HexDumper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/HexDumper.java index 7d8fd8aa..e189f050 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/HexDumper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/HexDumper.java @@ -15,11 +15,11 @@ ******************************************************************************/ package com.exactpro.sf.common.util; -import org.apache.mina.core.buffer.IoBuffer; - import java.util.ArrayList; import java.util.List; +import org.apache.mina.core.buffer.IoBuffer; + public class HexDumper { private static final int BYTES_COLUMN_WIDTH = 16*2+8; @@ -77,19 +77,19 @@ public HexDumper(byte[] data) { bytesColumn.append(" "); } - this.addresses.add(addressColumn.toString()); - this.bytes.add(bytesColumn.toString()); - this.printableStrings.add(printableColumn.toString()); + addresses.add(addressColumn.toString()); + bytes.add(bytesColumn.toString()); + printableStrings.add(printableColumn.toString()); } } public String getHexdump() { StringBuilder result = new StringBuilder(); - for (int i=0; i lengthLimit; - int size; - if (truncate) { - size = lengthLimit; - } else { - size = in.remaining(); - } + int size = truncate ? lengthLimit : in.remaining(); - if (size == 0) { + if(size == 0) { return new byte[0]; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ICommonSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ICommonSettings.java index 98c5ee1b..d4854000 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ICommonSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/ICommonSettings.java @@ -30,5 +30,5 @@ public interface ICommonSettings * * @param config - source of settings */ - public void load(final HierarchicalConfiguration config); + void load(HierarchicalConfiguration config); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidRangeException.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidRangeException.java index b60df674..a74bdc78 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidRangeException.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidRangeException.java @@ -24,8 +24,7 @@ public class InvalidRangeException extends RuntimeException { public InvalidRangeException() { - super(); - } + } public InvalidRangeException(String message) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidXMLCharacterException.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidXMLCharacterException.java index 8eee4639..b824f326 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidXMLCharacterException.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/InvalidXMLCharacterException.java @@ -65,7 +65,7 @@ public int getInvalidCharacterLine() { } public String getInfo() { - return new StringBuilder(this.getMessage()) + return new StringBuilder(getMessage()) .append(", column: ") .append(invalidCharacterColumn) .append(", line: ") diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/Range.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/Range.java index cd620c86..c05f585c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/Range.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/common/util/Range.java @@ -27,7 +27,7 @@ public class Range { private String origRange; - private List operators; + private final List operators; public static Range newInstance(String s) { @@ -49,23 +49,19 @@ private Range() @Override public String toString() { - return this.origRange; + return origRange; } public String toStringEx() { StringBuilder sb = new StringBuilder(); - - for (int i=0; i= "+this.number; + return "X >= " + number; } } @@ -309,12 +307,12 @@ protected Condition_Greater(long n) { @Override protected boolean checkCondition(long n) { - return n > this.number; + return n > number; } @Override public String toString() { - return "X > "+this.number; + return "X > " + number; } } @@ -326,20 +324,17 @@ protected Operator() { } protected abstract boolean match(long n); protected void add(AbstractCondition cond) { - this.conditions.add(cond); + conditions.add(cond); } } protected class OP_AND extends Operator { - protected OP_AND() { - super(); - } - @Override + @Override protected boolean match(long n) { - for (AbstractCondition a : this.conditions) + for(AbstractCondition a : conditions) { if (!a.checkCondition(n)) { return false; @@ -352,9 +347,9 @@ protected boolean match(long n) public String toString() { StringBuilder sb = new StringBuilder(); - for (int i=0; i - { - private boolean first; - private boolean excludeExt; - - public FileSpecialComparator(boolean first, boolean excludeExt) - { - this.first = first; - this.excludeExt = excludeExt; - } - - - @Override - public int compare(File o1, File o2) - { - int end_index = 0; - int start_index = 0; - - if ( first ) - { - if ( !excludeExt ) - { - end_index = o1.getName().lastIndexOf("_"); - start_index = o1.getName().lastIndexOf("_", end_index - 1); - } - else - { - end_index = getFileNameWithoutExt(o1.getName()).lastIndexOf("_"); - start_index = getFileNameWithoutExt(o1.getName()).lastIndexOf("_", end_index - 1); - } - - } - else - { - if ( !excludeExt ) - { - start_index = o1.getName().lastIndexOf("_"); - end_index = o1.getName().length(); - } - else - { - start_index = getFileNameWithoutExt(o1.getName()).lastIndexOf("_"); - end_index = getFileNameWithoutExt(o1.getName()).length(); - } - } - - long l1 = Long.parseLong(o1.getName().substring(start_index + 1, end_index)); - - if ( first ) - { - if ( !excludeExt ) - { - end_index = o2.getName().lastIndexOf("_"); - start_index = o2.getName().lastIndexOf("_", end_index - 1); - } - else - { - end_index = getFileNameWithoutExt(o2.getName()).lastIndexOf("_"); - start_index = getFileNameWithoutExt(o2.getName()).lastIndexOf("_", end_index - 1); - } - - } - else - { - if ( !excludeExt ) - { - start_index = o2.getName().lastIndexOf("_"); - end_index = o2.getName().length(); - } - else - { - start_index = getFileNameWithoutExt(o2.getName()).lastIndexOf("_"); - end_index = getFileNameWithoutExt(o2.getName()).length(); - } - } - - long l2 = Long.parseLong(o2.getName().substring(start_index + 1, end_index)); - - if ( l1 == l2 ) - return 0; - - if ( l1 > l2 ) - return 1; - else - return -1; - } - } - - - - public static class FileComparator implements Comparator - { - private CompType type; - private String prefix; - private boolean extension; - - public FileComparator(CompType type, String prefix, boolean extension) - { - this.type = type; - this.prefix = prefix; - this.extension = extension; - } - - - @Override - public int compare(File o1, File o2) - { - if ( type == CompType.TIME ) - { - if ( o1.lastModified() < o2.lastModified() ) - return -1; - else if ( o1.lastModified() > o2.lastModified() ) - return 1; - - return 0; - } - else if ( type == CompType.NAME ) - { - return o1.getName().compareTo(o2.getName()); - } - else if ( type == CompType.END_NAME ) - { - String os1 = null; - - if ( o1.getName().length() == this.prefix.length() ) - os1 = "0"; - else - { - if ( !this.extension ) - os1 = o1.getName().substring(this.prefix.length()); - else - os1 = getFileNameWithoutExt(o1.getName()).substring(this.prefix.length()); - } - - String os2 = null; - - if ( o2.getName().length() == this.prefix.length() ) - os2 = "0"; - else - { - if ( !this.extension ) - os2 = o2.getName().substring(this.prefix.length()); - else - os2 = getFileNameWithoutExt(o2.getName()).substring(this.prefix.length()); - } - - return Integer.parseInt(os1) - Integer.parseInt(os2); - } - else if ( type == CompType.TIME_END_NAME ) - { - if ( o1.lastModified() < o2.lastModified() ) - return -1; - else if ( o1.lastModified() > o2.lastModified() ) - return 1; - - String os1 = null; - - if ( o1.getName().length() == this.prefix.length() ) - os1 = "0"; - else - { - if ( !this.extension ) - os1 = o1.getName().substring(this.prefix.length()); - else - os1 = getFileNameWithoutExt(o1.getName()).substring(this.prefix.length()); - } - - String os2 = null; - - if ( o2.getName().length() == this.prefix.length() ) - os2 = "0"; - else - { - if ( !this.extension ) - os2 = o2.getName().substring(this.prefix.length()); - else - os2 = getFileNameWithoutExt(o2.getName()).substring(this.prefix.length()); - } - - return Integer.parseInt(os1) - Integer.parseInt(os2); - - } - else throw new IllegalArgumentException("Unknown CompType = [" + type + "]"); - } - } - - public static class FileExtensionFilter implements FileFilter{ - - private String ext; - - public FileExtensionFilter(String ext){ - this.ext = ext; - } - - @Override - public boolean accept(File file) { - return file.getName().endsWith("."+ext); - } - - } - - public static class FileNameFilter implements FileFilter - { - private final String fileNamePrefix; - - - public FileNameFilter(final String fileNamePrefix) - { - this.fileNamePrefix = fileNamePrefix; - } - - - @Override - public boolean accept(File file) - { - if ( file.getName().startsWith(this.fileNamePrefix) ) - return true; - - return false; - } - } - - - - - public static String getFileNameWithoutExt(String fileName) - { - int pos = fileName.lastIndexOf("."); - - if ( pos != -1 ) - fileName = fileName.substring(0, pos); - - return fileName; - } - - - public static long retrieveStartTimeForCalculating(File latencyFolder, File inputFolder, File outputFolder, long maxLatencyWindow) - { - File[] files = latencyFolder.listFiles(); - - Arrays.sort(files, new Utils.FileSpecialComparator(true, false)); - - if ( files.length > 0 ) - { - int i = 0; - - boolean calculate = false; - - long startInterval = 0; - - int startFileIndex = 0; - - File lastLatFile = files[files.length - 1]; - - File[] inputFiles = inputFolder.listFiles(); - - Arrays.sort(inputFiles, new Utils.FileSpecialComparator(true, false)); - - i = 0; - - for ( ; i < inputFiles.length; ++i ) - { - if ( FileUtils.isFileOlder(inputFiles[inputFiles.length - 1 - i], lastLatFile) ) - break; - } - - startFileIndex = inputFiles.length - i; - - if ( startFileIndex < inputFiles.length ) - { - calculate = true; - - long startTimeStamp = determineStartInterval(inputFiles[startFileIndex].getName()); - - startInterval = startTimeStamp / (maxLatencyWindow*1000000); - } - - File[] outputFiles = outputFolder.listFiles(); - - Arrays.sort(outputFiles, new Utils.FileSpecialComparator(true, false)); - - i = 0; - - for ( ; i < outputFiles.length; ++i ) - { - if ( FileUtils.isFileOlder(outputFiles[outputFiles.length - 1 - i], lastLatFile) ) - break; - } - - startFileIndex = outputFiles.length - i; - - if ( startFileIndex < outputFiles.length ) - { - long startTimeStamp = determineStartInterval(outputFiles[startFileIndex].getName()); - - long tempStartInterval = startTimeStamp / (maxLatencyWindow*1000000); - - if ( calculate ) - { - if ( startInterval > tempStartInterval ) - startInterval = tempStartInterval; - } - else - { - startInterval = tempStartInterval; - calculate = true; - } - } - - if ( calculate ) - return maxLatencyWindow*startInterval; - else - return -1; - } - - return 0; - } - - - - public static long retrieveStartTimeForCalculating(String latencyFolderName, long maxLatencyWindow) - { - File latencyFolder = new File(latencyFolderName); - - if ( latencyFolder.exists() ) - { - File[] files = latencyFolder.listFiles(); - - Arrays.sort(files, new Utils.FileComparator(CompType.TIME, "", false)); - - if ( files.length == 0 || files.length == 1 ) - return 0; - - return maxLatencyWindow*(files.length - 2); - } - else - throw new EPSCommonException("Could not find [" + latencyFolderName + "] folder with latency files"); - } - - - public static void generateInputFile(String folderName, long startTimeInSec, long finishTimeInSec, String generatingFile) throws IOException - { - File folder = new File(folderName); - - if ( folder.exists() ) - { - File[] files = folder.listFiles(); - - Arrays.sort(files, new Utils.FileSpecialComparator(true, false)); - - if ( files.length == 0 ) - return; - - int index = ( files.length - 1 ); - for ( ; index >= 0; --index ) - { - long startInterval = determineStartInterval(files[index].getName()); - - if ( startInterval < startTimeInSec*1000000 ) - break; - } - - if ( index < 0 ) - index = 0; - - - - BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile)); - - for ( int i = index; i < files.length; ++i ) - { - if ( isDebugged ) - { - logger.debug(files[i].getName()); - } - - CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); - reader.setSafetySwitch(false); - - reader.readRecord(); - - if ( i == index ) - { - writer.write(reader.getRawRecord()); - writer.newLine(); - } - - while ( reader.readRecord() ) - { - long timestamp = Long.parseLong(reader.getValues()[0]); - - if ( timestamp >= startTimeInSec*1000000 && ( timestamp < finishTimeInSec*1000000 || finishTimeInSec == Long.MAX_VALUE )) - { - writer.write(reader.getRawRecord()); - writer.newLine(); - } - else if ( timestamp < startTimeInSec*1000000 ) - { - } - else - break; - - } - - reader.close(); - } - - writer.close(); - - } - else - throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); - } - - - public static void generateMDLatFile(String folderName, long startTimeInSec, long finishTimeInSec, String generatingFile, SimpleDateFormat format, String analyzedField, long startSec) throws IOException - { - File folder = new File(folderName); - - if ( folder.exists() ) - { - File[] files = folder.listFiles(); - - Arrays.sort(files, new Utils.FileSpecialComparator(true, false)); - - if ( files.length == 0 ) - return; - - int index = ( files.length - 1 ); - for ( ; index >= 0; --index ) - { - long startInterval = determineStartInterval(files[index].getName()); - - if ( startInterval < startTimeInSec*1000000 ) - break; - } - - if ( index < 0 ) - index = 0; - - - try(BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile))) { - int fieldIndex = -1; - - for(int i = index; i < files.length; ++i) { - if(isDebugged) { - logger.debug(files[i].getName()); - } - - CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); - reader.setSafetySwitch(false); - - reader.readRecord(); - - if(i == index) { - - String[] headers = reader.getValues(); - - for(int j = 0; j < headers.length; ++j) { - if(headers[j].equals(analyzedField)) { - fieldIndex = j; - break; - } - } - - writer.write("Timestamp,Latency"); - - for(int j = 3; j < headers.length; ++j) - writer.write("," + headers[j]); - - writer.newLine(); - - if(fieldIndex == -1) - throw new IllegalArgumentException("Could not find fieldName = [" + analyzedField + "] in inputFile = [" + files[i].getName() + "]"); - } - - while(reader.readRecord()) { - String[] values = reader.getValues(); - - long timestamp = Long.parseLong(values[0]); - - if(timestamp >= startTimeInSec * 1000000 && (timestamp < finishTimeInSec * 1000000 || finishTimeInSec == Long.MAX_VALUE)) { - try { - String sendingTime = values[fieldIndex]; - - long sendingTimestamp = format.parse(sendingTime + " +0000").getTime(); - - sendingTimestamp = (sendingTimestamp - startSec * 1000) * 1000; - - writer.write(values[0] + "," + Long.toString(timestamp - sendingTimestamp)); - - for(int j = 3; j < values.length; ++j) - writer.write("," + values[j]); - - writer.newLine(); - } catch(ParseException e) { - } - - } else if(timestamp < startTimeInSec * 1000000) { - } else - break; - - } - - reader.close(); - } - } - } - else - throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); - } - - - - - - - - public static void generateFakeInputFile(String folderName, long startTimeInSec, long finishTimeInSec, String generatingFile) throws IOException - { - File folder = new File(folderName); - - if ( folder.exists() ) - { - File[] files = folder.listFiles(); - - Arrays.sort(files, new Utils.FileSpecialComparator(true, false)); - - if ( files.length == 0 ) - return; - - int index = ( files.length - 1 ); - for ( ; index >= 0; --index ) - { - long startInterval = determineStartInterval(files[index].getName()); - - if ( startInterval < startTimeInSec*1000000 ) - break; - } - - if ( index < 0 ) - index = 0; - - BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile)); - - - boolean firstRecordWritten = false; - - for ( int i = index; i < files.length; ++i ) - { - if ( isDebugged ) - { - logger.debug(files[i].getName()); - } - - CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); - reader.setSafetySwitch(false); - - reader.readRecord(); - - if ( i == index ) - { - writer.write(reader.getRawRecord()); - writer.newLine(); - } - - - if ( !firstRecordWritten || i == files.length - 1) - { - String lastRecord = ""; - - while ( reader.readRecord() ) - { - long timestamp = Long.parseLong(reader.getValues()[0]); - - lastRecord = reader.getRawRecord(); - - if ( !firstRecordWritten ) - { - if ( timestamp >= startTimeInSec*1000000 && ( timestamp < finishTimeInSec*1000000 || finishTimeInSec == Long.MAX_VALUE )) - { - writer.write(reader.getRawRecord()); - writer.newLine(); - firstRecordWritten = true; - } - else if ( timestamp < startTimeInSec*1000000 ) - { - } - else - break; - } - } - - writer.write(lastRecord); - } - - reader.close(); - } - - writer.close(); - - } - else - throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); - } - - - - - - - - - - - - - - - - - - - - public static long determineFinishInterval(String fileName) - { - long finishTime = Long.parseLong(Utils.getFileNameWithoutExt(fileName).substring(Utils.getFileNameWithoutExt(fileName).lastIndexOf("_") + 1)); - - return finishTime; - } - - - public static long determineStartInterval(String fileName) - { - int lastIndex = fileName.lastIndexOf("_"); - - if ( lastIndex == -1 ) - throw new EPSCommonException("Incorrect file name = [" + fileName + "]"); - - int prevIndex = fileName.lastIndexOf("_", lastIndex - 1); - - long startTime = Long.parseLong(fileName.substring(prevIndex + 1, lastIndex)); - - return startTime; - } - - - public static void mergeFiles(String folderName, String generatingFile) throws IOException - { - File folder = new File(folderName); - - if ( folder.exists() ) - { - File[] files = folder.listFiles(); - - Arrays.sort(files, new Utils.FileComparator(CompType.TIME, "", false)); - - if ( files.length == 0 ) - return; - - BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile)); - - for ( int i = 0; i < files.length; ++i ) - { - CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); - reader.setSafetySwitch(false); - - reader.readRecord(); - - if ( i == 0 ) - { - writer.write(reader.getRawRecord()); - writer.newLine(); - } - - while ( reader.readRecord() ) - { - writer.write(reader.getRawRecord()); - writer.newLine(); - } - - reader.close(); - } - - writer.close(); - - } - else - throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); - } - - - public static boolean lockFile(File file) throws IOException - { - String lockFileName = "." + file.getName(); - - File lockFile = new File(file.getParentFile(), lockFileName); - - return lockFile.createNewFile(); - } - - - public static boolean unlockFile(File file) throws IOException - { - String lockFileName = "." + file.getName(); - - File lockFile = new File(file.getParentFile(), lockFileName); - - return lockFile.delete(); - } - - - public static void deleteFileWithoutException(String destFile) - { - try - { - FileUtils.forceDelete(new File(destFile)); - } - catch ( Exception e ) - { - - } - } - - - public static void deleteFileWithoutException(File destFile) - { - try - { - FileUtils.forceDelete(destFile); - } - catch ( Exception e ) - { - - } - } - - public static String getTagColorClass(String name) { - if(name != null) { - return TAG_COLOR_CLASSES[Math.abs(name.hashCode()) % TAG_COLOR_CLASSES.length]; - } - - return TAG_COLOR_CLASSES[0]; - } -} +/****************************************************************************** + * Copyright 2009-2018 Exactpro (Exactpro Systems Limited) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.exactpro.sf.common.util; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileFilter; +import java.io.FileWriter; +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Objects; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.csvreader.CsvReader; + + +public class Utils +{ + private static final Logger logger = LoggerFactory.getLogger(Utils.class); + private static final boolean isDebugged = logger.isDebugEnabled(); + + private static final String[] TAG_COLOR_CLASSES = {"turquoise", "preaver", "amethyst", "green-sea", + "belize-hole", "wisteria", "sun-flower", "carrot", "clouds", "orange", "silver"}; + + public enum CompType + { + TIME, + NAME, + END_NAME, + TIME_END_NAME + } + + public static long determineStartSecFromParsedFile(String parsedFileName) throws IOException + { + CsvReader parsedReader = new CsvReader(parsedFileName); + + parsedReader.setSafetySwitch(false); + + parsedReader.readHeaders(); + + parsedReader.readRecord(); + + long startSec = Long.parseLong(parsedReader.getValues()[0]); + + parsedReader.close(); + + return startSec; + } + + + public static class FileSpecialComparator implements Comparator + { + private final boolean first; + private final boolean excludeExt; + + public FileSpecialComparator(boolean first, boolean excludeExt) + { + this.first = first; + this.excludeExt = excludeExt; + } + + + @Override + public int compare(File o1, File o2) + { + int end_index = 0; + int start_index = 0; + + if ( first ) + { + if ( !excludeExt ) + { + end_index = o1.getName().lastIndexOf("_"); + start_index = o1.getName().lastIndexOf("_", end_index - 1); + } + else + { + end_index = getFileNameWithoutExt(o1.getName()).lastIndexOf("_"); + start_index = getFileNameWithoutExt(o1.getName()).lastIndexOf("_", end_index - 1); + } + + } + else + { + if ( !excludeExt ) + { + start_index = o1.getName().lastIndexOf("_"); + end_index = o1.getName().length(); + } + else + { + start_index = getFileNameWithoutExt(o1.getName()).lastIndexOf("_"); + end_index = getFileNameWithoutExt(o1.getName()).length(); + } + } + + long l1 = Long.parseLong(o1.getName().substring(start_index + 1, end_index)); + + if ( first ) + { + if ( !excludeExt ) + { + end_index = o2.getName().lastIndexOf("_"); + start_index = o2.getName().lastIndexOf("_", end_index - 1); + } + else + { + end_index = getFileNameWithoutExt(o2.getName()).lastIndexOf("_"); + start_index = getFileNameWithoutExt(o2.getName()).lastIndexOf("_", end_index - 1); + } + + } + else + { + if ( !excludeExt ) + { + start_index = o2.getName().lastIndexOf("_"); + end_index = o2.getName().length(); + } + else + { + start_index = getFileNameWithoutExt(o2.getName()).lastIndexOf("_"); + end_index = getFileNameWithoutExt(o2.getName()).length(); + } + } + + long l2 = Long.parseLong(o2.getName().substring(start_index + 1, end_index)); + return Long.compare(l1, l2); + } + } + + + + public static class FileComparator implements Comparator + { + private final CompType type; + private final String prefix; + private final boolean extension; + + public FileComparator(CompType type, String prefix, boolean extension) + { + this.type = type; + this.prefix = prefix; + this.extension = extension; + } + + + @Override + public int compare(File o1, File o2) + { + if ( type == CompType.TIME ) + { + return Long.compare(o1.lastModified(), o2.lastModified()); + } + else if ( type == CompType.NAME ) + { + return o1.getName().compareTo(o2.getName()); + } + else if ( type == CompType.END_NAME ) + { + String os1 = null; + + if(o1.getName().length() == prefix.length()) { + os1 = "0"; + } else + { + if(!extension) { + os1 = o1.getName().substring(prefix.length()); + } else { + os1 = getFileNameWithoutExt(o1.getName()).substring(prefix.length()); + } + } + + String os2 = null; + + if(o2.getName().length() == prefix.length()) { + os2 = "0"; + } else + { + if(!extension) { + os2 = o2.getName().substring(prefix.length()); + } else { + os2 = getFileNameWithoutExt(o2.getName()).substring(prefix.length()); + } + } + + return Integer.parseInt(os1) - Integer.parseInt(os2); + } + else if ( type == CompType.TIME_END_NAME ) + { + if(o1.lastModified() < o2.lastModified()) { + return -1; + } else if(o1.lastModified() > o2.lastModified()) { + return 1; + } + + String os1 = null; + + if(o1.getName().length() == prefix.length()) { + os1 = "0"; + } else + { + if(!extension) { + os1 = o1.getName().substring(prefix.length()); + } else { + os1 = getFileNameWithoutExt(o1.getName()).substring(prefix.length()); + } + } + + String os2 = null; + + if(o2.getName().length() == prefix.length()) { + os2 = "0"; + } else + { + os2 = !extension ? o2.getName().substring(prefix.length()) : getFileNameWithoutExt(o2.getName()).substring(prefix.length()); + } + + return Integer.parseInt(os1) - Integer.parseInt(os2); + + } else { + throw new IllegalArgumentException("Unknown CompType = [" + type + "]"); + } + } + } + + public static class FileExtensionFilter implements FileFilter{ + + private final String ext; + + public FileExtensionFilter(String ext){ + this.ext = ext; + } + + @Override + public boolean accept(File file) { + return file.getName().endsWith("."+ext); + } + + } + + public static class FileNameFilter implements FileFilter + { + private final String fileNamePrefix; + + public FileNameFilter(String fileNamePrefix) + { + this.fileNamePrefix = fileNamePrefix; + } + + + @Override + public boolean accept(File file) + { + return file.getName().startsWith(fileNamePrefix); + } + } + + + + + public static String getFileNameWithoutExt(String fileName) + { + return FilenameUtils.removeExtension(fileName); + } + + + public static long retrieveStartTimeForCalculating(File latencyFolder, File inputFolder, File outputFolder, long maxLatencyWindow) + { + File[] files = latencyFolder.listFiles(); + + Arrays.sort(files, new FileSpecialComparator(true, false)); + + if ( files.length > 0 ) + { + + boolean calculate = false; + + long startInterval = 0; + + File lastLatFile = files[files.length - 1]; + + File[] inputFiles = inputFolder.listFiles(); + + Arrays.sort(inputFiles, new FileSpecialComparator(true, false)); + + int i = 0; + + for ( ; i < inputFiles.length; ++i ) + { + if(FileUtils.isFileOlder(inputFiles[inputFiles.length - 1 - i], lastLatFile)) { + break; + } + } + + int startFileIndex = inputFiles.length - i; + + if ( startFileIndex < inputFiles.length ) + { + calculate = true; + + long startTimeStamp = determineStartInterval(inputFiles[startFileIndex].getName()); + + startInterval = startTimeStamp / (maxLatencyWindow*1000000); + } + + File[] outputFiles = outputFolder.listFiles(); + + Arrays.sort(outputFiles, new FileSpecialComparator(true, false)); + + i = 0; + + for ( ; i < outputFiles.length; ++i ) + { + if(FileUtils.isFileOlder(outputFiles[outputFiles.length - 1 - i], lastLatFile)) { + break; + } + } + + startFileIndex = outputFiles.length - i; + + if ( startFileIndex < outputFiles.length ) + { + long startTimeStamp = determineStartInterval(outputFiles[startFileIndex].getName()); + + long tempStartInterval = startTimeStamp / (maxLatencyWindow*1000000); + + if ( calculate ) + { + if(startInterval > tempStartInterval) { + startInterval = tempStartInterval; + } + } + else + { + startInterval = tempStartInterval; + calculate = true; + } + } + + return calculate ? maxLatencyWindow * startInterval : -1; + } + + return 0; + } + + + + public static long retrieveStartTimeForCalculating(String latencyFolderName, long maxLatencyWindow) + { + File latencyFolder = new File(latencyFolderName); + + if ( latencyFolder.exists() ) + { + File[] files = latencyFolder.listFiles(); + + Arrays.sort(files, new FileComparator(CompType.TIME, "", false)); + + return files.length == 0 || files.length == 1 ? 0 : maxLatencyWindow * (files.length - 2); + + } else { + throw new EPSCommonException("Could not find [" + latencyFolderName + "] folder with latency files"); + } + } + + + public static void generateInputFile(String folderName, long startTimeInSec, long finishTimeInSec, String generatingFile) throws IOException + { + File folder = new File(folderName); + + if ( folder.exists() ) + { + File[] files = folder.listFiles(); + + Arrays.sort(files, new FileSpecialComparator(true, false)); + + if(files.length == 0) { + return; + } + + int index = files.length - 1; + for ( ; index >= 0; --index ) + { + long startInterval = determineStartInterval(files[index].getName()); + + if(startInterval < startTimeInSec * 1000000) { + break; + } + } + + if(index < 0) { + index = 0; + } + + + + BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile)); + + for ( int i = index; i < files.length; ++i ) + { + if ( isDebugged ) + { + logger.debug(files[i].getName()); + } + + CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); + reader.setSafetySwitch(false); + + reader.readRecord(); + + if ( i == index ) + { + writer.write(reader.getRawRecord()); + writer.newLine(); + } + + while ( reader.readRecord() ) + { + long timestamp = Long.parseLong(reader.getValues()[0]); + + if(timestamp >= startTimeInSec * 1000000 && (timestamp < finishTimeInSec * 1000000 || finishTimeInSec == Long.MAX_VALUE)) { + writer.write(reader.getRawRecord()); + writer.newLine(); + } else if(timestamp >= startTimeInSec * 1000000) { + break; + } + } + + reader.close(); + } + + writer.close(); + + } else { + throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); + } + } + + + public static void generateMDLatFile(String folderName, long startTimeInSec, long finishTimeInSec, String generatingFile, SimpleDateFormat format, String analyzedField, long startSec) throws IOException + { + File folder = new File(folderName); + + if ( folder.exists() ) + { + File[] files = folder.listFiles(); + + Arrays.sort(files, new FileSpecialComparator(true, false)); + + if(files.length == 0) { + return; + } + + int index = files.length - 1; + for ( ; index >= 0; --index ) + { + long startInterval = determineStartInterval(files[index].getName()); + + if(startInterval < startTimeInSec * 1000000) { + break; + } + } + + if(index < 0) { + index = 0; + } + + + try(BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile))) { + int fieldIndex = -1; + + for(int i = index; i < files.length; ++i) { + if(isDebugged) { + logger.debug(files[i].getName()); + } + + CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); + reader.setSafetySwitch(false); + + reader.readRecord(); + + if(i == index) { + + String[] headers = reader.getValues(); + + for(int j = 0; j < headers.length; ++j) { + if(headers[j].equals(analyzedField)) { + fieldIndex = j; + break; + } + } + + writer.write("Timestamp,Latency"); + + for(int j = 3; j < headers.length; ++j) { + writer.write("," + headers[j]); + } + + writer.newLine(); + + if(fieldIndex == -1) { + throw new IllegalArgumentException("Could not find fieldName = [" + analyzedField + "] in inputFile = [" + files[i].getName() + "]"); + } + } + + while(reader.readRecord()) { + String[] values = reader.getValues(); + + long timestamp = Long.parseLong(values[0]); + + if(timestamp >= startTimeInSec * 1000000 && (timestamp < finishTimeInSec * 1000000 || finishTimeInSec == Long.MAX_VALUE)) { + try { + String sendingTime = values[fieldIndex]; + + long sendingTimestamp = format.parse(sendingTime + " +0000").getTime(); + + sendingTimestamp = (sendingTimestamp - startSec * 1000) * 1000; + + writer.write(values[0] + ',' + (timestamp - sendingTimestamp)); + + for(int j = 3; j < values.length; ++j) { + writer.write("," + values[j]); + } + + writer.newLine(); + } catch(ParseException e) { + } + } else if(timestamp >= startTimeInSec * 1000000) { + break; + } + } + + reader.close(); + } + } + } else { + throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); + } + } + + + + + + + + public static void generateFakeInputFile(String folderName, long startTimeInSec, long finishTimeInSec, String generatingFile) throws IOException + { + File folder = new File(folderName); + + if ( folder.exists() ) + { + File[] files = folder.listFiles(); + + Arrays.sort(files, new FileSpecialComparator(true, false)); + + if(files.length == 0) { + return; + } + + int index = files.length - 1; + for ( ; index >= 0; --index ) + { + long startInterval = determineStartInterval(files[index].getName()); + + if(startInterval < startTimeInSec * 1000000) { + break; + } + } + + if(index < 0) { + index = 0; + } + + BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile)); + + + boolean firstRecordWritten = false; + + for ( int i = index; i < files.length; ++i ) + { + if ( isDebugged ) + { + logger.debug(files[i].getName()); + } + + CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); + reader.setSafetySwitch(false); + + reader.readRecord(); + + if ( i == index ) + { + writer.write(reader.getRawRecord()); + writer.newLine(); + } + + + if ( !firstRecordWritten || i == files.length - 1) + { + String lastRecord = ""; + + while ( reader.readRecord() ) + { + long timestamp = Long.parseLong(reader.getValues()[0]); + + lastRecord = reader.getRawRecord(); + + if ( !firstRecordWritten ) + { + if(timestamp >= startTimeInSec * 1000000 && (timestamp < finishTimeInSec * 1000000 || finishTimeInSec == Long.MAX_VALUE)) { + writer.write(reader.getRawRecord()); + writer.newLine(); + firstRecordWritten = true; + } else if(timestamp >= startTimeInSec * 1000000) { + break; + } + } + } + + writer.write(lastRecord); + } + + reader.close(); + } + + writer.close(); + + } else { + throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); + } + } + + + + + + + + + + + + + + + + + + + + public static long determineFinishInterval(String fileName) + { + long finishTime = Long.parseLong(getFileNameWithoutExt(fileName).substring(getFileNameWithoutExt(fileName).lastIndexOf("_") + 1)); + + return finishTime; + } + + + public static long determineStartInterval(String fileName) + { + int lastIndex = fileName.lastIndexOf("_"); + + if(lastIndex == -1) { + throw new EPSCommonException("Incorrect file name = [" + fileName + "]"); + } + + int prevIndex = fileName.lastIndexOf("_", lastIndex - 1); + + long startTime = Long.parseLong(fileName.substring(prevIndex + 1, lastIndex)); + + return startTime; + } + + + public static void mergeFiles(String folderName, String generatingFile) throws IOException + { + File folder = new File(folderName); + + if ( folder.exists() ) + { + File[] files = folder.listFiles(); + + Arrays.sort(files, new FileComparator(CompType.TIME, "", false)); + + if(files.length == 0) { + return; + } + + BufferedWriter writer = new BufferedWriter(new FileWriter(generatingFile)); + + for ( int i = 0; i < files.length; ++i ) + { + CsvReader reader = new CsvReader(folderName + File.separator + files[i].getName()); + reader.setSafetySwitch(false); + + reader.readRecord(); + + if ( i == 0 ) + { + writer.write(reader.getRawRecord()); + writer.newLine(); + } + + while ( reader.readRecord() ) + { + writer.write(reader.getRawRecord()); + writer.newLine(); + } + + reader.close(); + } + + writer.close(); + + } else { + throw new EPSCommonException("Could not find [" + folderName + "] folder with files"); + } + } + + + public static boolean lockFile(File file) throws IOException + { + String lockFileName = "." + file.getName(); + + File lockFile = new File(file.getParentFile(), lockFileName); + + return lockFile.createNewFile(); + } + + + public static boolean unlockFile(File file) throws IOException + { + String lockFileName = "." + file.getName(); + + File lockFile = new File(file.getParentFile(), lockFileName); + + return lockFile.delete(); + } + + + public static void deleteFileWithoutException(String destFile) + { + try + { + FileUtils.forceDelete(new File(destFile)); + } + catch ( Exception e ) + { + + } + } + + + public static void deleteFileWithoutException(File destFile) + { + try + { + FileUtils.forceDelete(destFile); + } + catch ( Exception e ) + { + + } + } + + public static String getTagColorClass(String name) { + return TAG_COLOR_CLASSES[Math.abs(Objects.hashCode(name)) % TAG_COLOR_CLASSES.length]; + } +} diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparatorSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparatorSettings.java index 5e331bcf..2fbf00b6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparatorSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparatorSettings.java @@ -29,10 +29,10 @@ public class ComparatorSettings { @Deprecated private String alternateValue; private MetaContainer metaContainer = new MetaContainer(); - private boolean checkGroupsOrder = false; + private boolean checkGroupsOrder; @Deprecated private Map negativeMap = Collections.emptyMap(); - private boolean reorderGroups = false; + private boolean reorderGroups; private IDictionaryStructure dictionaryStructure; private Set uncheckedFields = Collections.emptySet(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonResult.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonResult.java index 75a0c379..7618952b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonResult.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonResult.java @@ -35,7 +35,7 @@ public class ComparisonResult implements Iterable { private StatusType status; private ExpressionResult expressionResult; private Throwable exception; - private Map results = new LinkedHashMap<>(); + private final Map results = new LinkedHashMap<>(); private Set allKnownBugs = Collections.emptySet(); private Set reproducedBugs = Collections.emptySet(); private ComparisonResult parent; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonUtil.java index dcf4d519..e8cff603 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/ComparisonUtil.java @@ -15,16 +15,16 @@ ******************************************************************************/ package com.exactpro.sf.comparison; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.temporal.TemporalAccessor; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.ObjectUtils; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.temporal.TemporalAccessor; import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; import com.exactpro.sf.common.messages.IMessage; @@ -47,7 +47,7 @@ public static int getResultCount(ComparisonResult result, StatusType status) { int count = 0; - if (status.equals(result.getStatus())) { + if(status == result.getStatus()) { count++; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Convention.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Convention.java index 2eb335ef..38cacd15 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Convention.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Convention.java @@ -16,11 +16,10 @@ package com.exactpro.sf.comparison; import java.math.BigDecimal; -import java.util.List; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.List; import com.exactpro.sf.aml.scriptutil.StaticUtil; import com.exactpro.sf.common.messages.IMessage; @@ -86,7 +85,7 @@ public static final String getReplacementForPresent(Class type) return "\""+CONV_PRESENT_STRING+"\""; } if (type.equals(Byte.class) || type.equals(byte.class)) { - return "(byte)" + String.valueOf(CONV_PRESENT_BYTE); + return "(byte)" + CONV_PRESENT_BYTE; } if (type.equals(Integer.class) || type.equals(int.class)) { return String.valueOf(CONV_PRESENT_INTEGER); @@ -98,7 +97,7 @@ public static final String getReplacementForPresent(Class type) return String.valueOf(CONV_PRESENT_DOUBLE); } if (type.equals(Float.class) || type.equals(float.class)) { - return String.valueOf(CONV_PRESENT_FLOAT)+"f"; + return CONV_PRESENT_FLOAT +"f"; } if (type.equals(Character.class) || type.equals(char.class)) { return "'\\u0000'"; @@ -127,7 +126,7 @@ public static final String getReplacementForMissed(Class type) return "\""+CONV_MISSED_STRING+"\""; } if (type.equals(Byte.class) || type.equals(byte.class)) { - return "(byte)" + String.valueOf(CONV_MISSED_BYTE); + return "(byte)" + CONV_MISSED_BYTE; } if (type.equals(Integer.class) || type.equals(int.class)) { return String.valueOf(CONV_MISSED_INTEGER); @@ -139,7 +138,7 @@ public static final String getReplacementForMissed(Class type) return String.valueOf(CONV_MISSED_DOUBLE); } if (type.equals(Float.class) || type.equals(float.class)) { - return String.valueOf(CONV_MISSED_FLOAT)+"f"; + return CONV_MISSED_FLOAT +"f"; } if (type.equals(Character.class) || type.equals(char.class)) { return "'\\u0001'"; @@ -205,13 +204,13 @@ public static final boolean hasConventionForType(Class type) public static final boolean isConventionedValuePresent(Object value) { - Class type = value.getClass(); + Class type = value.getClass(); if (type.equals(String.class)) { return value.equals(CONV_PRESENT_STRING) - || value.equals(Convention.CONV_PRESENT_DATE_FIX_STRING) - || value.equals(Convention.CONV_PRESENT_DATEONLY_FIX_STRING) - || value.equals(Convention.CONV_PRESENT_TIMEONLY_FIX_STRING) - || value.equals(Convention.CONV_PRESENT_CHAR_FIX_STRING); + || value.equals(CONV_PRESENT_DATE_FIX_STRING) + || value.equals(CONV_PRESENT_DATEONLY_FIX_STRING) + || value.equals(CONV_PRESENT_TIMEONLY_FIX_STRING) + || value.equals(CONV_PRESENT_CHAR_FIX_STRING); } else if (type.equals(Integer.class)) { return value.equals(CONV_PRESENT_INTEGER); } else if (type.equals(Long.class)) { @@ -235,20 +234,20 @@ public static final boolean isConventionedValuePresent(Object value) } else if (type.equals(Byte.class)){ return value.equals(CONV_PRESENT_BYTE); } else if (value instanceof Enum) { - return (value.toString().equals(CONV_PRESENT_ENUM)); + return value.toString().equals(CONV_PRESENT_ENUM); } return false; } public static final boolean isConventionedValueMissed(Object value) { - Class type = value.getClass(); + Class type = value.getClass(); if (type.equals(String.class)) { return value.equals(CONV_MISSED_STRING) - || value.equals(Convention.CONV_MISSED_DATE_FIX_STRING) - || value.equals(Convention.CONV_MISSED_DATEONLY_FIX_STRING) - || value.equals(Convention.CONV_MISSED_TIMEONLY_FIX_STRING) - || value.equals(Convention.CONV_MISSED_CHAR_FIX_STRING); + || value.equals(CONV_MISSED_DATE_FIX_STRING) + || value.equals(CONV_MISSED_DATEONLY_FIX_STRING) + || value.equals(CONV_MISSED_TIMEONLY_FIX_STRING) + || value.equals(CONV_MISSED_CHAR_FIX_STRING); } else if (type.equals(Integer.class)) { return value.equals(CONV_MISSED_INTEGER); } else if (type.equals(Long.class)) { @@ -270,7 +269,7 @@ public static final boolean isConventionedValueMissed(Object value) } else if (type.equals(Byte.class)){ return value.equals(CONV_MISSED_BYTE); } else if (value instanceof Enum) { - return (value.toString().equals(CONV_MISSED_ENUM)); + return value.toString().equals(CONV_MISSED_ENUM); } return false; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Formatter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Formatter.java index eddf48c5..700f5aca 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Formatter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/Formatter.java @@ -17,7 +17,6 @@ import java.math.BigDecimal; import java.text.DecimalFormat; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; @@ -39,7 +38,7 @@ private Formatter() { // hide constructor } - private final static ThreadLocal df = new ThreadLocal() { + private static final ThreadLocal df = new ThreadLocal() { @Override protected DecimalFormat initialValue() { return new DecimalFormat("#.####################"); @@ -55,69 +54,106 @@ public static String format(Object o, boolean isExpected) { if (o instanceof String) { // DG: dirty hack for FIX protocol for DateTime fields comparison - if (o.equals(Convention.CONV_PRESENT_DATE_FIX_STRING)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_DATE_FIX_STRING)) return Convention.CONV_MISSED_STRING; - if (o.equals(Convention.CONV_PRESENT_CHAR_FIX_STRING)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_CHAR_FIX_STRING)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_DATE_FIX_STRING)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_DATE_FIX_STRING)) { + return Convention.CONV_MISSED_STRING; + } + if(o.equals(Convention.CONV_PRESENT_CHAR_FIX_STRING)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_CHAR_FIX_STRING)) { + return Convention.CONV_MISSED_STRING; + } String s = (String)o; - if (s.startsWith(" ") - || s.endsWith(" ") - || s.startsWith("\t") - || s.endsWith("\t")) { - return "["+s+"]"; - } - return s; - } + return s.startsWith(" ") + || s.endsWith(" ") + || s.startsWith("\t") + || s.endsWith("\t") ? "[" + s + "]" : s; + } if (o instanceof Integer) { - if (o.equals(Convention.CONV_PRESENT_INTEGER)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_INTEGER)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_INTEGER)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_INTEGER)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof Long) { - if (o.equals(Convention.CONV_PRESENT_LONG)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LONG)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LONG)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LONG)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof Double) { - if (o.equals(Convention.CONV_PRESENT_DOUBLE)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_DOUBLE)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_DOUBLE)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_DOUBLE)) { + return Convention.CONV_MISSED_STRING; + } Double d = (Double)o; - return (d.equals(Double.NaN)) ? "NaN" : df.get().format(d); + return d.equals(Double.NaN) ? "NaN" : df.get().format(d); } if (o instanceof Float) { - if (o.equals(Convention.CONV_PRESENT_FLOAT)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_FLOAT)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_FLOAT)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_FLOAT)) { + return Convention.CONV_MISSED_STRING; + } Float d = (Float)o; - return (d.equals(Float.NaN)) ? "NaN" : df.get().format(d); + return d.equals(Float.NaN) ? "NaN" : df.get().format(d); } if (o instanceof LocalDateTime) { - if (o.equals(Convention.CONV_PRESENT_LOCAL_DATE_TIME)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LOCAL_DATE_TIME)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LOCAL_DATE_TIME)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LOCAL_DATE_TIME)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof LocalDate) { - if (o.equals(Convention.CONV_PRESENT_LOCAL_DATE)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LOCAL_DATE)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LOCAL_DATE)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LOCAL_DATE)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof LocalTime) { - if (o.equals(Convention.CONV_PRESENT_LOCAL_TIME)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LOCAL_TIME)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LOCAL_TIME)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LOCAL_TIME)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof Character) { - if (o.equals(Convention.CONV_PRESENT_CHAR)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_CHAR)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_CHAR)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_CHAR)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } } if (o instanceof Double) { Double d = (Double)o; - return (d.equals(Double.NaN)) ? "NaN" : df.get().format(d); + return d.equals(Double.NaN) ? "NaN" : df.get().format(d); } if (o instanceof Float) { Float f = (Float)o; - return (f.equals(Float.NaN)) ? "NaN" : df.get().format(f); + return f.equals(Float.NaN) ? "NaN" : df.get().format(f); } if (o instanceof BigDecimal) { BigDecimal bd = (BigDecimal)o; @@ -154,10 +190,18 @@ public static String formatForHtml(Object o, boolean isExpected) { } if (o instanceof String) { // DG: dirty hack for FIX protocol for DateTime fields comparison - if (o.equals(Convention.CONV_PRESENT_DATE_FIX_STRING)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_DATE_FIX_STRING)) return Convention.CONV_MISSED_STRING; - if (o.equals(Convention.CONV_PRESENT_CHAR_FIX_STRING)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_CHAR_FIX_STRING)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_DATE_FIX_STRING)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_DATE_FIX_STRING)) { + return Convention.CONV_MISSED_STRING; + } + if(o.equals(Convention.CONV_PRESENT_CHAR_FIX_STRING)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_CHAR_FIX_STRING)) { + return Convention.CONV_MISSED_STRING; + } String s = (String)o; if (s.startsWith(" ") || s.endsWith(" ") @@ -174,48 +218,84 @@ public static String formatForHtml(Object o, boolean isExpected) { return s.replaceAll(XML_10_PATTERN, Convention.CONV_MISSED_STRING); } if (o instanceof Integer) { - if (o.equals(Convention.CONV_PRESENT_INTEGER)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_INTEGER)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_INTEGER)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_INTEGER)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof Long) { - if (o.equals(Convention.CONV_PRESENT_LONG)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LONG)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LONG)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LONG)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof Double) { - if (o.equals(Convention.CONV_PRESENT_DOUBLE)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_DOUBLE)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_DOUBLE)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_DOUBLE)) { + return Convention.CONV_MISSED_STRING; + } return df.get().format(o); } if (o instanceof Float) { - if (o.equals(Convention.CONV_PRESENT_FLOAT)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_FLOAT)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_FLOAT)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_FLOAT)) { + return Convention.CONV_MISSED_STRING; + } return df.get().format(o); } if (o instanceof Short) { - if (o.equals(Convention.CONV_PRESENT_SHORT)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_SHORT)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_SHORT)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_SHORT)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof LocalDateTime) { - if (o.equals(Convention.CONV_PRESENT_LOCAL_DATE_TIME)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LOCAL_DATE_TIME)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LOCAL_DATE_TIME)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LOCAL_DATE_TIME)) { + return Convention.CONV_MISSED_STRING; + } return ((LocalDateTime) o).format(LocalDateTimeConst.DATE_TIME_FORMATTER); } if (o instanceof LocalDate) { - if (o.equals(Convention.CONV_PRESENT_LOCAL_DATE)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LOCAL_DATE)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LOCAL_DATE)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LOCAL_DATE)) { + return Convention.CONV_MISSED_STRING; + } return ((LocalDate) o).format(LocalDateTimeConst.DATE_FORMATTER); } if (o instanceof LocalTime) { - if (o.equals(Convention.CONV_PRESENT_LOCAL_TIME)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_LOCAL_TIME)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_LOCAL_TIME)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_LOCAL_TIME)) { + return Convention.CONV_MISSED_STRING; + } return ((LocalTime) o).format(LocalDateTimeConst.TIME_FORMATTER); } if (o instanceof Character) { - if (o.equals(Convention.CONV_PRESENT_CHAR)) return Convention.CONV_PRESENT_STRING; - if (o.equals(Convention.CONV_MISSED_CHAR)) return Convention.CONV_MISSED_STRING; + if(o.equals(Convention.CONV_PRESENT_CHAR)) { + return Convention.CONV_PRESENT_STRING; + } + if(o.equals(Convention.CONV_MISSED_CHAR)) { + return Convention.CONV_MISSED_STRING; + } return o.toString(); } if (o instanceof BigDecimal) { @@ -241,21 +321,14 @@ public static String formatForHtml(Object o, boolean isExpected) { return df.get().format(o); } - String s; - if(o instanceof BigDecimal) { - s = ((BigDecimal) o).toPlainString(); - } else - s = o.toString(); + String s = o instanceof BigDecimal ? ((BigDecimal)o).toPlainString() : o.toString(); - if (s.startsWith(" ") - || s.endsWith(" ") - || s.startsWith("\t") - || s.endsWith("\t")) { - return "["+s+"]"; - } + return s.startsWith(" ") + || s.endsWith(" ") + || s.startsWith("\t") + || s.endsWith("\t") ? "[" + s + "]" : s; - return s; - } + } public static String formatExpected(ComparisonResult result) { Object expected = result.getExpected(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/IPostValidation.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/IPostValidation.java index 083df6ba..6c664305 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/IPostValidation.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/IPostValidation.java @@ -19,6 +19,6 @@ public interface IPostValidation { - public void doValidate(IMessage message, IMessage filter, ComparatorSettings settings, ComparisonResult result); + void doValidate(IMessage message, IMessage filter, ComparatorSettings settings, ComparisonResult result); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/MessageComparator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/MessageComparator.java index 3f037438..9391c488 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/MessageComparator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/MessageComparator.java @@ -467,21 +467,12 @@ private static ComparisonResult addToResult(Object object, ComparisonResult resu } private static List getMetaContainers(List metaContainers, int index) { - if(index < metaContainers.size()) { - return Collections.singletonList(metaContainers.get(index)); - } - - return metaContainers; + return index < metaContainers.size() ? Collections.singletonList(metaContainers.get(index)) : metaContainers; } private static List getMetaContainers(List metaContainers, String name) { List subMetaContainers = metaContainers.get(0).get(name); - - if(subMetaContainers != null) { - return subMetaContainers; - } - - return metaContainers; + return subMetaContainers != null ? subMetaContainers : metaContainers; } private static boolean checkTypes(Object actual, Object expected, Class clazz, IFieldStructure structure) throws Exception { @@ -532,10 +523,7 @@ private static boolean isCollection(IFieldStructure structure) { } private static List getExpectedList(Object expected, List embeddedListFilter) { - if (expected instanceof IFilter && embeddedListFilter != null) { - return embeddedListFilter; - } - return (List)expected; + return expected instanceof IFilter && embeddedListFilter != null ? embeddedListFilter : (List)expected; } private static Object getValue(Object wrapper) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/ConvertingComparator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/ConvertingComparator.java index f638d07f..fd88c6fa 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/ConvertingComparator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/ConvertingComparator.java @@ -16,16 +16,15 @@ package com.exactpro.sf.comparison.conversion; import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; public class ConvertingComparator implements Comparator { - private final static List> PRIORITIES = new ArrayList<>(); + private static final List> PRIORITIES = new ArrayList<>(); static { PRIORITIES.add(String.class); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/MultiConverter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/MultiConverter.java index ed3beab8..583f6907 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/MultiConverter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/MultiConverter.java @@ -16,15 +16,14 @@ package com.exactpro.sf.comparison.conversion; import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - import com.exactpro.sf.comparison.conversion.impl.BigDecimalConverter; import com.exactpro.sf.comparison.conversion.impl.BooleanConverter; import com.exactpro.sf.comparison.conversion.impl.ByteConverter; @@ -41,9 +40,9 @@ public class MultiConverter { - private final static Map, IConverter> CONVERTERS = initConverters(); + private static final Map, IConverter> CONVERTERS = initConverters(); - public final static Set> SUPPORTED_TYPES = Collections.unmodifiableSet(CONVERTERS.keySet()); + public static final Set> SUPPORTED_TYPES = Collections.unmodifiableSet(CONVERTERS.keySet()); @SuppressWarnings("unchecked") public static T convert(Object value, Class clazz) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/impl/AbstractNumberConverter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/impl/AbstractNumberConverter.java index a70998bd..4568d4aa 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/impl/AbstractNumberConverter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/conversion/impl/AbstractNumberConverter.java @@ -70,11 +70,7 @@ public T convert(String value) { @SuppressWarnings("unchecked") protected T getValue(Number value) { - if(value == null || value.getClass() == getTargetClass()) { - return (T)value; - } - - return checkForDataLoss(value, convertValue(value)); + return value == null || value.getClass() == getTargetClass() ? (T)value : checkForDataLoss(value, convertValue(value)); } protected T getValue(String value) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Column.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Column.java index 622b9c7d..6c1aee90 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Column.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Column.java @@ -17,7 +17,7 @@ public class Column { - private String cell; + private final String cell; private int offset; public Column(String s) { @@ -46,13 +46,13 @@ public String toString() { } if (cell != null) { - sb.append(this.cell); + sb.append(cell); } return sb.toString(); } public String getValue() { - return this.cell; + return cell; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Row.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Row.java index 7f67e8cc..6f8d086b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Row.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/comparison/table/Row.java @@ -19,7 +19,7 @@ public class Row { - private Column[] columns; + private final Column[] columns; private int offset; @@ -48,7 +48,7 @@ public boolean isDelimiter() for (Column c : columns) { length += c.getLength(); } - return length == this.offset; + return length == offset; } public String toString(int[] length) @@ -71,7 +71,7 @@ public String toString(int[] length) { Column c = columns[ic]; int len = length[ic]; - sb.append(c.toString()); + sb.append(c); for (int i=c.getLength(); i rows; - private int offset = 0; + private final List rows; + private int offset; private String title; public Table() @@ -70,7 +70,7 @@ public void setOffset(int offset) { } public int getOffset() { - return this.offset; + return offset; } public int getMaxColumnLength(int iColumn) @@ -85,7 +85,7 @@ public int getMaxColumnLength(int iColumn) public void add(Table that) { - if (that.rows.size() != 0) { + if(!that.rows.isEmpty()) { // rows.add(new Row()); rows.addAll(that.rows); } @@ -93,7 +93,7 @@ public void add(Table that) public void add(Row row) { - this.rows.add(row); + rows.add(row); } @Override @@ -101,35 +101,35 @@ public String toString() { StringBuilder sb = new StringBuilder(); - int[] colWidth = new int[Table.COLUMN_COUNT]; + int[] colWidth = new int[COLUMN_COUNT]; int tableWidth = 0; for (int i=0; i getRows() { - return this.rows; + return rows; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DataManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DataManager.java index 0b35db84..5b7b47f6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DataManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DataManager.java @@ -76,14 +76,14 @@ public boolean exists(SailfishURI uri) { */ @Override public InputStream getDataInputStream(SailfishURI uri) { - String resource = SailfishURIUtils.getMatchingValue(uri, this.location, SailfishURIRule.REQUIRE_RESOURCE); + String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE); if (resource == null) { throw new RuntimeException("No data found for URI: " + uri); } try { - return new FileInputStream(this.workspaceDispatcher.getFile(FolderType.ROOT, resource)); + return new FileInputStream(workspaceDispatcher.getFile(FolderType.ROOT, resource)); } catch (FileNotFoundException e) { throw new ScriptRunException("Could not create data input stream [" + resource + "]", e); } @@ -115,20 +115,20 @@ public InputStream getDataInputStream(String pluginAlias, String resourcePath) { */ @Override public OutputStream getDataOutputStream(SailfishURI uri, boolean append) { - String resource = SailfishURIUtils.getMatchingValue(uri, this.location, SailfishURIRule.REQUIRE_RESOURCE); + String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE); if (resource == null) { throw new RuntimeException("No data found for URI: " + uri); } try { - return new FileOutputStream(this.workspaceDispatcher.getOrCreateFile(FolderType.ROOT, resource), append); + return new FileOutputStream(workspaceDispatcher.getOrCreateFile(FolderType.ROOT, resource), append); } catch (IOException e) { throw new ScriptRunException("Could not create data output stream [" + resource + "]", e); } } - private void loadDataLocations(final InputStream xml, final String pathToDataFolder, IVersion version) { + private void loadDataLocations(InputStream xml, String pathToDataFolder, IVersion version) { DataListing dataListing = null; try { @@ -189,7 +189,7 @@ public Path getRelativePathToPlugin(String pluginAlias) { @Override public String getExtension(SailfishURI uri) { - String resource = SailfishURIUtils.getMatchingValue(uri, this.location, SailfishURIRule.REQUIRE_RESOURCE); + String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE); if(resource == null) { throw new RuntimeException("No data found for URI: " + uri); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DefaultAdapterManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DefaultAdapterManager.java index a3db3ece..02c65a05 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DefaultAdapterManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DefaultAdapterManager.java @@ -183,15 +183,17 @@ private DefaultAdapterManager() { */ private void addFactoriesFor(Class type, Map, IAdapterFactory> table) { List factoryList = getFactories().get(type); - if (factoryList == null) - return; + if(factoryList == null) { + return; + } for (int i = 0, imax = factoryList.size(); i < imax; i++) { IAdapterFactory factory = factoryList.get(i); Class[] adapters = factory.getAdapterList(); for (int j = 0; j < adapters.length; j++) { - if (table.get(adapters[j]) == null) - table.put(adapters[j], factory); + if(table.get(adapters[j]) == null) { + table.put(adapters[j], factory); + } } } } @@ -214,15 +216,17 @@ public String[] computeAdapterTypes(Class adaptable) { private Map, IAdapterFactory> getFactories(Class adaptable) { //cache reference to lookup to protect against concurrent flush Map, Map, IAdapterFactory>> lookup = adapterLookup; - if (lookup == null) - adapterLookup = lookup = Collections.synchronizedMap(new HashMap, Map, IAdapterFactory>>(30)); + if(lookup == null) { + adapterLookup = lookup = Collections.synchronizedMap(new HashMap, Map, IAdapterFactory>>(30)); + } Map, IAdapterFactory> table = lookup.get(adaptable); if (table == null) { // calculate adapters for the class table = new HashMap<>(4); Class[] classes = computeClassOrder(adaptable); - for (int i = 0; i < classes.length; i++) - addFactoriesFor(classes[i], table); + for(int i = 0; i < classes.length; i++) { + addFactoriesFor(classes[i], table); + } // cache the table lookup.put(adaptable, table); } @@ -238,10 +242,11 @@ public Class[] computeClassOrder(Class adaptable) { Class[] classes = null; //cache reference to lookup to protect against concurrent flush Map, Class[]> lookup = classSearchOrderLookup; - if (lookup == null) - classSearchOrderLookup = lookup = Collections.synchronizedMap(new HashMap, Class[]>()); - else - classes = lookup.get(adaptable); + if(lookup == null) { + classSearchOrderLookup = lookup = Collections.synchronizedMap(new HashMap, Class[]>()); + } else { + classes = lookup.get(adaptable); + } // compute class order only if it hasn't been cached before if (classes == null) { classes = doComputeClassOrder(adaptable); @@ -265,8 +270,9 @@ private Class[] doComputeClassOrder(Class adaptable) { } //now traverse interface hierarchy for each class Class[] classHierarchy = classes.toArray(new Class[classes.size()]); - for (int i = 0; i < classHierarchy.length; i++) - computeInterfaceOrder(classHierarchy[i].getInterfaces(), classes, seen); + for(int i = 0; i < classHierarchy.length; i++) { + computeInterfaceOrder(classHierarchy[i].getInterfaces(), classes, seen); + } return classes.toArray(new Class[classes.size()]); } @@ -280,8 +286,9 @@ private void computeInterfaceOrder(Class[] interfaces, Collection> c newInterfaces.add(interfac); } } - for (Iterator> it = newInterfaces.iterator(); it.hasNext();) - computeInterfaceOrder(it.next().getInterfaces(), classes, seen); + for(Iterator> it = newInterfaces.iterator(); it.hasNext(); ) { + computeInterfaceOrder(it.next().getInterfaces(), classes, seen); + } } /** @@ -302,12 +309,8 @@ public synchronized void flushLookup() { public Object getAdapter(Class clazz, Class adapterType) { IAdapterFactory factory = getFactories(clazz).get(adapterType); - Object result = null; - if (factory != null) - result = factory.getAdapter(null, adapterType); - return result; - - } + return factory != null ? factory.getAdapter(null, adapterType) : null; + } /* (non-Javadoc) * @see org.eclipse.core.runtime.IAdapterManager#getAdapter(java.lang.Object, java.lang.Class) @@ -316,12 +319,11 @@ public Object getAdapter(Class clazz, Class adapterType) public Object getAdapter(Object adaptable, Class adapterType) { IAdapterFactory factory = getFactories(adaptable.getClass()).get(adapterType); Object result = null; - if (factory != null) - result = factory.getAdapter(adaptable, adapterType); - if (result == null && adapterType.isInstance(adaptable)) - return adaptable; - return result; - } + if(factory != null) { + result = factory.getAdapter(adaptable, adapterType); + } + return result == null && adapterType.isInstance(adaptable) ? adaptable : result; + } @Override public boolean hasAdapter(Object adaptable, Class adapterType) { @@ -334,11 +336,8 @@ public boolean hasAdapter(Object adaptable, Class adapterType) { @Override public int queryAdapter(Object adaptable, Class adapterType) { IAdapterFactory factory = getFactories(adaptable.getClass()).get(adapterType); - if (factory == null) - return NONE; - - return LOADED; - } + return factory == null ? NONE : LOADED; + } /* * @see IAdapterManager#registerAdapters @@ -366,8 +365,9 @@ public void registerFactory(IAdapterFactory factory, Class adaptable) { */ @Override public synchronized void unregisterAdapters(IAdapterFactory factory) { - for (Iterator> it = factories.values().iterator(); it.hasNext();) - it.next().remove(factory); + for(Iterator> it = factories.values().iterator(); it.hasNext(); ) { + it.next().remove(factory); + } flushLookup(); } @@ -377,8 +377,9 @@ public synchronized void unregisterAdapters(IAdapterFactory factory) { @Override public synchronized void unregisterAdapters(IAdapterFactory factory, Class adaptable) { List factoryList = factories.get(adaptable); - if (factoryList == null) - return; + if(factoryList == null) { + return; + } factoryList.remove(factory); flushLookup(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DictionaryManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DictionaryManager.java index c592ae67..ac5d7c94 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DictionaryManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DictionaryManager.java @@ -95,13 +95,13 @@ public class DictionaryManager implements IDictionaryManager, ILoadableManager { // plugin alias -> list of dictionary URI's private final SetMultimap pluginDictTitles = HashMultimap.create(); - private long dictLoadedCounter = 0; + private long dictLoadedCounter; - private Map dictionaryIds = new ConcurrentHashMap<>(); + private final Map dictionaryIds = new ConcurrentHashMap<>(); private final List eventListeners; - public DictionaryManager(final IWorkspaceDispatcher workspaceDispatcher, UtilityManager utilityManager) { + public DictionaryManager(IWorkspaceDispatcher workspaceDispatcher, UtilityManager utilityManager) { this.workspaceDispatcher = Objects.requireNonNull(workspaceDispatcher, "workspaceDispatcher cannot be null"); this.utilityManager = Objects.requireNonNull(utilityManager, "utilityManager cannot be null"); this.eventListeners = new CopyOnWriteArrayList<>(); @@ -114,16 +114,16 @@ public synchronized Set getDictionaryURIs() { @Override public synchronized Set getDictionaryURIs(String pluginAlias) { - if (pluginAlias == null || !this.pluginDictTitles.containsKey(pluginAlias)) { + if(pluginAlias == null || !pluginDictTitles.containsKey(pluginAlias)) { logger.error("Dictionary titles for plugin alias '{}' not found", pluginAlias); return null; } - return this.pluginDictTitles.get(pluginAlias); + return pluginDictTitles.get(pluginAlias); } @Override public synchronized List getCachedDictURIs() { - return new ArrayList<>(this.dicts.keySet()); + return new ArrayList<>(dicts.keySet()); } @Override @@ -134,10 +134,10 @@ public synchronized Map getDictionaryLocations() { @Override public void load(ILoadableManagerContext context) { try { - final ClassLoader loader = context.getClassLoaders()[0]; - final InputStream stream = context.getResourceStream(); - final String dictionaryFolderPath = context.getResourceFolder(); - final IVersion version = context.getVersion(); + ClassLoader loader = context.getClassLoaders()[0]; + InputStream stream = context.getResourceStream(); + String dictionaryFolderPath = context.getResourceFolder(); + IVersion version = context.getVersion(); JAXBContext jc = JAXBContext.newInstance(Dictionaries.class); Unmarshaller u = jc.createUnmarshaller(); @@ -154,12 +154,12 @@ public void load(ILoadableManagerContext context) { SailfishURI dictionaryURI = new SailfishURI(version.getAlias(), null, SailfishURIUtils.sanitize(dict.getTitle())); DictionarySettings settings = dictSettings.get(dictionaryURI); - this.pluginDictTitles.put(dictionaryURI.getPluginAlias(), dictionaryURI); + pluginDictTitles.put(dictionaryURI.getPluginAlias(), dictionaryURI); if (settings == null) { settings = new DictionarySettings(); settings.setURI(dictionaryURI); - this.dictSettings.put(dictionaryURI, settings); + dictSettings.put(dictionaryURI, settings); } for (String className : dict.getUtilityClassName()){ @@ -180,7 +180,7 @@ public void load(ILoadableManagerContext context) { } } - String currentResource = this.location.get(dictionaryURI); + String currentResource = location.get(dictionaryURI); String resource = dict.getResource(); if (resource == null) { logger.warn("resource (xml dictionary) not specified for dictionary {}", dictionaryURI); @@ -189,7 +189,7 @@ public void load(ILoadableManagerContext context) { if (currentResource != null && !currentResource.equals(resource)) { logger.warn("Resources '{}' wasn't sent, because current value '{}' not null", resource, currentResource); } else { - this.location.put(dictionaryURI, resource); + location.put(dictionaryURI, resource); } } @@ -221,26 +221,26 @@ public void finalize(ILoadableManagerContext context) throws Exception { @Override public synchronized IDictionaryStructure getDictionary(SailfishURI uri) throws RuntimeException { - IDictionaryStructure dict = SailfishURIUtils.getMatchingValue(uri, this.dicts, SailfishURIRule.REQUIRE_RESOURCE); + IDictionaryStructure dict = SailfishURIUtils.getMatchingValue(uri, dicts, SailfishURIRule.REQUIRE_RESOURCE); if (dict == null) { this.dictLoadedCounter++; - this.dictionaryIds.put(uri, this.dictLoadedCounter); + dictionaryIds.put(uri, dictLoadedCounter); - String resource = SailfishURIUtils.getMatchingValue(uri, this.location, SailfishURIRule.REQUIRE_RESOURCE); + String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE); if (resource == null) { throw new RuntimeException("No dictionary found for URI: " + uri); } - dict = this.createMessageDictionary(resource); + dict = createMessageDictionary(resource); if (dict == null) { throw new RuntimeException("Can not create dictionary for URI: " + uri +", resource = "+resource); } - this.dicts.put(uri, dict); + dicts.put(uri, dict); logger.info("Dictionary {} was loaded", uri); } @@ -266,9 +266,10 @@ public synchronized IMessageFactory getMessageFactory(SailfishURI uri) { @Override public String toString() { StringBuilder sb = new StringBuilder(); - for (Entry e : this.dicts.entrySet()) { - if (sb.length() > 0) - sb.append(", "); + for(Entry e : dicts.entrySet()) { + if(sb.length() > 0) { + sb.append(", "); + } sb.append(e.getKey()); sb.append(" = "); sb.append(e.getValue().getNamespace()); @@ -279,17 +280,17 @@ public String toString() { @Override public synchronized void invalidateDictionaries(SailfishURI ... uris) { if (uris == null || uris.length == 0) { - this.invalidateEvent(Collections.unmodifiableSet(this.dicts.keySet())); - this.dicts.clear(); - this.dictionaryIds.clear(); - this.factories.clear(); + invalidateEvent(Collections.unmodifiableSet(dicts.keySet())); + dicts.clear(); + dictionaryIds.clear(); + factories.clear(); logger.info("All dictionaries have been invalidated"); } else { - this.invalidateEvent(new HashSet<>(Arrays.asList(uris))); + invalidateEvent(new HashSet<>(Arrays.asList(uris))); for (SailfishURI uri : uris) { - this.dicts.remove(uri); - this.dictionaryIds.remove(uri); - this.factories.remove(uri); + dicts.remove(uri); + dictionaryIds.remove(uri); + factories.remove(uri); } StringBuilder builder = new StringBuilder("Dictionaries ") .append(Arrays.toString(uris)) @@ -333,7 +334,7 @@ private synchronized void createDictionary(String filename, DictionarySettings s SailfishURI uri = settings.getURI(); - if (DictionaryManager.this.getDictionaryURIs().contains(uri)) { + if(getDictionaryURIs().contains(uri)) { if (!overwrite) { throw new EPSCommonException(String.format("Concurrent dictionary registration with SailfishURI: '%s' and name: '%s' already exists", uri, filename)); } @@ -353,10 +354,10 @@ private synchronized void createDictionary(String filename, DictionarySettings s Dictionaries dictionaries = null; - if (this.workspaceDispatcher.exists(FolderType.CFG, PluginLoader.CUSTOM_DICTIONARIES_XML)) { + if(workspaceDispatcher.exists(FolderType.CFG, PluginLoader.CUSTOM_DICTIONARIES_XML)) { try { - File customDictionariesXml = this.workspaceDispatcher.getFile(FolderType.CFG, PluginLoader.CUSTOM_DICTIONARIES_XML); + File customDictionariesXml = workspaceDispatcher.getFile(FolderType.CFG, PluginLoader.CUSTOM_DICTIONARIES_XML); JAXBContext jc = JAXBContext.newInstance(Dictionaries.class); Unmarshaller u = jc.createUnmarshaller(); @@ -374,7 +375,7 @@ private synchronized void createDictionary(String filename, DictionarySettings s dictionaries.getDictionary().add(dictionary); try { - File customDictionariesXml = this.workspaceDispatcher.createFile(FolderType.CFG, true, PluginLoader.CUSTOM_DICTIONARIES_XML); + File customDictionariesXml = workspaceDispatcher.createFile(FolderType.CFG, true, PluginLoader.CUSTOM_DICTIONARIES_XML); JAXBContext jc = JAXBContext.newInstance(Dictionaries.class); Marshaller m = jc.createMarshaller(); @@ -403,7 +404,7 @@ public IDictionaryStructure createMessageDictionary(String pathName) throws Runt try { IDictionaryStructureLoader loader = createStructureLoader(pathName); - File targetFile = this.workspaceDispatcher.getFile(FolderType.ROOT, pathName); + File targetFile = workspaceDispatcher.getFile(FolderType.ROOT, pathName); try (InputStream in = new BufferedInputStream(new FileInputStream(targetFile))) { return loader.load(in); @@ -472,12 +473,12 @@ public long getDictionaryId(SailfishURI uri) { @Override public void subscribeForEvents(IDictionaryManagerListener listener){ - this.eventListeners.add(listener); + eventListeners.add(listener); } @Override public void unSubscribeForEvents(IDictionaryManagerListener listener){ - this.eventListeners.remove(listener); + eventListeners.remove(listener); } public void invalidateEvent(Set uris) { @@ -499,22 +500,22 @@ public void createEvent(SailfishURI uri) { @Override - public IDictionaryRegistrator registerDictionary(final String title, final boolean overwrite) throws WorkspaceStructureException, WorkspaceSecurityException { + public IDictionaryRegistrator registerDictionary(String title, boolean overwrite) throws WorkspaceStructureException, WorkspaceSecurityException { - final SailfishURI suri; + SailfishURI suri; try { suri = new SailfishURI(IVersion.GENERAL, null, title); } catch (SailfishURIException e) { throw new EPSCommonException(String.format("Name '%s' is incorrect", title)); } synchronized (this) { - if (!overwrite && this.getDictionaryURIs().contains(suri)) { + if(!overwrite && getDictionaryURIs().contains(suri)) { throw new EPSCommonException(String.format("Dictionary with title %s and suri %s already registred", title, suri)); } } Path relativePath = Paths.get("cfg", "dictionaries", title + ".xml"); - this.workspaceDispatcher.createFile(FolderType.ROOT, overwrite, relativePath.toString()); + workspaceDispatcher.createFile(FolderType.ROOT, overwrite, relativePath.toString()); return new DictionaryRegistrator(suri, relativePath, overwrite); } @@ -540,30 +541,30 @@ public DictionaryRegistrator(SailfishURI dictionarySURI, Path relativePath, bool this.relativePath = relativePath; this.overwrite = overwrite; this.dictionarySettings = new DictionarySettings(); - this.dictionarySettings.setURI(dictionarySURI); - this.dictionarySettings.setFactoryClass(DummyMessageFactory.class); + dictionarySettings.setURI(dictionarySURI); + dictionarySettings.setFactoryClass(DummyMessageFactory.class); } @Override public SailfishURI registrate() { try { - DictionaryManager.this.createDictionary(this.relativePath.getFileName().toString(), this.dictionarySettings, this.overwrite); + createDictionary(relativePath.getFileName().toString(), dictionarySettings, overwrite); } catch (Exception e) { - throw new EPSCommonException(String.format("Could not create dictionary with SailfishURI: '%s'", this.dictionarySettings.getURI()), e); + throw new EPSCommonException(String.format("Could not create dictionary with SailfishURI: '%s'", dictionarySettings.getURI()), e); } - return this.dictionarySettings.getURI(); + return dictionarySettings.getURI(); } @Override public String getPath() { - return this.relativePath.toString(); + return relativePath.toString(); } @Override public IDictionaryRegistrator addUtilityClassURI(SailfishURI uri) { - this.dictionarySettings.addUtilityClassURI(uri); + dictionarySettings.addUtilityClassURI(uri); return this; } @@ -577,7 +578,7 @@ public IDictionaryRegistrator addUtilityClassURI(Collection uri) { @Override public IDictionaryRegistrator setFactoryClass(Class factoryClass) { - this.dictionarySettings.setFactoryClass(factoryClass); + dictionarySettings.setFactoryClass(factoryClass); return this; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DummyDictionaryManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DummyDictionaryManager.java index 3962ed09..6a2a37a6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DummyDictionaryManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/DummyDictionaryManager.java @@ -39,7 +39,7 @@ public DummyDictionaryManager(Map suriToDictionary public DummyDictionaryManager(IDictionaryStructure dictionaryStructure, SailfishURI dictionaryURI) { this.uriToDictionary = new HashMap<>(); - this.uriToDictionary.put(dictionaryURI.getResourceName(), dictionaryStructure); + uriToDictionary.put(dictionaryURI.getResourceName(), dictionaryStructure); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/EnvironmentManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/EnvironmentManager.java index 791d5930..5e3ab4a2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/EnvironmentManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/EnvironmentManager.java @@ -44,7 +44,7 @@ public class EnvironmentManager implements IEnvironmentManager private final EnvironmentSettings envSettings; - public EnvironmentManager(final IMessageStorage messageStorage, final IServiceStorage serviceStorage, final IConnectionManager connectionManager, final EnvironmentSettings envSettings) throws Exception { + public EnvironmentManager(IMessageStorage messageStorage, IServiceStorage serviceStorage, IConnectionManager connectionManager, EnvironmentSettings envSettings) throws Exception { logger.info("Environment manager initializing started..."); this.messageStorage = messageStorage; this.serviceStorage = serviceStorage; @@ -55,35 +55,35 @@ public EnvironmentManager(final IMessageStorage messageStorage, final IServiceSt @Override public void updateEnvironmentSettings(EnvironmentSettings envSettings) { try { - this.envSettingsLock.writeLock().lock(); + envSettingsLock.writeLock().lock(); this.envSettings.set(envSettings); } finally { - this.envSettingsLock.writeLock().unlock(); + envSettingsLock.writeLock().unlock(); } } @Override public EnvironmentSettings getEnvironmentSettings() { try { - this.envSettingsLock.readLock().lock(); + envSettingsLock.readLock().lock(); return envSettings.clone(); } finally { - this.envSettingsLock.readLock().unlock(); + envSettingsLock.readLock().unlock(); } } @Override public IConnectionManager getConnectionManager() { - return this.connectionManager; + return connectionManager; } @Override public IMessageStorage getMessageStorage() { - return this.messageStorage; + return messageStorage; } @Override public IServiceStorage getServiceStorage() { - return this.serviceStorage; + return serviceStorage; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManager.java index 891d2e99..7d0bedd0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManager.java @@ -20,6 +20,6 @@ * */ public interface ILoadableManager { - public void load(final ILoadableManagerContext context) throws Exception; - public void finalize(final ILoadableManagerContext context) throws Exception; + void load(ILoadableManagerContext context) throws Exception; + void finalize(ILoadableManagerContext context) throws Exception; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManagerContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManagerContext.java index 7826b3e6..baff9372 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManagerContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/ILoadableManagerContext.java @@ -25,8 +25,8 @@ */ public interface ILoadableManagerContext { - public IVersion getVersion(); - public String getResourceFolder(); - public ClassLoader[] getClassLoaders(); - public InputStream getResourceStream(); + IVersion getVersion(); + String getResourceFolder(); + ClassLoader[] getClassLoaders(); + InputStream getResourceStream(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfiguration.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfiguration.java index 7c5aed9d..918cf942 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfiguration.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfiguration.java @@ -24,8 +24,8 @@ */ public class LoggingConfiguration implements ILoggingConfiguration, ICommonSettings { - private final static String INDIVIDUAL_APPENDER_ENABLE_PROPERTY = "IndividualAppendersEnabled"; - private final static String INDIVIDUAL_APPENDER_THRESHOLD_PROPERTY = "IndividualAppendersThreshold"; + private static final String INDIVIDUAL_APPENDER_ENABLE_PROPERTY = "IndividualAppendersEnabled"; + private static final String INDIVIDUAL_APPENDER_THRESHOLD_PROPERTY = "IndividualAppendersThreshold"; private boolean individualAppendersEnabled; private final HierarchicalConfiguration config; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfigurator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfigurator.java index 039f7b1a..67ffb537 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfigurator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/LoggingConfigurator.java @@ -243,7 +243,7 @@ private static String toLogPath(ServiceName serviceName, boolean folderOnly) { .append(serviceName.getEnvironment()).append(separator) .append(serviceName.getServiceName()); if (!folderOnly) { - pathBuilder.append(separator).append(serviceName.toString()); + pathBuilder.append(separator).append(serviceName); } return pathBuilder.toString(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/DictionaryValidationErrorLevel.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/DictionaryValidationErrorLevel.java index ec83e397..4ab08fe0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/DictionaryValidationErrorLevel.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/DictionaryValidationErrorLevel.java @@ -19,6 +19,6 @@ public enum DictionaryValidationErrorLevel { DICTIONARY, MESSAGE, - FIELD; + FIELD } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/ValidationHelper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/ValidationHelper.java index 2a4df951..109bcd55 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/ValidationHelper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/ValidationHelper.java @@ -21,6 +21,8 @@ import java.util.List; import java.util.Set; +import org.apache.commons.lang3.ClassUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,8 +54,8 @@ public static void checkDuplicates(IMessageStructure message, Collection\"" + field.getName() + "\"", level, DictionaryValidationErrorType.ERR_DUPLICATE_NAME)); - - logger.error("[{}{}] Duplicated field", (message != null ? message.getName() + "/" : ""), field.getName()); + + logger.error("[{}{}] Duplicated field", message != null ? message.getName() + "/" : "", field.getName()); } } @@ -174,7 +176,7 @@ public static boolean checkMessageAttributeType(List IAttributeStructure messageTypeStructure = message.getAttributes().get(attributeName); - return ValidationHelper.checkAttributeType(errors, messageTypeStructure, message, null, + return checkAttributeType(errors, messageTypeStructure, message, null, attributeName, expectedJavaType, possibleValues); } @@ -184,7 +186,7 @@ public static boolean checkFieldAttributeType(List er IAttributeStructure messageTypeStructure = field.getAttributes().get(attributeName); - return ValidationHelper.checkAttributeType(errors, messageTypeStructure, null, field, + return checkAttributeType(errors, messageTypeStructure, null, field, attributeName, expectedJavaType, possibleValues); } @@ -208,7 +210,7 @@ public static boolean checkAttributeType(List errors, return false; } - if(!messageTypeStructure.getType().equals(expectedJavaType)) { + if(messageTypeStructure.getType() != expectedJavaType) { errors.add(new DictionaryValidationError(messageName, fieldName, type + " \"" + name + "\" contain " + attributeName + " attribute" @@ -242,64 +244,80 @@ private static boolean isTypeApplicable(IFieldStructure field, JavaType type, Ob String value = null; try { - - if (objValue == null) return true; - - if (type == null) return true; - - if (!(objValue instanceof String)) { - return true; - } - - value = (String) objValue; - - if (value.isEmpty()) return true; + + if(objValue == null || type == null || !(objValue instanceof String)) { + return true; + } + + value = (String)objValue; + + if(value.isEmpty()) { + return true; + } switch (type) { - - case JAVA_LANG_BOOLEAN : - - if (null == boolValueOf(value)) throw new ClassCastException(); + + case JAVA_LANG_BOOLEAN: + + if(boolValueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_BYTE : - - if (null == Byte.valueOf(value)) throw new ClassCastException(); + + if(Byte.valueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_SHORT : - - if (null == Short.valueOf(value)) throw new ClassCastException(); + + if(Short.valueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_INTEGER : - - if (null == Integer.valueOf(value)) throw new ClassCastException(); + + if(Integer.valueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_LONG : - - if (null == Long.valueOf(value)) throw new ClassCastException(); + + if(Long.valueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_FLOAT : - - if (null == Float.valueOf(value)) throw new ClassCastException(); + + if(Float.valueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_DOUBLE : - - if (null == Double.valueOf(value)) throw new ClassCastException(); + + if(Double.valueOf(value) == null) { + throw new ClassCastException(); + } break; case JAVA_LANG_CHARACTER : - - if (value.length() > 1) throw new ClassCastException(); + + if(value.length() > 1) { + throw new ClassCastException(); + } break; case JAVA_MATH_BIG_DECIMAL : - - if (null == BigDecimal.valueOf(Double.valueOf(value))) throw new ClassCastException(); + + if(BigDecimal.valueOf(Double.valueOf(value)) == null) { + throw new ClassCastException(); + } break; default: break; @@ -317,24 +335,27 @@ private static boolean isTypeApplicable(IFieldStructure field, JavaType type, Ob } private static Boolean boolValueOf(String value) { - - if ("Y".equals(value)) return true; - - if ("N".equals(value)) return false; - - if (Boolean.valueOf(value)) return true; - - if (!value.equalsIgnoreCase("false")) return null; + + if("Y".equals(value)) { + return true; + } + + if("N".equals(value)) { + return false; + } + + if(Boolean.valueOf(value)) { + return true; + } + + if(!"false".equalsIgnoreCase(value)) { + return null; + } return false; } private static String getJavaTypeLabel(JavaType type) { - int index = type.value().lastIndexOf(".") + 1; - String result = type.value(); - if (index != 0) { - result = type.value().substring(index); - } - return result; - } + return ClassUtils.getShortClassName(type.value()); + } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/AbstractDictionaryValidator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/AbstractDictionaryValidator.java index b1713e8e..27523210 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/AbstractDictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/AbstractDictionaryValidator.java @@ -49,8 +49,8 @@ public List validate(IDictionaryStructure dictionary, List errors = new ArrayList<>(); - if (this.parentValidator != null) { - errors.addAll(this.parentValidator.validate(dictionary, false, null)); + if(parentValidator != null) { + errors.addAll(parentValidator.validate(dictionary, false, null)); } if (full) { @@ -71,8 +71,8 @@ public List validate(IDictionaryStructure dictionary, public List validate(IDictionaryStructure dictionary, IMessageStructure message, boolean full) { List errors = new ArrayList<>(); - if (this.parentValidator != null) { - errors.addAll(this.parentValidator.validate(dictionary, message, false)); + if(parentValidator != null) { + errors.addAll(parentValidator.validate(dictionary, message, false)); } if (full) { @@ -87,8 +87,8 @@ public List validate(IMessageStructure message, IFiel List errors = new ArrayList<>(); - if (this.parentValidator != null) { - errors.addAll(this.parentValidator.validate(message, field)); + if(parentValidator != null) { + errors.addAll(parentValidator.validate(message, field)); } return errors; @@ -98,7 +98,7 @@ protected void checkMessages(IDictionaryStructure dictionary, List fields, List errors, Map values, DictionaryValidationErrorType errType) { - if (value == null) return; - if (value instanceof String && StringUtils.isEmpty((String)value)) return; - if (values == null || values.isEmpty()) return; + if(value == null) { + return; + } + if(value instanceof String && StringUtils.isEmpty((String)value)) { + return; + } + if(values == null || values.isEmpty()) { + return; + } boolean found = false; @@ -154,7 +159,7 @@ private void checkContainsError(List errors, "Value \"" + value + "\" wasn't found in values table", DictionaryValidationErrorLevel.FIELD, errType)); - logger.error("[{}{}] Value \"{}\" wasn't found in values table", (message != null ? message.getName() + "/" : ""), field.getName(), value); + logger.error("[{}{}] Value \"{}\" wasn't found in values table", message != null ? message.getName() + "/" : "", field.getName(), value); } } @@ -216,7 +221,7 @@ private enum Structure { Dictionary, Attribute, Value { - Set prohibit = new HashSet<>(prohibitedNames); + final Set prohibit = new HashSet<>(prohibitedNames); { prohibit.add("Missed"); prohibit.add("Present"); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/PrototypeDictionaryValidator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/PrototypeDictionaryValidator.java index 08c0beeb..56287c5a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/PrototypeDictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/impl/PrototypeDictionaryValidator.java @@ -128,7 +128,7 @@ private void catchDifference(List errors, DictionaryV String field = dictionaryPath.getField(); - if (DictionaryValidationErrorType.ERR_REQUIRED_FIELD == type) { + if(type == DictionaryValidationErrorType.ERR_REQUIRED_FIELD) { field = null; } @@ -154,38 +154,33 @@ private String createCommonErrorMsg(DistinctionType type, Object prototype, Obje switch (type) { case AttributeValue: if (actual == null) { - errorMsg = String.format("Attribute %s was missed", path.getAttribute()); + return String.format("Attribute %s was missed", path.getAttribute()); } else { - errorMsg = String.format("Attribute %s should be %s but was %s", path.getAttribute(), prototype, actual); + return String.format("Attribute %s should be %s but was %s", path.getAttribute(), prototype, actual); } - break; - case EnumValue: + case EnumValue: if (actual == null) { - errorMsg = String.format("Value %s was missed", path.getValue()); + return String.format("Value %s was missed", path.getValue()); } else { - errorMsg = String.format("Value %s should be %s but was %s", path.getValue(), prototype, actual); + return String.format("Value %s should be %s but was %s", path.getValue(), prototype, actual); } - break; - case JavaType: + case JavaType: case IsCollection: case IsRequired: case IsServiceName: case IsComplex: case IsEnum: case DefaultValue: - errorMsg = String.format("%s should be %s but was %s", type, prototype, actual); - break; - case Existing: - errorMsg = "Missed required field " + path.getField() + ""; - break; - case FieldOrder: + return String.format("%s should be %s but was %s", type, prototype, actual); + case Existing: + return "Missed required field " + path.getField() + ""; + case FieldOrder: errorMsg = String.format("At this position message should have field %s but it was %s", prototype, actual); default: //do nothing - break; + return errorMsg; } - return errorMsg; } private String createDictionaryErrorMsg(DictionaryPath path) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/interfaces/IDictionaryValidator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/interfaces/IDictionaryValidator.java index 1fd3fbec..3d98818a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/interfaces/IDictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/dictionary/interfaces/IDictionaryValidator.java @@ -24,7 +24,7 @@ public interface IDictionaryValidator { - public static final String NAME_REGEX = "[a-zA-Z]+\\w*"; + String NAME_REGEX = "[a-zA-Z]+\\w*"; /** * fieldsOnly == null ? Validate messages and fields diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperOptions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperOptions.java index 26f4db74..ecbce2a2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperOptions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperOptions.java @@ -17,19 +17,20 @@ import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; public class NetDumperOptions implements Cloneable { - private final static String STORAGE_PREFIX = "netdumper."; + private static final String STORAGE_PREFIX = "netdumper."; private String rootHost = "0.0.0.0"; private int rootPort = 6000; private boolean enabled; public void fillFromMap(Map options) throws Exception { - for (Map.Entry entry : options.entrySet()) { + for(Entry entry : options.entrySet()) { if (entry.getKey().startsWith(STORAGE_PREFIX)) { BeanUtils.setProperty(this, entry.getKey().replace(STORAGE_PREFIX, ""), entry.getValue()); } @@ -41,9 +42,9 @@ public Map toMap() throws Exception { Map description = BeanUtils.describe(this); Map result = new HashMap<>(); - - for (Map.Entry entry : description.entrySet()) { - if (!entry.getKey().equals("class")) { + + for(Entry entry : description.entrySet()) { + if(!"class".equals(entry.getKey())) { result.put(STORAGE_PREFIX + entry.getKey(), entry.getValue()); } } @@ -56,9 +57,9 @@ public String getRootUrl() { StringBuilder builder = new StringBuilder(); builder.append("http://") - .append(this.rootHost) + .append(rootHost) .append(":") - .append(this.rootPort); + .append(rootPort); return builder.toString(); } @@ -67,9 +68,9 @@ public NetDumperOptions clone() { NetDumperOptions options = new NetDumperOptions(); - options.setEnabled(this.enabled); - options.setRootHost(this.rootHost); - options.setRootPort(this.rootPort); + options.setEnabled(enabled); + options.setRootHost(rootHost); + options.setRootPort(rootPort); return options; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperService.java index 5a026bf9..0d1a8767 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/NetDumperService.java @@ -28,6 +28,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReadWriteLock; @@ -98,18 +99,18 @@ public void init() { try { - this.readWriteLock.writeLock().lock(); - this.options.fillFromMap(optionsStorage.getAllOptions()); + readWriteLock.writeLock().lock(); + options.fillFromMap(optionsStorage.getAllOptions()); } catch (Exception e) { logger.error("Settings could not be read; connection to RESTDumper will fail"); } finally { - this.readWriteLock.writeLock().unlock(); + readWriteLock.writeLock().unlock(); } - this.connectionManager.subscribeForEvents(this); + connectionManager.subscribeForEvents(this); } @Override @@ -117,14 +118,14 @@ public void onEvent(ServiceEvent event) { try { - this.readWriteLock.readLock().lock(); + readWriteLock.readLock().lock(); - if (!this.options.isEnabled()) { + if(!options.isEnabled()) { return; } } finally { - this.readWriteLock.readLock().unlock(); + readWriteLock.readLock().unlock(); } if (event instanceof ServiceStatusUpdateEvent) { @@ -137,7 +138,7 @@ public void onEvent(ServiceEvent event) { if (event.getType() != Type.STARTING && event.getType() != Type.STARTED) { - List clients = this.serviceRecordings.remove(event.getServiceName()); + List clients = serviceRecordings.remove(event.getServiceName()); if (clients != null) { handleFinish(clients); @@ -153,22 +154,22 @@ public void onEvent(ServiceEvent event) { public NetDumperOptions getOptions() { try { - this.readWriteLock.readLock().lock(); - return this.options.clone(); + readWriteLock.readLock().lock(); + return options.clone(); } finally { - this.readWriteLock.readLock().unlock(); + readWriteLock.readLock().unlock(); } } public File[] getRecordedFiles() throws IOException { - if (this.recordedFiles == null) { + if(recordedFiles == null) { updateFiles(); } - return this.recordedFiles; + return recordedFiles; } private void updateFiles() throws IOException { - this.recordedFiles = this.workspaceDispatcher.getFolder(FolderType.TRAFFIC_DUMP).listFiles(); + this.recordedFiles = workspaceDispatcher.getFolder(FolderType.TRAFFIC_DUMP).listFiles(); } public boolean checkAvailability() { @@ -177,11 +178,11 @@ public boolean checkAvailability() { try { - this.readWriteLock.readLock().lock();; - rootUrl = this.options.getRootUrl(); + readWriteLock.readLock().lock(); + rootUrl = options.getRootUrl(); } finally { - this.readWriteLock.readLock().unlock(); + readWriteLock.readLock().unlock(); } try { @@ -211,18 +212,18 @@ public void applyOptions(NetDumperOptions options) { try { - this.readWriteLock.writeLock().lock(); + readWriteLock.writeLock().lock(); this.options = options; - for (Map.Entry option : options.toMap().entrySet()) { - this.optionsStorage.setOption(option.getKey(), option.getValue()); + for(Entry option : options.toMap().entrySet()) { + optionsStorage.setOption(option.getKey(), option.getValue()); } } catch (Exception e) { throw new RuntimeException(e); } finally { - this.readWriteLock.writeLock().unlock(); + readWriteLock.writeLock().unlock(); } } @@ -243,7 +244,7 @@ public void startRecording(long recordId, ServiceName[] services) { for (ServiceName svcName : services) { list.addAll(startRecordingService(svcName, svcName.toString())); } - this.externalRecorders.put(recordId, list); + externalRecorders.put(recordId, list); } catch (Exception e) { logger.error("An error occured while starting traffic recording for matrix", e); @@ -253,13 +254,13 @@ public void startRecording(long recordId, ServiceName[] services) { public void stopAndZip(long recordId, OutputStream out) { try { ZipOutputStream zip = new ZipOutputStream(out); - for (RESTDumperClient cl : this.externalRecorders.get(recordId)) { + for(RESTDumperClient cl : externalRecorders.get(recordId)) { zip.putNextEntry(new ZipEntry(cl.generateFilename())); cl.stopRecord(zip); zip.closeEntry(); } zip.close(); - this.externalRecorders.remove(recordId); + externalRecorders.remove(recordId); } catch (Exception e) { logger.error("An error occured while finishing traffic recording for matrix", e); @@ -268,12 +269,12 @@ public void stopAndZip(long recordId, OutputStream out) { public void stopAndStore(long recordId, File rootDir) { try { - for (RESTDumperClient cl : this.externalRecorders.get(recordId)) { + for(RESTDumperClient cl : externalRecorders.get(recordId)) { try (OutputStream out = new FileOutputStream(rootDir.getAbsolutePath() + File.separator + cl.generateFilename())) { cl.stopRecord(out); } } - this.externalRecorders.remove(recordId); + externalRecorders.remove(recordId); } catch (Exception e) { logger.error("An error occured while finishing traffic recording for matrix", e); @@ -282,7 +283,7 @@ public void stopAndStore(long recordId, File rootDir) { private List startRecordingService(ServiceName svcName, String identifier) throws Exception { - IServiceSettings svcSettings = this.connectionManager.getServiceDescription(svcName).getSettings(); + IServiceSettings svcSettings = connectionManager.getServiceDescription(svcName).getSettings(); if (!svcSettings.isPerformDump()) { return new ArrayList<>(); @@ -313,11 +314,11 @@ private List startRecordingService(ServiceName svcName, String try { - this.readWriteLock.readLock().lock(); - rootUrl = this.options.getRootUrl(); + readWriteLock.readLock().lock(); + rootUrl = options.getRootUrl(); } finally { - this.readWriteLock.readLock().unlock(); + readWriteLock.readLock().unlock(); } for (Integer index : catchMap.keySet()) { @@ -353,14 +354,14 @@ private String getProperty(IServiceSettings svcSettings, Field fld) throws Excep } private void handleStart(ServiceName svcName, Date startTime) throws Exception { - this.serviceRecordings.put(svcName, startRecordingService(svcName, svcName.toString() + "." + + serviceRecordings.put(svcName, startRecordingService(svcName, svcName + "." + dateFormat.get().format(startTime))); } private void handleFinish(List clients) throws Exception { for (RESTDumperClient cl : clients) { - cl.stopRecord(this.workspaceDispatcher.createFile(FolderType.TRAFFIC_DUMP, false, cl.generateFilename())); + cl.stopRecord(workspaceDispatcher.createFile(FolderType.TRAFFIC_DUMP, false, cl.generateFilename())); } updateFiles(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/RESTDumperClient.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/RESTDumperClient.java index 06bf5ac7..779460ad 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/RESTDumperClient.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/netdumper/RESTDumperClient.java @@ -62,7 +62,7 @@ public String generateFilename() { .append(".") .append(host) .append("_") - .append(String.valueOf(port)) + .append(port) .append(".tcpdump"); return builder.toString(); @@ -72,15 +72,15 @@ public void start() throws NetDumperException, ClientProtocolException, IOExcept StringBuilder builder = new StringBuilder(); - builder.append(this.rdRoot) + builder.append(rdRoot) .append("/start?host=") - .append(this.host) + .append(host) .append("&port=") - .append(String.valueOf(this.port)); + .append(port); - if (this.iface != null) { + if(iface != null) { builder.append("&iface=") - .append(this.iface); + .append(iface); } HttpGet req = new HttpGet(builder.toString()); @@ -110,9 +110,9 @@ public void stopRecord(OutputStream target) throws ClientProtocolException, IOEx StringBuilder builder = new StringBuilder(); - builder.append(this.rdRoot) + builder.append(rdRoot) .append("/stop?id=") - .append(this.index); + .append(index); HttpGet req = new HttpGet(builder.toString()); HttpResponse resp = http.execute(req); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderOptions.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderOptions.java index b46ab2c7..94c320b2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderOptions.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderOptions.java @@ -18,6 +18,7 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; @@ -32,7 +33,7 @@ public class FlightRecorderOptions implements Serializable { public void fillFromMap(Map options) throws Exception { - for(Map.Entry entry : options.entrySet()) { + for(Entry entry : options.entrySet()) { if(entry.getKey().startsWith(STORAGE_PREFIX)) { @@ -51,9 +52,9 @@ public Map toMap() throws Exception { Map result = new HashMap(); - for(Map.Entry entry : description.entrySet()) { - - if(!entry.getKey().equals("class")) { + for(Entry entry : description.entrySet()) { + + if(!"class".equals(entry.getKey())) { result.put(STORAGE_PREFIX + entry.getKey(), entry.getValue()); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderService.java index 9bb6a9b7..176bf645 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/FlightRecorderService.java @@ -28,7 +28,7 @@ import java.util.Collections; import java.util.Date; import java.util.List; -import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; @@ -44,28 +44,28 @@ public class FlightRecorderService { private static final String JCMD_INVOKE_COMMAND = " %s JFR.start duration=%ss name=MyRecording filename='%s' settings=profile"; - - private volatile boolean recordingStarted = false; - - private volatile boolean continiousRecordingStarted = false; + + private volatile boolean recordingStarted; + + private volatile boolean continiousRecordingStarted; private String errorMessage; private boolean canRecord = true; - - private final String[] requiredOptions = new String[] {"-XX:+UnlockCommercialFeatures", "-XX:+FlightRecorder"}; + + private final String[] requiredOptions = { "-XX:+UnlockCommercialFeatures", "-XX:+FlightRecorder" }; private final List recordFiles = new ArrayList(); - - private volatile Date busyTill = null; - - private ITaskExecutor taskExecutor; + + private volatile Date busyTill; + + private final ITaskExecutor taskExecutor; private ContiniousRecordTask continiousRecordingTask; private volatile FlightRecorderOptions settings; - - private IOptionsStorage optionsStorage; + + private final IOptionsStorage optionsStorage; public FlightRecorderService(ITaskExecutor taskExecutor, IOptionsStorage optionsStorage) { @@ -76,8 +76,8 @@ public FlightRecorderService(ITaskExecutor taskExecutor, IOptionsStorage options this.settings = new FlightRecorderOptions(); try { - - this.settings.fillFromMap(optionsStorage.getAllOptions()); + + settings.fillFromMap(optionsStorage.getAllOptions()); } catch (Exception e) { @@ -92,16 +92,16 @@ public FlightRecorderService(ITaskExecutor taskExecutor, IOptionsStorage options } private void initDefaultSettings() { - - if(this.settings.getJdkPath() == null) { - - this.settings.setJdkPath(getJdkFolder()); + + if(settings.getJdkPath() == null) { + + settings.setJdkPath(getJdkFolder()); } - - if(this.settings.getRecordsFolder() == null) { - - this.settings.setRecordsFolder(System.getProperty("java.io.tmpdir")); + + if(settings.getRecordsFolder() == null) { + + settings.setRecordsFolder(System.getProperty("java.io.tmpdir")); } @@ -150,8 +150,8 @@ private void checkRequiredJvmOptions() { List missingArguments = new ArrayList<>(); logger.info("{}", arguments); - - for(String option : this.requiredOptions) { + + for(String option : requiredOptions) { if(!arguments.contains(option)) { @@ -168,28 +168,20 @@ private void checkRequiredJvmOptions() { } } - - private String getJdkFolder() { - - String environmentValue = System.getenv("JAVA_HOME"); - - if(StringUtils.isNotEmpty(environmentValue)) { - return environmentValue; - } - - return System.getProperty("java.home"); - - } + + private String getJdkFolder() { + return StringUtils.defaultIfEmpty(System.getenv("JAVA_HOME"), System.getProperty("java.home")); + } private String getProcessId() { // Note: may fail in some JVM implementations // something like '@', at least in SUN / Oracle JVMs - final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); + String jvmName = ManagementFactory.getRuntimeMXBean().getName(); logger.info("JVM name: {}", jvmName); - - final int index = jvmName.indexOf('@'); + + int index = jvmName.indexOf('@'); if (index < 1) { // part before '@' empty (index = 0) / '@' not found (index = -1) @@ -211,8 +203,8 @@ private String getProcessId() { private void refreshFilesList() { List toRemove = new ArrayList<>(); - - for(RecordedFile file : this.recordFiles) { + + for(RecordedFile file : recordFiles) { File fsFile = new File(file.getPath()); @@ -227,8 +219,8 @@ private void refreshFilesList() { } if(!toRemove.isEmpty()) { - - this.recordFiles.removeAll(toRemove); + + recordFiles.removeAll(toRemove); } @@ -237,12 +229,12 @@ private void refreshFilesList() { private File createRecordFile(String name) { try { - - File recordsFolder = new File(this.settings.getRecordsFolder()); + + File recordsFolder = new File(settings.getRecordsFolder()); if(!recordsFolder.exists()) { - - throw new FileNotFoundException(this.settings.getRecordsFolder()); + + throw new FileNotFoundException(settings.getRecordsFolder()); } @@ -265,14 +257,14 @@ private File createRecordFile(String name) { public void applySettings(FlightRecorderOptions settings) { this.settings = settings; - - this.recordFiles.clear(); + + recordFiles.clear(); try { - - for(Map.Entry option : this.settings.toMap().entrySet()) { - - this.optionsStorage.setOption(option.getKey(), option.getValue()); + + for(Entry option : this.settings.toMap().entrySet()) { + + optionsStorage.setOption(option.getKey(), option.getValue()); } @@ -293,18 +285,18 @@ private String createRecordFileName(Date from, Date to) { } public synchronized void startRecording(long duration) { - - if(this.recordingStarted) { - - if(this.busyTill.after(new Date())) { + + if(recordingStarted) { + + if(busyTill.after(new Date())) { throw new IllegalStateException("Recording already in progress"); } } - - String jvmPath =this.settings.getJdkPath(); + + String jvmPath = settings.getJdkPath(); if(StringUtils.isEmpty(jvmPath)) { @@ -337,7 +329,7 @@ public synchronized void startRecording(long duration) { File jcmdFile = null; for (File file : binFolder.listFiles()) { - if (file.getName().equals("jcmd") || file.getName().startsWith("jcmd.")) { + if("jcmd".equals(file.getName()) || file.getName().startsWith("jcmd.")) { jcmdFile = file; break; } @@ -357,29 +349,29 @@ public synchronized void startRecording(long duration) { this.recordingStarted = true; this.busyTill = recordedTo; - - this.recordFiles.add(0, new RecordedFile(fileName, - resultFile.getAbsolutePath(), recordedFrom, recordedTo) ); + + recordFiles.add(0, new RecordedFile(fileName, + resultFile.getAbsolutePath(), recordedFrom, recordedTo) ); } public synchronized void startContiniousRecording(long durationChank) { this.continiousRecordingTask = new ContiniousRecordTask(durationChank); - - this.taskExecutor.addRepeatedTask(continiousRecordingTask, 0, durationChank, TimeUnit.SECONDS); + + taskExecutor.addRepeatedTask(continiousRecordingTask, 0, durationChank, TimeUnit.SECONDS); this.continiousRecordingStarted = true; } public synchronized void stopContiniousRecording() { - - if(this.continiousRecordingTask == null) { + + if(continiousRecordingTask == null) { throw new IllegalStateException("Recording is not started"); } - - this.continiousRecordingTask.stop(); + + continiousRecordingTask.stop(); this.continiousRecordingStarted = false; @@ -388,8 +380,8 @@ public synchronized void stopContiniousRecording() { public synchronized List getRecordedFiles() { refreshFilesList(); - - return Collections.unmodifiableList(this.recordFiles); + + return Collections.unmodifiableList(recordFiles); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/RecordedFile.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/RecordedFile.java index 5ef7c7ab..68cd3003 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/RecordedFile.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/recorder/RecordedFile.java @@ -30,8 +30,7 @@ public class RecordedFile { private long size; public RecordedFile(String name, String path, Date from, Date to) { - super(); - this.name = name; + this.name = name; this.path = path; this.from = from; this.to = to; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/AbstractWorkspaceLayout.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/AbstractWorkspaceLayout.java index ffe90624..b45bd945 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/AbstractWorkspaceLayout.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/AbstractWorkspaceLayout.java @@ -26,8 +26,9 @@ public boolean isEmbedded() { protected String getFolder(FolderType folderType) { - if (folderType == null) + if(folderType == null) { throw new NullPointerException(); + } switch (folderType) { case MATRIX: return "uploaded"; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/DefaultWorkspaceDispatcher.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/DefaultWorkspaceDispatcher.java index 3df4bdad..eac54755 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/DefaultWorkspaceDispatcher.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/DefaultWorkspaceDispatcher.java @@ -35,6 +35,7 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,13 +67,7 @@ public DefaultWorkspaceDispatcher(List> workspaceCo this.createDirectories = createDirectories; if(workspaceConfigs == null || workspaceConfigs.isEmpty()) { - File workspaceFolder = null; - if (System.getProperties().containsKey("user.dir")) { - workspaceFolder = new File(System.getProperty("user.dir")); - } else { - workspaceFolder = new File("."); - } - + File workspaceFolder = new File(ObjectUtils.defaultIfNull(System.getProperty("user.dir"), ".")); workspaceConfigs = new ArrayList<>(1); workspaceConfigs.add(new Pair<>(workspaceFolder, DefaultWorkspaceLayout.getInstance())); } @@ -92,8 +87,8 @@ public DefaultWorkspaceDispatcher(List> workspaceCo } if (!isDuplicatePath(workspaceFolder)) { - this.workspaces.add(new WorkspaceLayer(workspaceFolder, config.getSecond())); - logger.info("Workspace {} has been added to the layer {}", workspaceFolder, this.workspaces.size()); + workspaces.add(new WorkspaceLayer(workspaceFolder, config.getSecond())); + logger.info("Workspace {} has been added to the layer {}", workspaceFolder, workspaces.size()); } else { logger.warn("Workspace {} has been skipped, because it overrides existing layers", workspaceFolder); } @@ -102,8 +97,9 @@ public DefaultWorkspaceDispatcher(List> workspaceCo } } - if (workspaces.isEmpty()) - throw new IllegalArgumentException("No exisiting workspace was specified"); + if(workspaces.isEmpty()) { + throw new IllegalArgumentException("No exisiting workspace was specified"); + } } @Override @@ -136,15 +132,15 @@ public File getFolder(FolderType folderType) throws FileNotFoundException { checkFolderType(folderType); try { - this.workspacesLock.readLock().lock(); - File targetDir = this.workspaces.get(this.workspaces.size() - 1).get(folderType); + workspacesLock.readLock().lock(); + File targetDir = workspaces.get(workspaces.size() - 1).get(folderType); if (targetDir.exists() || targetDir.mkdirs()) { return targetDir; } throw new FileNotFoundException("Folder {" + folderType + "}/" + targetDir + " can't be created"); } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } } @@ -159,14 +155,14 @@ public File getOrCreateFile(FolderType folderType, String... fileName) throws Wo checkFolderTypeAndFileName(folderType, fileName); try { - this.workspacesLock.readLock().lock(); - File targetFile = new File(this.workspaces.get(this.workspaces.size() - 1).get(folderType), toPathString(fileName)); + workspacesLock.readLock().lock(); + File targetFile = new File(workspaces.get(workspaces.size() - 1).get(folderType), toPathString(fileName)); if (targetFile.exists()) { return targetFile; } - WorkspaceLayer workspaceLayer = this.workspaces.get(this.workspaces.size() - 1); + WorkspaceLayer workspaceLayer = workspaces.get(workspaces.size() - 1); if (workspaceLayer.layout.isEmbedded()) { throw new WorkspaceLayerException("File {" + folderType + "}/" + toPathString(fileName) + " can't be created, the last layer is embedded"); } @@ -183,7 +179,7 @@ public File getOrCreateFile(FolderType folderType, String... fileName) throws Wo throw new WorkspaceStructureException("File {" + folderType + "}/" + toPathString(fileName) + " can't be created"); } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } } @@ -192,8 +188,8 @@ public File createFolder(FolderType folderType, String... folderName) throws Wor checkFolderTypeAndFileName(folderType, folderName); try { - this.workspacesLock.readLock().lock(); - WorkspaceLayer workspaceLayer = this.workspaces.get(this.workspaces.size() - 1); + workspacesLock.readLock().lock(); + WorkspaceLayer workspaceLayer = workspaces.get(workspaces.size() - 1); String path = toPathString(folderName); if (workspaceLayer.layout.isEmbedded()) { throw new WorkspaceLayerException("Folder {" + folderType + "}/" + path + " can't be created, the last layer is embedded"); @@ -208,7 +204,7 @@ public File createFolder(FolderType folderType, String... folderName) throws Wor throw new WorkspaceStructureException("Folder {" + folderType + "}/" + targetFolder + " can't be created"); } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } } @@ -221,8 +217,8 @@ public File createFile(FolderType folderType, boolean overwrite, String... fileN checkFolderTypeAndFileName(folderType, fileName); try { - this.workspacesLock.readLock().lock(); - WorkspaceLayer workspaceLayer = this.workspaces.get(this.workspaces.size() - 1); + workspacesLock.readLock().lock(); + WorkspaceLayer workspaceLayer = workspaces.get(workspaces.size() - 1); String path = toPathString(fileName); if (workspaceLayer.layout.isEmbedded()) { throw new WorkspaceLayerException("Folder {" + folderType + "}/" + path + " can't be created, the last layer is embedded"); @@ -254,7 +250,7 @@ public File createFile(FolderType folderType, boolean overwrite, String... fileN throw new WorkspaceStructureException("File {" + folderType + "}/" + toPathString(fileName) + " can't be created"); } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } } @@ -262,13 +258,13 @@ public File createFile(FolderType folderType, boolean overwrite, String... fileN public boolean exists(FolderType folderType, String... fileName) throws WorkspaceSecurityException { if (folderType != null && fileName != null) { try { - this.workspacesLock.readLock().lock(); + workspacesLock.readLock().lock(); getExists(folderType, fileName); return true; } catch (FileNotFoundException | WorkspaceSecurityException e) { // FIXME: is it ok to drop WorkspaceSecurityException ? // it is normal control flow path: return false } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } } return false; @@ -346,12 +342,12 @@ public Set listFiles(FileFilter filter, FolderType folderType, boolean r } try { - this.workspacesLock.readLock().lock(); + workspacesLock.readLock().lock(); Set result = new HashSet<>(); - for (int i = 0; i < this.workspaces.size(); i++) { - File folderInWorkspace = new File(this.workspaces.get(i).get(folderType), toPathString(folderName)); + for(int i = 0; i < workspaces.size(); i++) { + File folderInWorkspace = new File(workspaces.get(i).get(folderType), toPathString(folderName)); if (!folderInWorkspace.exists()) { continue; } @@ -373,7 +369,7 @@ public Set listFiles(FileFilter filter, FolderType folderType, boolean r return result; } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } } @@ -385,16 +381,16 @@ public Set listFiles(FileFilter filter, FolderType folderType, boolean r * @return * @throws FileNotFoundException */ - private Map.Entry getExists(FolderType folderType, String... fileName) throws FileNotFoundException, WorkspaceSecurityException { + private Entry getExists(FolderType folderType, String... fileName) throws FileNotFoundException, WorkspaceSecurityException { File targetFile = null; try { - this.workspacesLock.readLock().lock(); - for (int i = this.workspaces.size() - 1; i >= 0; i--) { - WorkspaceLayer layer = this.workspaces.get(i); + workspacesLock.readLock().lock(); + for(int i = workspaces.size() - 1; i >= 0; i--) { + WorkspaceLayer layer = workspaces.get(i); targetFile = new File(layer.get(folderType), toPathString(fileName)); Path targetPath = targetFile.toPath().normalize(); - Path rootPath = this.workspaces.get(i).get(folderType).toPath().normalize(); + Path rootPath = workspaces.get(i).get(folderType).toPath().normalize(); if (! targetPath.startsWith(rootPath)) { throw new WorkspaceSecurityException("Access outside workspace is denied. Access file: {" + folderType + "}/" + toPathString(fileName)); } @@ -405,7 +401,7 @@ private Map.Entry getExists(FolderType folderType, String. } } } finally { - this.workspacesLock.readLock().unlock(); + workspacesLock.readLock().unlock(); } throw new FileNotFoundException("Workspaces doesn't contain file {" + folderType + "}/" + toPathString(fileName)); @@ -413,8 +409,8 @@ private Map.Entry getExists(FolderType folderType, String. private boolean isDuplicatePath(File rootFolder) { Path newPath = rootFolder.toPath(); - for (int i = 0; i < this.workspaces.size(); i++) { - Path existing = this.workspaces.get(i).getRootFolder().toPath(); + for(int i = 0; i < workspaces.size(); i++) { + Path existing = workspaces.get(i).getRootFolder().toPath(); if (newPath.startsWith(existing) || existing.startsWith(newPath)) { return true; } @@ -447,7 +443,7 @@ public File getRootFolder() { } public File get(FolderType folderType) { - return this.paths.get(folderType); + return paths.get(folderType); } private Map createFolderMap(File rootDir, boolean createDir) { @@ -470,15 +466,12 @@ private Map createFolderMap(File rootDir, boolean createDir) { @Override public boolean equals(Object obj) { - if (obj instanceof WorkspaceLayer) { - return this.rootFolder.equals(((WorkspaceLayer)obj).rootFolder); - } - return false; + return obj instanceof WorkspaceLayer && rootFolder.equals(((WorkspaceLayer)obj).rootFolder); } @Override public int hashCode() { - return this.rootFolder.hashCode(); + return rootFolder.hashCode(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/ResourceWorkspaceLayout.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/ResourceWorkspaceLayout.java index 1c966c3a..2f6388e5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/ResourceWorkspaceLayout.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/configuration/workspace/ResourceWorkspaceLayout.java @@ -27,7 +27,7 @@ public ResourceWorkspaceLayout(String rootPackage) { @Override public String getPath(File workspaceRoot, FolderType folderType) { - return this.resourceFile + '/' + getFolder(folderType); + return resourceFile + '/' + getFolder(folderType); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/DefaultMulticastDatagramSessionConfig.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/DefaultMulticastDatagramSessionConfig.java index fc42f53e..cb0a0ef5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/DefaultMulticastDatagramSessionConfig.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/DefaultMulticastDatagramSessionConfig.java @@ -20,7 +20,7 @@ public class DefaultMulticastDatagramSessionConfig extends DefaultDatagramSessionConfig { - private static int DEFAULT_SOTIMEOUT = 1000; + private static final int DEFAULT_SOTIMEOUT = 1000; private int soTimeout = DEFAULT_SOTIMEOUT; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastDatagramSessionConfig.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastDatagramSessionConfig.java index 167ce3b1..0894fdb8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastDatagramSessionConfig.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastDatagramSessionConfig.java @@ -186,7 +186,7 @@ public void setTrafficClass(int trafficClass) { public int getSoTimeout() { try { - return this.socket.getSoTimeout(); + return socket.getSoTimeout(); } catch (SocketException e) { throw new RuntimeIoException(e); } @@ -195,7 +195,7 @@ public int getSoTimeout() public void setSoTimeout(int soTimeout) { try { - this.socket.setSoTimeout(soTimeout); + socket.setSoTimeout(soTimeout); } catch (SocketException e) { throw new RuntimeIoException(e); } @@ -205,8 +205,9 @@ public void setSoTimeout(int soTimeout) { @Override protected void doSetAll(IoSessionConfig config) { - if ( config instanceof DefaultMulticastDatagramSessionConfig ) - setSoTimeout(((DefaultMulticastDatagramSessionConfig) config).getSoTimeout()); + if(config instanceof DefaultMulticastDatagramSessionConfig) { + setSoTimeout(((DefaultMulticastDatagramSessionConfig)config).getSoTimeout()); + } super.doSetAll(config); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketConnector.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketConnector.java index 8ea54e49..6f68d934 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketConnector.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketConnector.java @@ -38,7 +38,7 @@ public class MulticastSocketConnector extends AbstractIoConnector { // object used for checking session idle - private IdleStatusChecker idleChecker; + private final IdleStatusChecker idleChecker; private final IoProcessor processor; private final boolean createdProcessor; @@ -91,20 +91,17 @@ protected ConnectFuture connect0(SocketAddress remoteAddress, try { InetSocketAddress address = (InetSocketAddress)remoteAddress; - - if (SystemUtils.IS_OS_WINDOWS) { - socket = new MulticastSocket(address.getPort()); - } else { - socket = new MulticastSocket(address); - } - - if (networkInterface != null) - socket.setInterface(networkInterface.getInterfaceAddresses().get(0).getAddress()); + + socket = SystemUtils.IS_OS_WINDOWS ? new MulticastSocket(address.getPort()) : new MulticastSocket(address); + + if(networkInterface != null) { + socket.setInterface(networkInterface.getInterfaceAddresses().get(0).getAddress()); + } socket.joinGroup(address.getAddress()); ConnectFuture future = new DefaultConnectFuture(); - MulticastSocketSession session = new MulticastSocketSession(this, socket, this.processor); + MulticastSocketSession session = new MulticastSocketSession(this, socket, processor); session.getConfig().setAll(getSessionConfig()); initSession(session, future, sessionInitializer); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketProcessor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketProcessor.java index 1dd46415..4384125f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketProcessor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/connectivity/mina/net/MulticastSocketProcessor.java @@ -74,7 +74,7 @@ public class MulticastSocketProcessor implements IoProcessor options) throws Exception { - this.storageSettings.fillFromMap(options); + storageSettings.fillFromMap(options); this.serviceEnabled = BooleanUtils.toBoolean(options.get(getStoragePrefix() + "serviceEnabled")); this.testQuery = options.get(getStoragePrefix() + "testQuery"); } @Override public Map toMap() throws Exception { - Map result = this.storageSettings.toMap(); + Map result = storageSettings.toMap(); result.put(getStoragePrefix() + "serviceEnabled", Boolean.toString(serviceEnabled)); result.put(getStoragePrefix() + "testQuery", testQuery); return result; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/JsonEntityParser.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/JsonEntityParser.java index 13077854..4b8d5c3d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/JsonEntityParser.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/JsonEntityParser.java @@ -16,6 +16,17 @@ package com.exactpro.sf.embedded.machinelearning; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.ObjectUtils; + import com.exactpro.sf.configuration.IDictionaryManager; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.configuration.suri.SailfishURIException; @@ -32,16 +43,6 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.ObjectUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; public class JsonEntityParser { @@ -58,7 +59,7 @@ public static FailedAction parse(IDictionaryManager dictionaryManager, InputStre FailedAction failedAction = new FailedAction(); checkToken(parser, JsonToken.START_OBJECT, parser.nextToken()); Map rootFields = new HashMap<>(); - while (JsonToken.END_OBJECT != parser.nextToken()) { + while(parser.nextToken() != JsonToken.END_OBJECT) { switch (parser.getCurrentToken()) { case FIELD_NAME: if(!collectField(parser, rootFields, "expected", "actuals", "user")) { @@ -73,7 +74,7 @@ public static FailedAction parse(IDictionaryManager dictionaryManager, InputStre checkToken(parser, JsonToken.START_OBJECT, parser.getCurrentToken()); Map messageFields = new HashMap<>(); Message message = null; - while (JsonToken.END_OBJECT != parser.nextToken()) { + while(parser.nextToken() != JsonToken.END_OBJECT) { if (!collectField(parser, messageFields, JsonMessageConverter.JSON_MESSAGE)) { message = parseMessage(dictionaryManager, parser, messageFields, true); } @@ -85,7 +86,7 @@ public static FailedAction parse(IDictionaryManager dictionaryManager, InputStre messageParticipant.setId(participantId); } failedAction.addParticipant(messageParticipant); - } while (JsonToken.END_ARRAY != parser.nextToken()); + } while(parser.nextToken() != JsonToken.END_ARRAY); break; case "user": parser.nextToken(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/MachineLearningService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/MachineLearningService.java index 65d9ec55..8f31aaf5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/MachineLearningService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/MachineLearningService.java @@ -53,7 +53,7 @@ public class MachineLearningService implements IEmbeddedService { private BatchInsertWorker insertWorker; - private BlockingQueue batchInsertQueue = new LinkedBlockingQueue<>(); + private final BlockingQueue batchInsertQueue = new LinkedBlockingQueue<>(); private final ExecutorService exService = Executors.newSingleThreadExecutor(); private MLPredictor mlPredictor; @@ -86,7 +86,7 @@ public MLFileStorage getStorage() { @Override public boolean isConnected() { - return this.status.equals(ServiceStatus.Connected); + return status == ServiceStatus.Connected; } @Override @@ -117,18 +117,18 @@ private void setStatus(ServiceStatus status, String message) { public synchronized void tearDown() { logger.info("tearDown"); - if(this.status.equals(ServiceStatus.Disconnected)) { + if(status == ServiceStatus.Disconnected) { return; } - this.batchInsertQueue.clear(); + batchInsertQueue.clear(); - if(this.insertWorker != null) { - this.insertWorker.stop(); + if(insertWorker != null) { + insertWorker.stop(); this.insertWorker = null; } - if (this.storage != null) { + if(storage != null) { setStatus(ServiceStatus.Disconnected); } @@ -150,7 +150,7 @@ public synchronized void init() { } this.insertWorker = new BatchInsertWorker(); - Thread workerThread = new Thread(this.insertWorker, "Machine Learning insert worker"); + Thread workerThread = new Thread(insertWorker, "Machine Learning insert worker"); workerThread.setDaemon(true); workerThread.start(); @@ -160,19 +160,19 @@ public synchronized void init() { initPredictor(); - logger.info("{}", this.status); + logger.info("{}", status); } catch (Exception e) { logger.error(e.getMessage(), e); } } public void storeData(FailedAction fAction) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(status != ServiceStatus.Connected) { return; } try { - this.batchInsertQueue.put(fAction); + batchInsertQueue.put(fAction); } catch (InterruptedException e) { logger.error("Put interrupted", e); Thread.currentThread().interrupt(); @@ -245,7 +245,7 @@ public void stop() { public void run() { logger.info("Machine Learning InsertWorker started"); - while (this.running) { + while(running) { try { FailedAction fAction = batchInsertQueue.poll(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/EntryType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/EntryType.java index e807dd0f..43913733 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/EntryType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/EntryType.java @@ -19,5 +19,5 @@ public enum EntryType { SIMPLE, MESSAGE, SIMPLE_ARRAY, - MESSAGE_ARRAY; + MESSAGE_ARRAY } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/FailedAction.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/FailedAction.java index 18d88489..d80e3a80 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/FailedAction.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/FailedAction.java @@ -15,16 +15,30 @@ ******************************************************************************/ package com.exactpro.sf.embedded.machinelearning.entities; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + @JsonPropertyOrder({"id", "submittedAt", "submitter", "expectedMessage", "participants"}) @Entity @Table(name = "mlfailedaction") @@ -42,15 +56,17 @@ public class FailedAction implements Serializable { private Message expectedMessage; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinTable(name = "mlmessageparticipants", joinColumns = { - @JoinColumn(name = "failed_action_id", nullable = false, updatable = true) }, inverseJoinColumns = { - @JoinColumn(name = "message_participant_id", nullable = false, updatable = true) }) + @JoinTable( + name = "mlmessageparticipants", + joinColumns = @JoinColumn(name = "failed_action_id", nullable = false), + inverseJoinColumns = @JoinColumn(name = "message_participant_id", nullable = false) + ) private List participants; @Column(nullable = false) private long submittedAt; - @Column(nullable = true) + @Column private String submitter; public FailedAction() { @@ -61,11 +77,11 @@ public FailedAction() { public FailedAction(Message expectedMessage, MessageParticipant... messageParticipants) { this(); this.expectedMessage = expectedMessage; - this.participants.addAll(Arrays.asList(messageParticipants)); + participants.addAll(Arrays.asList(messageParticipants)); } public void addParticipant(MessageParticipant participant) { - this.participants.add(participant); + participants.add(participant); } public long getId() { @@ -111,9 +127,9 @@ public void setSubmitter(String user) { @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("id", this.id) - .append("expectedMessage", this.expectedMessage) - .append("participants", this.participants) + .append("id", id) + .append("expectedMessage", expectedMessage) + .append("participants", participants) .append("submittedAt", submittedAt) .append("submitter", submitter).toString(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/Message.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/Message.java index 49808372..62696f80 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/Message.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/Message.java @@ -15,16 +15,29 @@ ******************************************************************************/ package com.exactpro.sf.embedded.machinelearning.entities; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + @JsonPropertyOrder({"id", "type", "entries"}) @Entity @Table(name = "mlmessage") @@ -42,9 +55,11 @@ public class Message implements Serializable { private MessageType type; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinTable(name = "mlmessageentries", joinColumns = { - @JoinColumn(name = "parent_message_id", nullable = false, updatable = true) }, inverseJoinColumns = { - @JoinColumn(name = "entry_id", nullable = false, updatable = true) }) + @JoinTable( + name = "mlmessageentries", + joinColumns = @JoinColumn(name = "parent_message_id", nullable = false), + inverseJoinColumns = @JoinColumn(name = "entry_id", nullable = false) + ) private List entries; private boolean dirty; @@ -66,7 +81,7 @@ public Message(MessageType type, MessageEntry... entries) { } public void addEntry(MessageEntry entry) { - this.entries.add(entry); + entries.add(entry); } public long getId() { @@ -96,10 +111,10 @@ public void setEntries(List entries) { @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("id", this.id) - .append("dirty", this.dirty) - .append("type", this.type) - .append("entries", this.entries).toString(); + .append("id", id) + .append("dirty", dirty) + .append("type", type) + .append("entries", entries).toString(); } public boolean isDirty() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageEntry.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageEntry.java index 6e5b0ed6..4d199b84 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageEntry.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageEntry.java @@ -15,16 +15,32 @@ ******************************************************************************/ package com.exactpro.sf.embedded.machinelearning.entities; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import javax.persistence.*; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Objects; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + @JsonPropertyOrder({"id", "name", "type", "value", "message", "values", "messages"}) @Entity @Table(name = "mlmessageentry") @@ -46,23 +62,27 @@ public class MessageEntry implements Serializable { private String name; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinColumn(name = "simple_value_id", nullable = true) + @JoinColumn(name = "simple_value_id") private SimpleValue value; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinColumn(name = "message_id", nullable = true) + @JoinColumn(name = "message_id") private Message message; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinTable(name = "mlsimplearray", joinColumns = { - @JoinColumn(name = "entry_id", nullable = false, updatable = true) }, inverseJoinColumns = { - @JoinColumn(name = "simple_value_id", nullable = false, updatable = true) }) + @JoinTable( + name = "mlsimplearray", + joinColumns = @JoinColumn(name = "entry_id", nullable = false), + inverseJoinColumns = @JoinColumn(name = "simple_value_id", nullable = false) + ) private List values; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinTable(name = "mlmessagearray", joinColumns = { - @JoinColumn(name = "entry_id", nullable = false, updatable = true) }, inverseJoinColumns = { - @JoinColumn(name = "message_id", nullable = false, updatable = true) }) + @JoinTable( + name = "mlmessagearray", + joinColumns = @JoinColumn(name = "entry_id", nullable = false), + inverseJoinColumns = @JoinColumn(name = "message_id", nullable = false) + ) private List messages; public MessageEntry() { @@ -152,27 +172,27 @@ public void setName(String name) { @Override public String toString() { ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("id", this.id) - .append("type", this.type) - .append("name", this.name); - switch (this.type) { + .append("id", id) + .append("type", type) + .append("name", name); + switch(type) { case SIMPLE: - builder.append("value", this.value); + builder.append("value", value); break; case MESSAGE: - builder.append("message", this.message); + builder.append("message", message); break; case SIMPLE_ARRAY: - builder.append("values", this.values); + builder.append("values", values); break; case MESSAGE_ARRAY: - builder.append("messages", this.messages); + builder.append("messages", messages); break; default: - builder.append("value", this.value) - .append("message", this.message) - .append("values", this.values) - .append("messages", this.messages); + builder.append("value", value) + .append("message", message) + .append("values", values) + .append("messages", messages); break; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageParticipant.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageParticipant.java index e67c58ec..2b1707b9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageParticipant.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageParticipant.java @@ -15,12 +15,23 @@ ******************************************************************************/ package com.exactpro.sf.embedded.machinelearning.entities; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.io.Serializable; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import javax.persistence.*; -import java.io.Serializable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"id", "explanation", "message"}) @Entity @@ -75,8 +86,8 @@ public void setMessage(Message message) { @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("id", this.id) - .append("explanation", this.explanation) - .append("message", this.message).toString(); + .append("id", id) + .append("explanation", explanation) + .append("message", message).toString(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageType.java index 5fb54b6e..9d048e2a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/MessageType.java @@ -27,15 +27,16 @@ import javax.persistence.Table; import javax.persistence.UniqueConstraint; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + @JsonPropertyOrder({"id", "name", "dictionaryURI", "protocol"}) @Entity -@Table(name = "mlmessagetype", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "protocol", "dictionaryURI" }) }) +@Table(name = "mlmessagetype", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "protocol", "dictionaryURI" })) @SequenceGenerator(name = "mlmessagetype_generator", sequenceName = "mlmessagetype_sequence") public class MessageType implements Serializable { @@ -82,10 +83,10 @@ public String getProtocol() { @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("id", this.id) - .append("name", this.name) - .append("dictionaryURI", this.dictionaryURI) - .append("protocol", this.protocol).toString(); + .append("id", id) + .append("name", name) + .append("dictionaryURI", dictionaryURI) + .append("protocol", protocol).toString(); } @Override @@ -96,16 +97,16 @@ public boolean equals(Object o) { MessageType that = (MessageType)o; return new EqualsBuilder() - .append(this.name, that.name) - .append(this.dictionaryURI, that.dictionaryURI) - .append(this.protocol, that.protocol).isEquals(); + .append(name, that.name) + .append(dictionaryURI, that.dictionaryURI) + .append(protocol, that.protocol).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() - .append(this.name) - .append(this.dictionaryURI) - .append(this.protocol).toHashCode(); + .append(name) + .append(dictionaryURI) + .append(protocol).toHashCode(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/SimpleValue.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/SimpleValue.java index e2ed8981..41446fbe 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/SimpleValue.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/entities/SimpleValue.java @@ -25,10 +25,11 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + @JsonPropertyOrder({"id", "type", "value"}) @Entity @Table(name = "mlsimplevalue") @@ -81,8 +82,8 @@ public void setValue(String value) { @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("id", this.id) - .append("type", this.type) - .append("value", this.value).toString(); + .append("id", id) + .append("type", type) + .append("value", value).toString(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/storage/MLFileStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/storage/MLFileStorage.java index f3b534c9..89363f63 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/storage/MLFileStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/machinelearning/storage/MLFileStorage.java @@ -48,7 +48,7 @@ public class MLFileStorage { private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); - private ObjectWriter jsonWriter = new ObjectMapper().writer(); + private final ObjectWriter jsonWriter = new ObjectMapper().writer(); private final IWorkspaceDispatcher workspaceDispatcher; public MLFileStorage(IWorkspaceDispatcher workspaceDispatcher) throws IOException { @@ -85,7 +85,7 @@ public void zipDocumentsToStream(OutputStream target, int compressionLevel) thro public List getDocuments() throws FileNotFoundException { - Function supplier = (file) -> { + Function supplier = file -> { try { return workspaceDispatcher.getFile(FolderType.ML, file); } catch (FileNotFoundException e) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/EMailService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/EMailService.java index 2804cdef..a894722b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/EMailService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/EMailService.java @@ -73,7 +73,7 @@ public void tearDown() { public void send(String subject, String body, String htmlBody, List additionalRecipients, List attachments) { - if (!ServiceStatus.Connected.equals(this.status)) { + if(status != ServiceStatus.Connected) { logger.warn("EMail service in not the connected status. Please check its configurations"); return; } @@ -91,7 +91,7 @@ public void send(String subject, String body, String htmlBody, List recipients = setTransportSettings(mailer); if (attachments != null && !attachments.isEmpty()) { - for (final File attachment : attachments) { + for(File attachment : attachments) { if (attachment != null) { try { ((MultiPartEmail) mailer).attach(new Attachment(attachment.getName(), attachment), attachment.getName(), ""); @@ -132,18 +132,18 @@ public void send(String subject, String body, String htmlBody, public EMailServiceSettings getSettings() { try { - this.lock.readLock().lock(); + lock.readLock().lock(); return settings; } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @Override public void setSettings(IMapableSettings settings) { - this.lock.writeLock().lock(); + lock.writeLock().lock(); this.settings = (EMailServiceSettings) settings; - this.lock.writeLock().unlock(); + lock.writeLock().unlock(); } public void preCheckConnection() { @@ -176,7 +176,7 @@ public void checkConnection() { @Override public boolean isConnected(){ - return this.status.equals(ServiceStatus.Connected); + return status == ServiceStatus.Connected; } @Override @@ -192,7 +192,7 @@ public String getErrorMsg() { private List setTransportSettings(Email email) { try { - this.lock.readLock().lock(); + lock.readLock().lock(); email.setHostName(settings.getSmtpHost()); email.setSmtpPort(settings.getSmtpPort()); @@ -208,7 +208,7 @@ private List setTransportSettings(Email email) { logger.error("Cannot set the email settings", e); throw new EPSCommonException("Cannot set the email settings", e); } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/configuration/EMailServiceSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/configuration/EMailServiceSettings.java index 8193e947..192eb91f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/configuration/EMailServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/mail/configuration/EMailServiceSettings.java @@ -3,14 +3,15 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.Objects; import org.apache.commons.beanutils.BeanUtils; - -import com.exactpro.sf.storage.IMapableSettings; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; +import com.exactpro.sf.storage.IMapableSettings; + public class EMailServiceSettings implements IMapableSettings, Serializable { private static final long serialVersionUID = -2048992849401701406L; @@ -21,7 +22,7 @@ public class EMailServiceSettings implements IMapableSettings, Serializable { private String smtpHost = "smtp.example.com"; private Integer smtpPort = 25; - private boolean useSSL = false; + private boolean useSSL; private String username = "user@example.com"; private String password = "password"; private String recipients = "user1@example.com;user2@example.com"; @@ -51,7 +52,7 @@ public String settingsName() { @Override public void fillFromMap(Map options) throws Exception { - for(Map.Entry entry : options.entrySet()) { + for(Entry entry : options.entrySet()) { if(entry.getKey().startsWith(STORAGE_PREFIX)) { BeanUtils.setProperty(this, entry.getKey().replace(STORAGE_PREFIX, ""), entry.getValue()); } @@ -65,7 +66,7 @@ public Map toMap() throws Exception { Map description = BeanUtils.describe(this); Map result = new HashMap<>(); - for(Map.Entry entry : description.entrySet()) { + for(Entry entry : description.entrySet()) { result.put(STORAGE_PREFIX + entry.getKey(), entry.getValue()); } result.put(ENABLED_KEY, String.valueOf(serviceEnabled)); @@ -147,12 +148,12 @@ public boolean equals(Object o) { EMailServiceSettings that = (EMailServiceSettings) o; return Objects.equals(smtpHost, that.smtpHost) && Objects.equals(smtpPort, that.smtpPort) && - Objects.equals(useSSL, that.useSSL) && + useSSL == that.useSSL && Objects.equals(username, that.username) && Objects.equals(password, that.password) && Objects.equals(recipients, that.recipients) && Objects.equals(timeout, that.timeout) && - Objects.equals(serviceEnabled, that.serviceEnabled); + serviceEnabled == that.serviceEnabled; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/DimensionMap.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/DimensionMap.java index 8820b3d1..5bffaa0c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/DimensionMap.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/DimensionMap.java @@ -15,16 +15,16 @@ ******************************************************************************/ package com.exactpro.sf.embedded.statistics; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; - import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; + public class DimensionMap { - private Map> dimensions = new LinkedHashMap<>(); + private final Map> dimensions = new LinkedHashMap<>(); @JsonAnyGetter public Map> getDimensions() { @@ -33,7 +33,7 @@ public Map> getDimensions() { @JsonAnySetter public void setDimensions(String key, List value) { - this.dimensions.put(key, value); + dimensions.put(key, value); } public List getTagNames() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/MatrixInfo.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/MatrixInfo.java index b8771674..00dd755e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/MatrixInfo.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/MatrixInfo.java @@ -16,17 +16,18 @@ package com.exactpro.sf.embedded.statistics; -import com.exactpro.sf.embedded.statistics.entities.Tag; -import com.exactpro.sf.embedded.statistics.storage.AggregatedReportRow; -import com.exactpro.sf.scriptrunner.StatusType; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; +import com.exactpro.sf.embedded.statistics.entities.Tag; +import com.exactpro.sf.embedded.statistics.storage.AggregatedReportRow; +import com.exactpro.sf.scriptrunner.StatusType; + public class MatrixInfo { private final long allMatricesPassed; private final long allMatricesFailed; @@ -212,7 +213,7 @@ private static boolean isMatrixFailedRow(AggregatedReportRow row) { private static void separateTagsAndSetTestCasesToMatrixRows(Map> testCaseRunRows, Map matrixRows) { - for (Map.Entry> testCaseRunEntry : testCaseRunRows.entrySet()) { + for(Entry> testCaseRunEntry : testCaseRunRows.entrySet()) { List testCaseRows = testCaseRunEntry.getValue(); if (!testCaseRows.isEmpty()) { Set matrixTags = new HashSet<>(); @@ -229,7 +230,9 @@ private static void separateTagsAndSetTestCasesToMatrixRows(Map tag.setForAllTestCaseRuns(true)); + for(Tag tag : matrixTags) { + tag.setForAllTestCaseRuns(true); + } AggregatedReportRow matrixRow = matrixRows.get(testCaseRunEntry.getKey()); matrixRow.setTags(new ArrayList<>(allTags)); for (AggregatedReportRow testCaseRow : testCaseRows) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsException.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsException.java index e8424407..69729d97 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsException.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsException.java @@ -16,7 +16,7 @@ package com.exactpro.sf.embedded.statistics; public class StatisticsException extends RuntimeException { - private String summary; + private final String summary; public StatisticsException(String summary, String message) { super(message); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsFlywayWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsFlywayWrapper.java index 810a38d2..687add31 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsFlywayWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsFlywayWrapper.java @@ -16,22 +16,23 @@ package com.exactpro.sf.embedded.statistics; -import com.exactpro.sf.embedded.statistics.configuration.DbmsType; -import com.exactpro.sf.embedded.statistics.storage.NewerSchemaException; -import com.exactpro.sf.embedded.statistics.storage.OlderSchemaException; -import com.exactpro.sf.embedded.storage.HibernateStorageSettings; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationInfo; import org.flywaydb.core.api.MigrationInfoService; import org.flywaydb.core.api.MigrationState; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; +import com.exactpro.sf.embedded.statistics.configuration.DbmsType; +import com.exactpro.sf.embedded.statistics.storage.NewerSchemaException; +import com.exactpro.sf.embedded.statistics.storage.OlderSchemaException; +import com.exactpro.sf.embedded.storage.HibernateStorageSettings; public class StatisticsFlywayWrapper { - private final static String PSQL_SCRIPT_LOCATION = "com/exactpro/sf/statistics/storage/pg/migration"; - private final static String MYSQL_SCRIPT_LOCATION = "com/exactpro/sf/statistics/storage/mysql/migration"; - private final static String[] MYSQL_INIT_SQL = new String[] { "SET default_storage_engine=InnoDB;" }; + private static final String PSQL_SCRIPT_LOCATION = "com/exactpro/sf/statistics/storage/pg/migration"; + private static final String MYSQL_SCRIPT_LOCATION = "com/exactpro/sf/statistics/storage/mysql/migration"; + private static final String[] MYSQL_INIT_SQL = { "SET default_storage_engine=InnoDB;" }; private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); @@ -102,7 +103,7 @@ public void init(HibernateStorageSettings settings) { if (all.length != 0) { MigrationInfo lastKnown = all[all.length - 1]; - if (lastKnown.getState().equals(MigrationState.FUTURE_SUCCESS)) { + if(lastKnown.getState() == MigrationState.FUTURE_SUCCESS) { sfUpdateRequired = true; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsMigration.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsMigration.java index 3a510878..0b153353 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsMigration.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsMigration.java @@ -20,6 +20,7 @@ import java.io.InputStream; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import com.exactpro.sf.embedded.statistics.configuration.DbmsType; @@ -29,9 +30,9 @@ public class StatisticsMigration { - private final static String CHECK_MODE = "check"; - private final static String MIGRATE_MODE = "migrate"; - private final static int NEED_MIGRATION_CODE = 7; + private static final String CHECK_MODE = "check"; + private static final String MIGRATE_MODE = "migrate"; + private static final int NEED_MIGRATION_CODE = 7; public static void main(String[] args) { try { @@ -53,7 +54,7 @@ public static void main(String[] args) { } Map settingsMap = new HashMap<>(); - for (Map.Entry prop : properties.entrySet()) { + for (Entry prop : properties.entrySet()) { settingsMap.put(prop.getKey().toString(), prop.getValue().toString()); } StatisticsServiceSettings settings = new StatisticsServiceSettings(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsService.java index 75fa486b..1e83950d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsService.java @@ -15,6 +15,7 @@ *******************************************************************************/ package com.exactpro.sf.embedded.statistics; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -26,32 +27,29 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.function.BiFunction; -import com.exactpro.sf.comparison.ComparisonResult; -import com.exactpro.sf.comparison.ComparisonUtil; -import com.exactpro.sf.embedded.statistics.configuration.DbmsType; -import com.exactpro.sf.embedded.statistics.entities.TagGroup; -import com.exactpro.sf.embedded.statistics.handlers.StatisticsReportHandlerLoader; -import com.exactpro.sf.embedded.statistics.storage.AggregatedReportRow; -import com.exactpro.sf.util.DateTimeUtility; - -import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.flywaydb.core.api.MigrationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.center.impl.SFLocalContext; +import com.exactpro.sf.common.util.EPSCommonException; +import com.exactpro.sf.comparison.ComparisonResult; +import com.exactpro.sf.comparison.ComparisonUtil; import com.exactpro.sf.embedded.IEmbeddedService; import com.exactpro.sf.embedded.configuration.ServiceStatus; +import com.exactpro.sf.embedded.statistics.configuration.DbmsType; import com.exactpro.sf.embedded.statistics.configuration.StatisticsServiceSettings; import com.exactpro.sf.embedded.statistics.entities.ActionRun; import com.exactpro.sf.embedded.statistics.entities.MatrixRun; import com.exactpro.sf.embedded.statistics.entities.SfInstance; import com.exactpro.sf.embedded.statistics.entities.Tag; +import com.exactpro.sf.embedded.statistics.entities.TagGroup; import com.exactpro.sf.embedded.statistics.entities.TestCase; import com.exactpro.sf.embedded.statistics.entities.TestCaseRun; +import com.exactpro.sf.embedded.statistics.handlers.StatisticsReportHandlerLoader; +import com.exactpro.sf.embedded.statistics.storage.AggregatedReportRow; import com.exactpro.sf.embedded.statistics.storage.IStatisticsStorage; import com.exactpro.sf.embedded.statistics.storage.StatisticsReportingStorage; import com.exactpro.sf.embedded.statistics.storage.StatisticsStorage; @@ -60,7 +58,8 @@ import com.exactpro.sf.scriptrunner.TestScriptDescription; import com.exactpro.sf.storage.IMapableSettings; import com.exactpro.sf.util.BugDescription; -import java.time.LocalDateTime; +import com.exactpro.sf.util.DateTimeUtility; +import com.google.common.collect.Sets; public class StatisticsService extends StatisticsReportHandlerLoader implements IEmbeddedService{ @@ -89,7 +88,7 @@ public class StatisticsService extends StatisticsReportHandlerLoader implements private volatile String errorMsg = ""; - private BlockingQueue batchInsertQueue = new LinkedBlockingQueue<>(); + private final BlockingQueue batchInsertQueue = new LinkedBlockingQueue<>(); private IStatisticsStorage storage; @@ -97,7 +96,7 @@ public class StatisticsService extends StatisticsReportHandlerLoader implements private final StatisticsFlywayWrapper statisticsFlywayWrapper = new StatisticsFlywayWrapper(); - private volatile boolean exceptionEncountered = false; + private volatile boolean exceptionEncountered; private final Map tagCache = new LinkedHashMap(CACHE_SIZE, CACHE_LOAD_FACTOR, true) { @Override @@ -112,9 +111,9 @@ protected boolean removeEldestEntry(Map.Entry eldest) { private void initStorage(HibernateStorageSettings storageSettings) { - if(this.storage != null) { + if(storage != null) { - this.storage.tearDown(); + storage.tearDown(); } @@ -153,7 +152,7 @@ public synchronized void migrateDB() { private void openMatrixRun(MatrixRun matrixRun, long scriptDescriptionId) { - this.storage.add(matrixRun); + storage.add(matrixRun); TestScriptDescription testScriptRun = SFLocalContext.getDefault().getScriptRunner().getTestScriptDescription(scriptDescriptionId); if (testScriptRun == null) { throw new EPSCommonException(String.format("TestScriptDescription with [%s] id is missed", scriptDescriptionId)); @@ -165,7 +164,7 @@ private void openMatrixRun(MatrixRun matrixRun, long scriptDescriptionId) { @Override public boolean isConnected() { - return this.status.equals(ServiceStatus.Connected); + return status == ServiceStatus.Connected; } @@ -184,7 +183,7 @@ public synchronized void init() { logger.info("init"); - if(this.status.equals(ServiceStatus.Connected) && settings.isServiceEnabled()) { + if(status == ServiceStatus.Connected && settings.isServiceEnabled()) { throw new IllegalStateException("Already enabled"); @@ -205,18 +204,18 @@ public synchronized void init() { throw t; } - initStorage(this.settings.getStorageSettings()); + initStorage(settings.getStorageSettings()); - this.thisSfInstance = this.storage.loadSfInstance(this.settings.getThisSfHost(), - this.settings.getThisSfPort(), - this.settings.getThisSfName()); + this.thisSfInstance = storage.loadSfInstance(settings.getThisSfHost(), + settings.getThisSfPort(), + settings.getThisSfName()); - this.unknownTc = this.storage.loadUnknownTestCase(); + this.unknownTc = storage.loadUnknownTestCase(); // Insert worker thread this.insertWorker = new BatchInsertWorker(); - Thread workerThread = new Thread(this.insertWorker, "Statistics insert worker"); + Thread workerThread = new Thread(insertWorker, "Statistics insert worker"); workerThread.setDaemon(true); @@ -225,7 +224,7 @@ public synchronized void init() { // Schema checker thread this.schemaChecker = new SchemaVersionChecker(); - Thread checkerThread = new Thread(this.schemaChecker, "Statistics schema checker"); + Thread checkerThread = new Thread(schemaChecker, "Statistics schema checker"); checkerThread.setDaemon(true); @@ -247,7 +246,7 @@ public synchronized void init() { } - logger.info("{}", this.status); + logger.info("{}", status); } @@ -256,25 +255,25 @@ public synchronized void tearDown() { logger.info("tearDown"); - if(this.status.equals(ServiceStatus.Disconnected)) { + if(status == ServiceStatus.Disconnected) { return; } - this.batchInsertQueue.clear(); + batchInsertQueue.clear(); - if(this.insertWorker != null) { + if(insertWorker != null) { - this.insertWorker.stop(); + insertWorker.stop(); this.insertWorker = null; } - if(this.schemaChecker != null) { + if(schemaChecker != null) { - this.schemaChecker.stop(); + schemaChecker.stop(); this.schemaChecker = null; @@ -282,9 +281,9 @@ public synchronized void tearDown() { } - if(this.storage != null) { + if(storage != null) { - this.storage.tearDown(); + storage.tearDown(); this.storage = null; @@ -294,9 +293,9 @@ public synchronized void tearDown() { } - this.runningActions.clear(); - this.runningMatrices.clear(); - this.runningTestCases.clear(); + runningActions.clear(); + runningMatrices.clear(); + runningTestCases.clear(); logger.info("Statistics service disposed"); @@ -305,7 +304,7 @@ public synchronized void tearDown() { public synchronized void matrixStarted(String matrixName, String reportFolder, long sfRunId, String environmentName, String userName, List tags, long scriptDescriptionId) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(status != ServiceStatus.Connected) { return; } @@ -316,10 +315,10 @@ public synchronized void matrixStarted(String matrixName, String reportFolder, MatrixRun matrixRun = new MatrixRun(); matrixRun.setStartTime(DateTimeUtility.nowLocalDateTime()); matrixRun.setSfInstance(thisSfInstance); - matrixRun.setMatrix(this.storage.loadMatrix(matrixName)); + matrixRun.setMatrix(storage.loadMatrix(matrixName)); matrixRun.setSfRunId(sfRunId); - matrixRun.setEnvironment(this.storage.getEnvironmentEntity(environmentName)); - matrixRun.setUser(this.storage.getUserEntity(userName)); + matrixRun.setEnvironment(storage.getEnvironmentEntity(environmentName)); + matrixRun.setUser(storage.getUserEntity(userName)); matrixRun.setReportFolder(reportFolder); if(tags != null) { matrixRun.setTags(new HashSet<>(tags)); @@ -327,7 +326,7 @@ public synchronized void matrixStarted(String matrixName, String reportFolder, openMatrixRun(matrixRun, scriptDescriptionId); - this.runningMatrices.put(matrixName, matrixRun); + runningMatrices.put(matrixName, matrixRun); } catch(Exception e) { @@ -341,7 +340,7 @@ public synchronized void matrixStarted(String matrixName, String reportFolder, public void matrixEception(String matrixName, Throwable cause) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(status != ServiceStatus.Connected) { return; } @@ -349,7 +348,7 @@ public void matrixEception(String matrixName, Throwable cause) { logger.debug("Matrix {} init/run exception", matrixName); - MatrixRun matrixRun = this.runningMatrices.get(matrixName); + MatrixRun matrixRun = runningMatrices.get(matrixName); if(matrixRun == null) { @@ -361,7 +360,7 @@ public void matrixEception(String matrixName, Throwable cause) { matrixRun.setFailReason(cause.getMessage()); - this.storage.update(matrixRun); + storage.update(matrixRun); } catch(Throwable t) { @@ -375,7 +374,7 @@ public void matrixEception(String matrixName, Throwable cause) { public void matrixFinished(String matrixName) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(status != ServiceStatus.Connected) { return; } @@ -391,7 +390,7 @@ public void matrixFinished(String matrixName) { } - MatrixRun matrixRun = this.runningMatrices.remove(matrixName); + MatrixRun matrixRun = runningMatrices.remove(matrixName); if(matrixRun == null) { @@ -403,7 +402,7 @@ public void matrixFinished(String matrixName) { matrixRun.setFinishTime(DateTimeUtility.nowLocalDateTime()); - this.storage.update(matrixRun); + storage.update(matrixRun); } catch(Throwable t) { @@ -418,7 +417,7 @@ public void matrixFinished(String matrixName) { public synchronized void testCaseStarted(String matrixName, String tcId, String reportFile, String description, long rank, int tcHash, Set tags) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(status != ServiceStatus.Connected) { return; } @@ -435,26 +434,17 @@ public synchronized void testCaseStarted(String matrixName, String tcId, String tcRun.setFinishTime(now); tcRun.setRank(rank); tcRun.setHash(tcHash); - - if(tcId != null) { - - tcRun.setTestCase(this.storage.loadTestCase(tcId)); - - } else { - - tcRun.setTestCase(this.unknownTc); - - } + tcRun.setTestCase(tcId != null ? storage.loadTestCase(tcId) : unknownTc); if (tags != null && !tags.isEmpty()) { tcRun.addTags(loadTags(tags), false); } - tcRun.setMatrixRun(this.runningMatrices.get(matrixName)); + tcRun.setMatrixRun(runningMatrices.get(matrixName)); - this.storage.add(tcRun); + storage.add(tcRun); - this.runningTestCases.put(matrixName, tcRun); + runningTestCases.put(matrixName, tcRun); } catch(Throwable t) { @@ -468,7 +458,7 @@ public synchronized void testCaseStarted(String matrixName, String tcId, String public void testCaseFinished(String matrixName, StatusType status, String failReason, Set knownBugs) { // status, description - if(!this.status.equals(ServiceStatus.Connected)) { + if(this.status != ServiceStatus.Connected) { return; } @@ -476,7 +466,7 @@ public void testCaseFinished(String matrixName, StatusType status, String failRe logger.debug("TC finished {}, {}, {}, {}", matrixName, status); - TestCaseRun tcRun = this.runningTestCases.remove(matrixName); + TestCaseRun tcRun = runningTestCases.remove(matrixName); if(tcRun == null) { @@ -495,7 +485,7 @@ public void testCaseFinished(String matrixName, StatusType status, String failRe tcRun.setComment(String.format("Known bugs: [%s]", StringUtils.join(knownBugs, ", "))); } - this.storage.update(tcRun); + storage.update(tcRun); } catch(Throwable t) { @@ -510,7 +500,7 @@ public void testCaseFinished(String matrixName, StatusType status, String failRe public void actionStarted(String matrixName, String serviceName, String actionName, String msgType, String description, long rank, String tag, int hash) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(status != ServiceStatus.Connected) { return; } @@ -522,7 +512,7 @@ public void actionStarted(String matrixName, String serviceName, String actionNa actionRun.setRank(rank); - actionRun.setTcRun(this.runningTestCases.get(matrixName)); + actionRun.setTcRun(runningTestCases.get(matrixName)); actionRun.setTag(tag); @@ -530,18 +520,18 @@ public void actionStarted(String matrixName, String serviceName, String actionNa ActionRunSaveTask saveTask = new ActionRunSaveTask(actionRun, serviceName, msgType, actionName); - this.runningActions.put(matrixName, saveTask); + runningActions.put(matrixName, saveTask); } public void actionFinished(String matrixName, StatusType status, String failReason) { - if(!this.status.equals(ServiceStatus.Connected)) { + if(this.status != ServiceStatus.Connected) { return; } try { - ActionRunSaveTask task = this.runningActions.remove(matrixName); + ActionRunSaveTask task = runningActions.remove(matrixName); if(task == null) { logger.error("Unknown action finished! {}, {}, {}", matrixName, status, failReason); @@ -553,7 +543,7 @@ public void actionFinished(String matrixName, StatusType status, String failReas task.getActionRun().setStatus(status); task.getActionRun().setFailReason(failReason); - this.batchInsertQueue.put(task); + batchInsertQueue.put(task); } catch (InterruptedException e) { logger.error("Put interrupted", e); @@ -570,7 +560,7 @@ public void addKnownBugsToActionRun(String matrixName, ComparisonResult result) if (!allKnownBugs.isEmpty()) { Set reproducedBugs = result.getReproducedBugs(); Set noReproducedBugs = Sets.difference(allKnownBugs, reproducedBugs); - ActionRunSaveTask actionRunSaveTask = this.runningActions.get(matrixName); + ActionRunSaveTask actionRunSaveTask = runningActions.get(matrixName); if (actionRunSaveTask == null) { logger.error("Unknown action create verification! {}, {}", matrixName, result); return; @@ -609,22 +599,22 @@ public String getErrorMsg() { } public StatisticsReportingStorage getReportingStorage() { - return this.storage.getReportingStorage(); + return storage.getReportingStorage(); } private class ActionRunSaveTask { - private ActionRun actionRun; + private final ActionRun actionRun; - private String service; + private final String service; - private String msgType; + private final String msgType; - private String action; + private final String action; - private Set reproducedKnownBugs = new HashSet<>(); + private final Set reproducedKnownBugs = new HashSet<>(); - private Set noReproducedKnownBugs = new HashSet<>(); + private final Set noReproducedKnownBugs = new HashSet<>(); public ActionRunSaveTask(ActionRun actionRun, String service, String msgType, String action) { @@ -676,7 +666,7 @@ public void run() { logger.info("Statistics InsertWorker started"); - while(this.running) { + while(running) { try { @@ -837,20 +827,20 @@ private void manageTagToRows(List rows, BiFunction loadTags(Set tagNames) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java index 124819ad..57c5c08b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/StatisticsUtils.java @@ -29,6 +29,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; @@ -126,7 +127,7 @@ public static List generateTagGroupReportResults(Statistic } public static void writeTagGroupReportToCsv(OutputStream outputStream, List results) throws IOException { - String[] header = new String[] { + String[] header = { "Tag", "Total Execution Time", "Total Test Cases", @@ -273,7 +274,7 @@ public static void writeScriptRunsHistory(ISFContext context, OutputStream out, AggregateReportParameters parameters = new AggregateReportParameters(); parameters.setTestCaseRunIds(new ArrayList<>(testCasesToLoad.keySet())); Map> testCasesKnownBugs = context.getStatisticsService().getReportingStorage().generateTestCasesKnownBugsReports(parameters); - for (Map.Entry> entry : testCasesKnownBugs.entrySet()) { + for(Entry> entry : testCasesKnownBugs.entrySet()) { AggregatedReportRow row = testCasesToLoad.get(entry.getKey()); row.setCategorisedKnownBugs(groupKnownBugsByCategory(entry.getValue())); } @@ -319,7 +320,7 @@ public static void writeScriptRunsHistory(ISFContext context, OutputStream out, columns.add(index + 1, "Passed"); } - String header[] = columns.toArray(new String[columns.size()]); + String[] header = columns.toArray(new String[columns.size()]); writeRowsToCsv(writer, header, taggedActions, rowsToWrite, exportWithTCsInfo, exportWithActionsInfo, info); @@ -418,17 +419,10 @@ private static void writeRowsToCsv(CsvWriter writer, String[] headers, Map infoRows = taggedActions.get(row.getTestCaseRunId()); - - if (infoRows != null) { - toWrite = getActionDescriptionsByTag(infoRows, tag); - } else { - toWrite = ""; - } + toWrite = infoRows != null ? getActionDescriptionsByTag(infoRows, tag) : ""; } - } else if (headers[i].equals("Message Type")) { - toWrite = ""; } else { - toWrite = row.get(headers[i], ""); + toWrite = "Message Type".equals(headers[i]) ? "" : row.get(headers[i], ""); } } @@ -440,7 +434,7 @@ private static void writeRowsToCsv(CsvWriter writer, String[] headers, Map ca || (entry.getNonReproducedBugs().isEmpty() && !reproduced)) { continue; } - if (StringUtils.isBlank(entry.getCategoryString())) { - cellText.append("No category"); - } else { - cellText.append(entry.getCategoryString()); - } + cellText.append(StringUtils.defaultIfBlank(entry.getCategoryString(), "No category")); cellText.append(categoryDelimiter); - if (reproduced) { - cellText.append(entry.getReproducedBugsString()); - } else { - cellText.append(entry.getNonReproducedBugsString()); - } + cellText.append(reproduced ? entry.getReproducedBugsString() : entry.getNonReproducedBugsString()); cellText.append("\n"); } return cellText.toString().trim(); @@ -520,12 +506,9 @@ private static String extractMatrixStatus(AggregatedReportRow row) { if (row.getMatrixFailReason() != null || row.getFailedCount() > 0) { return StatusType.FAILED.name(); - } else if (row.getConditionallyPassedCount() > 0) { - return StatusType.CONDITIONALLY_PASSED.name(); - } else { - return StatusType.PASSED.name(); } + return row.getConditionallyPassedCount() > 0 ? StatusType.CONDITIONALLY_PASSED.name() : StatusType.PASSED.name(); } private static String getActionDescriptionsByTag(List infoRows, String tag) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/DbmsType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/DbmsType.java index 9e73631f..0e816d4f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/DbmsType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/DbmsType.java @@ -38,7 +38,7 @@ public void setDbmsSettings(HibernateStorageSettings hibSettings) { private final String value; - private DbmsType(final String value) { + DbmsType(String value) { this.value = value; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/StatisticsServiceSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/StatisticsServiceSettings.java index da5b2c19..2bc05083 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/StatisticsServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/configuration/StatisticsServiceSettings.java @@ -15,8 +15,6 @@ ******************************************************************************/ package com.exactpro.sf.embedded.statistics.configuration; -import java.util.Map; - import com.exactpro.sf.embedded.configuration.AbstractHibernateServiceSettings; import com.exactpro.sf.embedded.storage.HibernateStorageSettings; @@ -96,7 +94,7 @@ public String toString() { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + (serviceEnabled ? 1231 : 1237); result = prime * result @@ -112,35 +110,47 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } StatisticsServiceSettings other = (StatisticsServiceSettings) obj; - if (serviceEnabled != other.serviceEnabled) - return false; + if(serviceEnabled != other.serviceEnabled) { + return false; + } if (storageSettings == null) { - if (other.storageSettings != null) - return false; - } else if (!storageSettings.equals(other.storageSettings)) - return false; + if(other.storageSettings != null) { + return false; + } + } else if(!storageSettings.equals(other.storageSettings)) { + return false; + } if (thisSfHost == null) { - if (other.thisSfHost != null) - return false; - } else if (!thisSfHost.equals(other.thisSfHost)) - return false; + if(other.thisSfHost != null) { + return false; + } + } else if(!thisSfHost.equals(other.thisSfHost)) { + return false; + } if (thisSfName == null) { - if (other.thisSfName != null) - return false; - } else if (!thisSfName.equals(other.thisSfName)) - return false; + if(other.thisSfName != null) { + return false; + } + } else if(!thisSfName.equals(other.thisSfName)) { + return false; + } if (thisSfPort == null) { - if (other.thisSfPort != null) - return false; - } else if (!thisSfPort.equals(other.thisSfPort)) - return false; + if(other.thisSfPort != null) { + return false; + } + } else if(!thisSfPort.equals(other.thisSfPort)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Action.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Action.java index 8bb670c8..5f78de22 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Action.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Action.java @@ -24,8 +24,7 @@ import javax.persistence.UniqueConstraint; @Entity -@Table(name="stactions", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "stactions", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="stactions_generator", sequenceName="stactions_sequence") public class Action { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRun.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRun.java index 04449f3d..bd5c9f8f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRun.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRun.java @@ -47,12 +47,12 @@ public class ActionRun { @GeneratedValue(strategy=GenerationType.AUTO, generator="stactionruns_generator") private Long id; - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "255")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "255")) private String description; private int status; - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "255")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "255")) private String failReason; private long rank; @@ -75,7 +75,7 @@ public class ActionRun { private MessageType msgType; @Column(name = "tag", nullable = true) - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "255")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "255")) private String tag; @OneToMany(mappedBy = "id.actionRun", cascade = CascadeType.ALL) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRunKnownBug.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRunKnownBug.java index 0dc2cad2..9ce9817a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRunKnownBug.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/ActionRunKnownBug.java @@ -34,7 +34,7 @@ public class ActionRunKnownBug { @EmbeddedId - private ActionRunKnownBugId id = new ActionRunKnownBugId(); + private final ActionRunKnownBugId id = new ActionRunKnownBugId(); private Boolean reproduced; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Environment.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Environment.java index 576edbf5..7dcace28 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Environment.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Environment.java @@ -24,8 +24,7 @@ import javax.persistence.UniqueConstraint; @Entity -@Table(name="stenvironments", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "stenvironments", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="stenvironments_generator", sequenceName="stenvironments_sequence") public class Environment { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/KnownBug.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/KnownBug.java index be8a30c3..11a0a366 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/KnownBug.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/KnownBug.java @@ -25,7 +25,6 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import javax.persistence.UniqueConstraint; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; @@ -45,7 +44,7 @@ public class KnownBug { * {@code ["Subject"]}
* {@code ["Category1","Subject"]}
*/ - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "255")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "255")) @Column(name = "known_bug", unique = true) private String knownBug; @@ -67,8 +66,12 @@ public void setKnownBug(String knownBug) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(this == o) { + return true; + } + if(o == null || getClass() != o.getClass()) { + return false; + } KnownBug knownBug1 = (KnownBug) o; return Objects.equals(knownBug, knownBug1.knownBug); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Matrix.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Matrix.java index ea36fda6..0840560b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Matrix.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Matrix.java @@ -24,8 +24,7 @@ import javax.persistence.UniqueConstraint; @Entity -@Table(name="stmatrices", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "stmatrices", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="stmatrices_generator", sequenceName="stmatrices_sequence") public class Matrix { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MatrixRun.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MatrixRun.java index 1a6f993f..42f03eb0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MatrixRun.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MatrixRun.java @@ -40,7 +40,7 @@ public class MatrixRun { private long sfRunId; - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "16384")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "16384")) private String failReason; private String reportFolder; @@ -66,10 +66,8 @@ public class MatrixRun { private Environment environment; @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinTable(name = "stmrtags", joinColumns = { - @JoinColumn(name = "mr_id", nullable = false, updatable = true) }, - inverseJoinColumns = { @JoinColumn(name = "tag_id", - nullable = false, updatable = true) }) + @JoinTable(name = "stmrtags", joinColumns = @JoinColumn(name = "mr_id", nullable = false, updatable = true), inverseJoinColumns = @JoinColumn(name = "tag_id", + nullable = false, updatable = true)) private Set tags; public Set getTags() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MessageType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MessageType.java index 9235febc..3510df4a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MessageType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/MessageType.java @@ -24,8 +24,7 @@ import javax.persistence.UniqueConstraint; @Entity -@Table(name="stmessagetypes", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "stmessagetypes", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="stmessagetypes_generator", sequenceName="stmessagetypes_sequence") public class MessageType { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Service.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Service.java index 78e324f6..38a96b0a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Service.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Service.java @@ -24,8 +24,7 @@ import javax.persistence.UniqueConstraint; @Entity -@Table(name="stservices", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "stservices", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="stservices_generator", sequenceName="stservices_sequence") public class Service { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/SfInstance.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/SfInstance.java index 7f1ecf43..bce4b8a2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/SfInstance.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/SfInstance.java @@ -27,8 +27,7 @@ @SuppressWarnings("serial") @Entity -@Table(name="stsfinstances", -uniqueConstraints = {@UniqueConstraint(columnNames={"host", "port", "name"})}) +@Table(name = "stsfinstances", uniqueConstraints = @UniqueConstraint(columnNames = { "host", "port", "name" })) @SequenceGenerator(name="stsf_generator", sequenceName="stsf_sequence") public class SfInstance implements Serializable { @@ -91,7 +90,7 @@ public String toString() { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; @@ -99,18 +98,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } SfInstance other = (SfInstance) obj; if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Tag.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Tag.java index e17d36c6..79dfb4c5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Tag.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/Tag.java @@ -36,8 +36,7 @@ @SuppressWarnings("serial") @Entity -@Table(name="sttags", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "sttags", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="sttags_generator", sequenceName="sttags_sequence") public class Tag implements Serializable { @@ -113,7 +112,7 @@ public void setForAllTestCaseRuns(boolean forAllTestCaseRuns) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; @@ -121,18 +120,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } Tag other = (Tag) obj; if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TagGroup.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TagGroup.java index 7b4dc355..3012e312 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TagGroup.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TagGroup.java @@ -32,8 +32,7 @@ @SuppressWarnings("serial") @Entity -@Table(name="sttaggroups", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "sttaggroups", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="sttaggroups_generator", sequenceName="sttaggroups_sequence") public class TagGroup implements Serializable { @@ -65,7 +64,7 @@ public void setName(String name) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; @@ -73,18 +72,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } TagGroup other = (TagGroup) obj; if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCase.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCase.java index c2003f31..5f24ba3f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCase.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCase.java @@ -27,8 +27,7 @@ @SuppressWarnings("serial") @Entity -@Table(name="sttestcases", -uniqueConstraints = {@UniqueConstraint(columnNames={"testCaseId"})}) +@Table(name = "sttestcases", uniqueConstraints = @UniqueConstraint(columnNames = "testCaseId")) @SequenceGenerator(name="sttestcases_generator", sequenceName="sttestcases_sequence") public class TestCase implements Serializable { @@ -56,7 +55,7 @@ public void setTestCaseId(String testCaseId) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; @@ -64,18 +63,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } TestCase other = (TestCase) obj; if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRun.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRun.java index 22fc3ea0..166c68ba 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRun.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRun.java @@ -15,6 +15,12 @@ ******************************************************************************/ package com.exactpro.sf.embedded.statistics.entities; +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + import javax.persistence.CascadeType; import javax.persistence.Convert; import javax.persistence.Entity; @@ -28,21 +34,13 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import com.exactpro.sf.statistics.LocalDateTimeDBConverter; -import org.apache.commons.lang3.BooleanUtils; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import com.exactpro.sf.scriptrunner.StatusType; -import java.time.LocalDateTime; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.Set; +import com.exactpro.sf.statistics.LocalDateTimeDBConverter; @Entity @Table(name="sttestcaseruns") @@ -53,7 +51,7 @@ public class TestCaseRun { @GeneratedValue(strategy=GenerationType.AUTO, generator="sttestcaseruns_generator") private Long id; - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "255")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "255")) private String description; @Convert(converter = LocalDateTimeDBConverter.class) @@ -64,14 +62,14 @@ public class TestCaseRun { private int status; - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "255")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "255")) private String failReason; private long rank; private String reportFile; - @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = {@Parameter(name = "length", value = "1024")}) + @Type(type = "com.exactpro.sf.storage.TruncatedString", parameters = @Parameter(name = "length", value = "1024")) private String comment; private String fixRevision; @@ -239,8 +237,12 @@ public void setTags(Set tags) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(this == o) { + return true; + } + if(o == null || getClass() != o.getClass()) { + return false; + } TestCaseRun that = (TestCaseRun) o; return Objects.equals(id, that.id); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunStatus.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunStatus.java index 8ee79db6..87a23341 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunStatus.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunStatus.java @@ -27,8 +27,7 @@ @SuppressWarnings("serial") @Entity -@Table(name="sttcrstatus", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "sttcrstatus", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="sttcrstatus_generator", sequenceName="sttcrstatus_sequence") public class TestCaseRunStatus implements Serializable { @@ -56,7 +55,7 @@ public void setName(String name) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; @@ -64,18 +63,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } TestCaseRunStatus other = (TestCaseRunStatus) obj; if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTag.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTag.java index 5e17639e..288af9eb 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTag.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTag.java @@ -15,6 +15,9 @@ ******************************************************************************/ package com.exactpro.sf.embedded.statistics.entities; +import java.io.Serializable; +import java.util.Objects; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -22,8 +25,6 @@ import javax.persistence.ManyToOne; import javax.persistence.MapsId; import javax.persistence.Table; -import java.io.Serializable; -import java.util.Objects; @Entity @Table(name = "sttcrtags") @@ -86,8 +87,12 @@ public void setId(TestCaseRunTagId id) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(this == o) { + return true; + } + if(o == null || getClass() != o.getClass()) { + return false; + } TestCaseRunTag that = (TestCaseRunTag) o; return Objects.equals(id, that.id); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTagId.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTagId.java index 51f0cf70..ae81f551 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTagId.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/TestCaseRunTagId.java @@ -15,11 +15,12 @@ ******************************************************************************/ package com.exactpro.sf.embedded.statistics.entities; -import javax.persistence.Column; -import javax.persistence.Embeddable; import java.io.Serializable; import java.util.Objects; +import javax.persistence.Column; +import javax.persistence.Embeddable; + @Embeddable public class TestCaseRunTagId implements Serializable { @@ -54,8 +55,12 @@ public void setTagId(Long tagId) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(this == o) { + return true; + } + if(o == null || getClass() != o.getClass()) { + return false; + } TestCaseRunTagId that = (TestCaseRunTagId) o; return Objects.equals(tcrId, that.tcrId) && Objects.equals(tagId, that.tagId); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/User.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/User.java index 3c68b127..8fa4cec3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/User.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/entities/User.java @@ -24,8 +24,7 @@ import javax.persistence.UniqueConstraint; @Entity -@Table(name="stusers", -uniqueConstraints = {@UniqueConstraint(columnNames={"name"})}) +@Table(name = "stusers", uniqueConstraints = @UniqueConstraint(columnNames = "name")) @SequenceGenerator(name="stusers_generator", sequenceName="stusers_sequence") public class User { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/ReportValue.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/ReportValue.java index c3dac7ca..aa2e0856 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/ReportValue.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/ReportValue.java @@ -58,7 +58,7 @@ public Object getValue() { @Override public String toString() { - return this.value.toString(); + return value.toString(); } protected enum Type { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/StatisticsReportHandlerLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/StatisticsReportHandlerLoader.java index ffc07976..059abf73 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/StatisticsReportHandlerLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/StatisticsReportHandlerLoader.java @@ -38,7 +38,7 @@ import com.exactpro.sf.embedded.statistics.handlers.impl.DefaultStatisticsHandlerFactory; public class StatisticsReportHandlerLoader implements ILoadableManager { - private final static Logger logger = LoggerFactory.getLogger(StatisticsReportHandlerLoader.class); + private static final Logger logger = LoggerFactory.getLogger(StatisticsReportHandlerLoader.class); private final Map uriToClass = new ConcurrentHashMap<>(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/AbstractStatisticsReportHandler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/AbstractStatisticsReportHandler.java index 5a73ee81..fb928d3c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/AbstractStatisticsReportHandler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/AbstractStatisticsReportHandler.java @@ -19,14 +19,14 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; +import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; import java.util.Objects; -import com.csvreader.CsvWriter; import org.apache.commons.lang3.StringUtils; -import java.time.format.DateTimeFormatter; +import com.csvreader.CsvWriter; import com.exactpro.sf.embedded.statistics.handlers.IStatisticsReportHandler; import com.exactpro.sf.embedded.statistics.handlers.ReportRow; import com.exactpro.sf.embedded.statistics.handlers.ReportValue; @@ -49,7 +49,7 @@ public AbstractStatisticsReportHandler(List header, String prefix) { @Override public List getHeaderColumns() { - return this.HEADER; + return HEADER; } @Override @@ -57,7 +57,7 @@ public String getReportName(AggregateReportParameters parameters) { Objects.requireNonNull(parameters, "'AggregateReportParameters' parameter"); Objects.requireNonNull(parameters.getFrom(), "'From' parameter"); Objects.requireNonNull(parameters.getTo(), "'To' parameter"); - StringBuilder reportName = new StringBuilder(this.PREFIX) + StringBuilder reportName = new StringBuilder(PREFIX) .append(AGGREGATED_REPORT_NAME_PART) .append(formatter.format(parameters.getFrom())) .append("__") diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/DefaultStatisticsHandlerFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/DefaultStatisticsHandlerFactory.java index 9ad11172..58218637 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/DefaultStatisticsHandlerFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/handlers/impl/DefaultStatisticsHandlerFactory.java @@ -20,7 +20,7 @@ import com.exactpro.sf.embedded.statistics.handlers.IStatisticsReportHandler; import com.exactpro.sf.embedded.statistics.handlers.IStatisticsReportHandlerFactory; -@ResourceAliases({"Default_Report"}) +@ResourceAliases("Default_Report") public class DefaultStatisticsHandlerFactory implements IStatisticsReportHandlerFactory { @Override public IStatisticsReportHandler createReportHandler() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AggregatedReportRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AggregatedReportRow.java index 90b8c3fc..52c27fc1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AggregatedReportRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/AggregatedReportRow.java @@ -15,6 +15,8 @@ ******************************************************************************/ package com.exactpro.sf.embedded.statistics.storage; +import java.sql.Timestamp; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -24,7 +26,6 @@ import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; -import java.time.LocalDateTime; import com.exactpro.sf.embedded.statistics.entities.SfInstance; import com.exactpro.sf.embedded.statistics.entities.Tag; @@ -48,33 +49,33 @@ public class AggregatedReportRow extends CommonReportRow { public AggregatedReportRow() { for (String type : TYPES) { - this.fields.put(type, null); + fields.put(type, null); } - this.fields.put("User Comments", new TestCaseRunComments()); - this.fields.put("SfInstance", new SfInstance()); + fields.put("User Comments", new TestCaseRunComments()); + fields.put("SfInstance", new SfInstance()); } public AggregatedReportRow(Long sfId, String name, String description, int status, String failReason, - java.sql.Timestamp startTime, java.sql.Timestamp finishTime, String userName, String host, + Timestamp startTime, Timestamp finishTime, String userName, String host, String reportFolder, String reportFile) { - this.fields.put("id", sfId); - this.fields.put("Name", name); - this.fields.put("Description", description); - this.fields.put("Status", StatusType.getStatusType(status)); - this.fields.put("Failure Reason", failReason); + fields.put("id", sfId); + fields.put("Name", name); + fields.put("Description", description); + fields.put("Status", StatusType.getStatusType(status)); + fields.put("Failure Reason", failReason); //this.faildActions = faildActions; - this.fields.put("Start Time", DateTimeUtility.toLocalDateTime(startTime)); - this.fields.put("Finish Time", DateTimeUtility.toLocalDateTime(finishTime)); - this.fields.put("User Name", userName); + fields.put("Start Time", DateTimeUtility.toLocalDateTime(startTime)); + fields.put("Finish Time", DateTimeUtility.toLocalDateTime(finishTime)); + fields.put("User Name", userName); SfInstance sfInstance = new SfInstance(); sfInstance.setHost(host); - this.fields.put("SfInstance", sfInstance); + fields.put("SfInstance", sfInstance); //this.servicesUsed = servicesUsed; - this.fields.put("Report Folder", reportFolder); - this.fields.put("Report File", reportFile); + fields.put("Report Folder", reportFolder); + fields.put("Report File", reportFile); } @@ -83,7 +84,7 @@ public T get(String key, T defaultValue) { if (!TYPES.contains(key)) { throw new RuntimeException("There is no field in AggregatedReportRow: " + key); } - return ObjectUtils.defaultIfNull((T) this.fields.get(key), defaultValue); + return ObjectUtils.defaultIfNull((T)fields.get(key), defaultValue); } public boolean isUnknownTc() { @@ -93,7 +94,7 @@ public boolean isUnknownTc() { public String getRowKey() { return Long.toString(getMatrixRunId() != null ? getMatrixRunId() : -1l) - + Long.toString(getTestCaseRunId() != null ? getTestCaseRunId() : -1l); + + (getTestCaseRunId() != null ? getTestCaseRunId() : -1l); } @@ -123,64 +124,64 @@ public long getSfId() { } public void setSfId(long sfId) { - this.fields.put("id", sfId); + fields.put("id", sfId); } public String getDescription() { - return (String) this.fields.get("Description"); + return (String)fields.get("Description"); } public void setDescription(String description) { //TODO: Remove escaping after release 3.1, because escaping is executed on save data - this.fields.put("Description", StringEscapeUtils.escapeEcmaScript(description)); + fields.put("Description", StringEscapeUtils.escapeEcmaScript(description)); } public StatusType getStatus() { - return (StatusType) this.fields.get("Status"); + return (StatusType)fields.get("Status"); } public void setStatus(StatusType status) { - this.fields.put("Status", status); + fields.put("Status", status); } public String getFailReason() { - return (String) this.fields.get("Failure Reason"); + return (String)fields.get("Failure Reason"); } public void setFailReason(String failReason) { - this.fields.put("Failure Reason", failReason); + fields.put("Failure Reason", failReason); } public String getMatrixFailReason() { - return (String) this.fields.get("Matrix Failure Reason"); + return (String)fields.get("Matrix Failure Reason"); } public void setMatrixFailReason(String matrixFailReason) { - this.fields.put("Matrix Failure Reason", matrixFailReason); + fields.put("Matrix Failure Reason", matrixFailReason); } public String getFailedActions() { - return (String) this.fields.get("Failed Actions"); + return (String)fields.get("Failed Actions"); } public void setFailedActions(String faildActions) { - this.fields.put("Failed Actions", faildActions); + fields.put("Failed Actions", faildActions); } public LocalDateTime getStartTime() { - return (LocalDateTime) this.fields.get("Start Time"); + return (LocalDateTime)fields.get("Start Time"); } public void setStartTime(LocalDateTime startTime) { - this.fields.put("Start Time", startTime); + fields.put("Start Time", startTime); } public LocalDateTime getFinishTime() { - return (LocalDateTime) this.fields.get("Finish Time"); + return (LocalDateTime)fields.get("Finish Time"); } public void setFinishTime(LocalDateTime finishTime) { - this.fields.put("Finish Time", finishTime); + fields.put("Finish Time", finishTime); } public Long getExecutionTime() { @@ -198,11 +199,11 @@ public Long getExecutionCaseTime() { } public String getUserName() { - return (String) this.fields.get("User Name"); + return (String)fields.get("User Name"); } public void setUserName(String userName) { - this.fields.put("User Name", userName); + fields.put("User Name", userName); } public String getHost() { @@ -214,67 +215,67 @@ public void setHost(String host) { } public String getServicesUsed() { - return (String) this.fields.get("Services Used"); + return (String)fields.get("Services Used"); } public void setServicesUsed(String servicesUsed) { - this.fields.put("Services Used", servicesUsed); + fields.put("Services Used", servicesUsed); } public String getMatrixName() { - return (String) this.fields.get("Matrix Name"); + return (String)fields.get("Matrix Name"); } public void setMatrixName(String matrixName) { - this.fields.put("Matrix Name", matrixName); + fields.put("Matrix Name", matrixName); } public String getTestCaseName() { - return (String) this.fields.get("Test Case Name"); + return (String)fields.get("Test Case Name"); } public void setTestCaseName(String testCaseName) { - this.fields.put("Test Case Name", testCaseName); + fields.put("Test Case Name", testCaseName); } public Long getTestCaseNumber() { - return (Long)this.fields.get("Test Case Number"); + return (Long)fields.get("Test Case Number"); } public void setTestCaseNumber(Long testCaseNumber) { - this.fields.put("Test Case Number", testCaseNumber); + fields.put("Test Case Number", testCaseNumber); } public LocalDateTime getMatrixStartTime() { - return (LocalDateTime) this.fields.get("Matrix Start Time"); + return (LocalDateTime)fields.get("Matrix Start Time"); } public void setMatrixStartTime(LocalDateTime matrixStartTime) { - this.fields.put("Matrix Start Time", matrixStartTime); + fields.put("Matrix Start Time", matrixStartTime); } public LocalDateTime getMatrixFinishTime() { - return (LocalDateTime) this.fields.get("Matrix Finish Time"); + return (LocalDateTime)fields.get("Matrix Finish Time"); } public void setMatrixFinishTime(LocalDateTime matrixFinishTime) { - this.fields.put("Matrix Finish Time", matrixFinishTime); + fields.put("Matrix Finish Time", matrixFinishTime); } public Long getTestCaseRunId() { - return (Long) this.fields.get("Test Case Run Id"); + return (Long)fields.get("Test Case Run Id"); } public void setTestCaseRunId(Long testCaseRunId) { - this.fields.put("Test Case Run Id", testCaseRunId); + fields.put("Test Case Run Id", testCaseRunId); } public String getEnvironmentName() { - return (String) this.fields.get("Environment"); + return (String)fields.get("Environment"); } public void setEnvironmentName(String environmentName) { - this.fields.put("Environment", environmentName); + fields.put("Environment", environmentName); } public boolean isMatrixRow() { @@ -282,7 +283,7 @@ public boolean isMatrixRow() { } public void setMatrixRow(boolean matrixRow) { - this.fields.put("Matrix Row", matrixRow); + fields.put("Matrix Row", matrixRow); } public int getPort() { @@ -302,60 +303,60 @@ public void setSfName(String sfName) { } public Long getMatrixRunId() { - return (Long) this.fields.get("Matrix Run Id"); + return (Long)fields.get("Matrix Run Id"); } public void setMatrixRunId(Long matrixRunId) { - this.fields.put("Matrix Run Id", matrixRunId); + fields.put("Matrix Run Id", matrixRunId); } public String getTestCaseId() { - return (String) this.fields.get("Test Case Id"); + return (String)fields.get("Test Case Id"); } public void setTestCaseId(String testCaseId) { - this.fields.put("Test Case Id", testCaseId); + fields.put("Test Case Id", testCaseId); } @SuppressWarnings("unchecked") public List getTags() { - return (List) this.fields.get("Tags"); + return (List)fields.get("Tags"); } public String getTagsString() { List tags = getTags(); - if (tags != null && !tags.isEmpty()) { + if(tags != null && !tags.isEmpty()) { return tags.stream().map(Tag::getName).collect(Collectors.joining(",")); } return ""; } public void setTags(List tags) { - this.fields.put("Tags", tags); + fields.put("Tags", tags); } public String getReportFolder() { - return (String) this.fields.get("Report Folder"); + return (String)fields.get("Report Folder"); } public void setReportFolder(String reportFolder) { - this.fields.put("Report Folder", reportFolder); + fields.put("Report Folder", reportFolder); } public String getReportFile() { - return (String) this.fields.get("Report File"); + return (String)fields.get("Report File"); } public void setReportFile(String reportFile) { - this.fields.put("Report File", reportFile); + fields.put("Report File", reportFile); } public TestCaseRunComments getUserComments() { - return (TestCaseRunComments) this.fields.get("User Comments"); + return (TestCaseRunComments)fields.get("User Comments"); } public void setUserComments(TestCaseRunComments userComments) { - this.fields.put("User Comments", userComments); + fields.put("User Comments", userComments); } public long getPassedCount() { @@ -363,7 +364,7 @@ public long getPassedCount() { } public void setPassedCount(long passedCount) { - this.fields.put("Passed", passedCount); + fields.put("Passed", passedCount); } public long getFailedCount() { @@ -371,7 +372,7 @@ public long getFailedCount() { } public void setFailedCount(long failedCount) { - this.fields.put("Failed", failedCount); + fields.put("Failed", failedCount); } public long getConditionallyPassedCount() { @@ -379,7 +380,7 @@ public long getConditionallyPassedCount() { } public void setConditionallyPassedCount(long conditionallyPassedCount) { - this.fields.put("CondPassed", conditionallyPassedCount); + fields.put("CondPassed", conditionallyPassedCount); } public int getHash() { @@ -387,7 +388,7 @@ public int getHash() { } public void setHash(int hash) { - this.fields.put("Hash", hash); + fields.put("Hash", hash); } public String getTaggedActions() { @@ -399,20 +400,20 @@ public boolean isFailed() { } public String getMessageType() { - return (String) this.fields.get("Message Type"); + return (String)fields.get("Message Type"); } public void setMessageType(String messageType) { - this.fields.put("Message Type", messageType); + fields.put("Message Type", messageType); } //TODO merge ActionName, TestCaseName, MatrixName >> Name public String getActionName() { - return (String) this.fields.get("Action Name"); + return (String)fields.get("Action Name"); } public void setActionName(String matrixName) { - this.fields.put("Action Name", matrixName); + fields.put("Action Name", matrixName); } public boolean isActionRow() { @@ -420,23 +421,23 @@ public boolean isActionRow() { } public void setActionRow(boolean matrixRow) { - this.fields.put("Action Row", matrixRow); + fields.put("Action Row", matrixRow); } public SfInstance getSfCurrentInstance() { - return (SfInstance) this.fields.get("sfCurrentInstance"); + return (SfInstance)fields.get("sfCurrentInstance"); } public void setSfCurrentInstance(SfInstance sfCurrent) { - this.fields.put("sfCurrentInstance", sfCurrent); + fields.put("sfCurrentInstance", sfCurrent); } public SfInstance getSfInstance() { - return (SfInstance) this.fields.get("SfInstance"); + return (SfInstance)fields.get("SfInstance"); } public void setSfInstance(SfInstance instance) { - this.fields.put("SfInstance", instance); + fields.put("SfInstance", instance); } public long getReproducedKnownBugsCount() { @@ -444,7 +445,7 @@ public long getReproducedKnownBugsCount() { } public void setReproducedKnownBugsCount(long count) { - this.fields.put("Reproduced Known Bugs Count", count); + fields.put("Reproduced Known Bugs Count", count); } public long getNonReproducedKnownBugsCount() { @@ -452,7 +453,7 @@ public long getNonReproducedKnownBugsCount() { } public void setNonReproducedKnownBugsCount(long count) { - this.fields.put("Non-reproduced Known Bugs Count", count); + fields.put("Non-reproduced Known Bugs Count", count); } public List getCategorisedKnownBugs() { @@ -460,7 +461,7 @@ public List getCategorisedKnownBugs() { } public void setCategorisedKnownBugs(List categorisedKnownBugs) { - this.fields.put("Known Bugs", categorisedKnownBugs); + fields.put("Known Bugs", categorisedKnownBugs); } public List getTestCaseRows() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/DayleTestCasesStatRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/DayleTestCasesStatRow.java index e2e6ea20..192cc6f3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/DayleTestCasesStatRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/DayleTestCasesStatRow.java @@ -35,8 +35,6 @@ public class DayleTestCasesStatRow { public DayleTestCasesStatRow(Date date, long passedCount, long conditionallyPassedCount, long failedCount) { - super(); - this.date = DateTimeUtility.toLocalDateTime(date); this.passedCount = passedCount; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java index deba0ebc..14e2b4cd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/NativeDbOperations.java @@ -24,8 +24,6 @@ import java.util.List; import java.util.stream.Collectors; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ObjectArrays; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.time.DurationFormatUtils; import org.hibernate.Query; @@ -47,6 +45,8 @@ import com.exactpro.sf.embedded.statistics.storage.reporting.TagGroupReportRow; import com.exactpro.sf.embedded.storage.HibernateStorageSettings; import com.exactpro.sf.scriptrunner.StatusType; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ObjectArrays; public class NativeDbOperations { @@ -61,7 +61,7 @@ public class NativeDbOperations { private static final String FILTERED_NAME = "filtered"; - private HibernateStorageSettings settings; + private final HibernateStorageSettings settings; public NativeDbOperations(HibernateStorageSettings settings) { this.settings = settings; @@ -69,13 +69,13 @@ public NativeDbOperations(HibernateStorageSettings settings) { private boolean isMysql() { - return this.settings.getDbms().equals(DbmsType.MySql.getValue()); + return settings.getDbms().equals(DbmsType.MySql.getValue()); } private boolean isPostgreSql() { - return this.settings.getDbms().equals(DbmsType.PostgreSQL.getValue()); + return settings.getDbms().equals(DbmsType.PostgreSQL.getValue()); } @@ -200,7 +200,7 @@ public List executeTaggedComparisonQuery(Session session, Long[] first } - throw new UnsupportedOperationException("Unsupported DBMS " + this.settings.getDbms()); + throw new UnsupportedOperationException("Unsupported DBMS " + settings.getDbms()); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java index 43b54835..2a8175d4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsReportingStorage.java @@ -17,11 +17,13 @@ import java.math.BigInteger; import java.sql.Timestamp; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import java.util.function.BiConsumer; @@ -34,7 +36,6 @@ import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.LocalDateTime; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.embedded.statistics.entities.KnownBug; @@ -65,9 +66,9 @@ public class StatisticsReportingStorage implements IAdditionalStatisticsLoader { private static final String FAILED_ACTION_SPLITTER = "FACTSPLITTER"; private static final String ACTION_RANK_FREASON_SPLITTER = "ARFRSPLITTER"; - private SessionFactory sessionFactory; + private final SessionFactory sessionFactory; - private HibernateStorageSettings settings; + private final HibernateStorageSettings settings; public StatisticsReportingStorage(SessionFactory sessionFactory, HibernateStorageSettings settings) { @@ -203,7 +204,7 @@ private void loadKnownBugInfo(List result) { + "where TCR.id in (:ids) " + "group by TCR.id, ARKB.reproduced"; - Session session = this.sessionFactory.openSession(); + Session session = sessionFactory.openSession(); try (AutoCloseable ignore = session::close) { Query query = session.createQuery(querySting); query.setParameterList("ids", ids); @@ -259,7 +260,7 @@ private List parseAggregatedTaggedReportResult(List rows) { try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameterList("ids", matrixRunToRow.keySet()); @@ -372,7 +373,7 @@ private void findUsedServices(List rows) { Map servicesUsed = readServicesUsedResultSet(resultSet); - for(Map.Entry entry: servicesUsed.entrySet()) { + for(Entry entry : servicesUsed.entrySet()) { List mrRows = matrixRunToRow.get(entry.getKey()); @@ -434,7 +435,7 @@ private void loadFailedActions(List rows) { try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameterList("ids", failedTcRunIds); @@ -444,7 +445,7 @@ private void loadFailedActions(List rows) { Map failedActions = readFailedActionsResultSet(resultSet); - for(Map.Entry entry: failedActions.entrySet()) { + for(Entry entry : failedActions.entrySet()) { failedTestCaseRunRows.get(entry.getKey()).setFailedActions(entry.getValue().toString()); @@ -477,7 +478,7 @@ private Map readFailedActionsResultSet(List resul } else { - result.get(tcrId).append(", ").append(Long.toString(actionRank)); + result.get(tcrId).append(", ").append(actionRank); } @@ -662,7 +663,7 @@ public List generateAggregatedReport(AggregateReportParamet try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameterList("mrId", params.getMatrixRunIds()); @@ -695,7 +696,7 @@ public List generateTestCaseHistoryReport(AggregateReportPar try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameter("tcId", params.getTestCaseId()); @@ -755,7 +756,7 @@ public List generateDayleTestCasesStatReport(AggregateRep try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(sb.toString()); query.setParameter("from", params.getFrom()); @@ -770,11 +771,7 @@ public List generateDayleTestCasesStatReport(AggregateRep Object[] tagIds = tagsToIds(params.getTags()); query.setParameterList("tcrTags", tagIds); query.setParameterList("mrTags", tagIds); - if(params.isAllTags()) { - query.setParameter("numTags", (long)params.getTags().size()); - } else { - query.setParameter("numTags", 1l); - } + query.setParameter("numTags", params.isAllTags() ? (long)params.getTags().size() : 1l); } query.setMaxResults(10); @@ -875,7 +872,7 @@ public List generateTestScriptsReport(AggregateReportParame } - if(TestCasesDisplayMode.FailedOnly.equals(params.getTcDisplayMode())) { + if(params.getTcDisplayMode() == TestCasesDisplayMode.FailedOnly) { sb.append("and (TCR.status = 0 or MR.failReason is not null or MR.failReason <> '') "); } @@ -889,15 +886,15 @@ public List generateTestScriptsReport(AggregateReportParame sb.append(params.isSortAsc() ? " asc " : " desc "); - if(TestCasesDisplayMode.FailedOnly.equals(params.getTcDisplayMode())) { + if(params.getTcDisplayMode() == TestCasesDisplayMode.FailedOnly) { sb.append(", TCR.rank"); } - if(TestCasesDisplayMode.AllNatural.equals(params.getTcDisplayMode())) { + if(params.getTcDisplayMode() == TestCasesDisplayMode.AllNatural) { sb.append(", TCR.rank"); } - if(TestCasesDisplayMode.AllFailedFirst.equals(params.getTcDisplayMode())) { + if(params.getTcDisplayMode() == TestCasesDisplayMode.AllFailedFirst) { sb.append(", TCR.status, TCR.rank"); } @@ -905,7 +902,7 @@ public List generateTestScriptsReport(AggregateReportParame try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(sb.toString()); query.setParameter("from", params.getFrom()); @@ -921,12 +918,7 @@ public List generateTestScriptsReport(AggregateReportParame Object[] ids = tagsToIds(params.getTags()); query.setParameterList("tcrTags", ids); query.setParameterList("mrTags", ids); - - if(params.isAllTags()) { - query.setParameter("numTags", (long)params.getTags().size()); - } else { - query.setParameter("numTags", 1l); - } + query.setParameter("numTags", params.isAllTags() ? (long)params.getTags().size() : 1l); } @@ -961,7 +953,7 @@ public List generateFailedActionsInfo(AggregateReportParameters p try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameter("tcrId", params.getTestCaseRunId()); @@ -1006,7 +998,7 @@ public Map> generateTestCasesFailedActionsInfo(Aggrega + "where TCR.id in (:tcrIds) and AR.status = 0 " + "order by AR.rank"; - Session session = this.sessionFactory.openSession(); + Session session = sessionFactory.openSession(); try (AutoCloseable ignore = session::close) { Query query = session.createQuery(queryString); query.setParameterList("ids", params.getTestCaseRunIds()); @@ -1051,7 +1043,7 @@ public List generateTaggedActionsInfo(AggregateReportParameters p Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameter("tcrId", params.getTestCaseRunId()); List list = query.list(); @@ -1075,7 +1067,7 @@ public List generateKnownBugsReport(AggregateReportParameters param + "join AR.actionRunKnownBugs as ARKB " + "join ARKB.id.knownBug as KB " + "where TCR.id = :tcrId"; - Session session = this.sessionFactory.openSession(); + Session session = sessionFactory.openSession(); try (AutoCloseable ignore = session::close) { Query query = session.createQuery(queryString); query.setParameter("tcrId", params.getTestCaseRunId()); @@ -1099,7 +1091,7 @@ public Map> generateTestCasesKnownBugsReports(AggregateR + "join AR.actionRunKnownBugs as ARKB " + "where TCR.id in (:ids)"; - Session session = this.sessionFactory.openSession(); + Session session = sessionFactory.openSession(); try (AutoCloseable ignore = session::close) { Query query = session.createQuery(queryString); query.setParameterList("ids", params.getTestCaseRunIds()); @@ -1141,7 +1133,7 @@ public List generateActionsAggregatedReportRow(AggregateRep Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameter("tcrId", params.getTestCaseRunId()); @@ -1190,7 +1182,10 @@ private List parseActionsToAggregateReportRow(List escapeDesription(List list) { - list.forEach(item -> item.setDescription(StringEscapeUtils.escapeEcmaScript(item.getDescription()))); + for(ActionInfoRow item : list) { + item.setDescription(StringEscapeUtils.escapeEcmaScript(item.getDescription())); + } + return list; } @@ -1264,7 +1259,7 @@ public List generateScriptsWeatherReport(AggregateReportParame try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(lastScriptsQuery); //query.setParameterValue("tcrId", params.getTestCaseRunId()); @@ -1288,8 +1283,8 @@ public List generateScriptsWeatherReport(AggregateReportParame } } - - } finally { + return result; + } finally { if(session != null) { session.close(); @@ -1297,9 +1292,7 @@ public List generateScriptsWeatherReport(AggregateReportParame } - return result; - - } + } private List readTaggedSetsComparisonResultSet(List rs) { @@ -1406,7 +1399,7 @@ public TaggedComparisonResult generateTaggedSetsComparisonReport(TaggedSetsCompa try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); result.setRows( readTaggedSetsComparisonResultSet( @@ -1434,7 +1427,7 @@ public TagGroupReportResult generateTagGroupReport(TagGroupReportParameters para try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); return nativeOps.generateTagGroupReport(session, params); @@ -1485,7 +1478,7 @@ public List generateAggregatedTaggedReport(AggregateReportP Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameter("from", params.getFrom()); @@ -1518,15 +1511,17 @@ private void loadAndAddMatrixTags(Map> matrixRow + "order by MR.id, T.name"; Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameterList("ids", matrixRows.keySet()); @SuppressWarnings("unchecked") List resultSet = query.list(); Map> tagsUsed = readTagsResultSet(resultSet, (t, row) -> t.setCustom(false), true); - for(Map.Entry> entry: tagsUsed.entrySet()) { + for(Entry> entry : tagsUsed.entrySet()) { List rows = matrixRows.get(entry.getKey()); - rows.forEach(r -> r.setTags(new ArrayList<>(entry.getValue()))); + for(AggregatedReportRow r : rows) { + r.setTags(new ArrayList<>(entry.getValue())); + } } } finally { if(session != null) { @@ -1549,13 +1544,13 @@ private void loadAndAddTestCaseTags(Map rows) { + "order by TCR.id, TCRT.tag.name"; Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Query query = session.createQuery(queryString); query.setParameterList("ids", rows.keySet()); @SuppressWarnings("unchecked") List resultSet = query.list(); Map> tagsUsed = readTagsResultSet(resultSet, (t, row) -> t.setCustom((Boolean)row[4]), false); - for(Map.Entry> entry: tagsUsed.entrySet()) { + for(Entry> entry : tagsUsed.entrySet()) { AggregatedReportRow row = rows.get(entry.getKey()); List tags = row.getTags(); if (tags == null) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsStorage.java index 86f24276..a6320e16 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/StatisticsStorage.java @@ -21,13 +21,6 @@ import java.util.List; import java.util.Map; -import com.exactpro.sf.embedded.statistics.StatisticsUtils; -import com.exactpro.sf.embedded.statistics.entities.ActionRunKnownBug; -import com.exactpro.sf.embedded.statistics.entities.KnownBug; -import com.exactpro.sf.embedded.statistics.entities.TestCaseRunTag; -import com.exactpro.sf.embedded.statistics.entities.TestCaseRunTagId; -import com.exactpro.sf.storage.StorageException; - import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.DefaultComponentSafeNamingStrategy; @@ -36,9 +29,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.exactpro.sf.embedded.statistics.StatisticsUtils; import com.exactpro.sf.embedded.statistics.entities.Action; import com.exactpro.sf.embedded.statistics.entities.ActionRun; +import com.exactpro.sf.embedded.statistics.entities.ActionRunKnownBug; import com.exactpro.sf.embedded.statistics.entities.Environment; +import com.exactpro.sf.embedded.statistics.entities.KnownBug; import com.exactpro.sf.embedded.statistics.entities.Matrix; import com.exactpro.sf.embedded.statistics.entities.MatrixRun; import com.exactpro.sf.embedded.statistics.entities.MessageType; @@ -49,9 +45,11 @@ import com.exactpro.sf.embedded.statistics.entities.TestCase; import com.exactpro.sf.embedded.statistics.entities.TestCaseRun; import com.exactpro.sf.embedded.statistics.entities.TestCaseRunStatus; +import com.exactpro.sf.embedded.statistics.entities.TestCaseRunTag; import com.exactpro.sf.embedded.statistics.entities.User; import com.exactpro.sf.embedded.storage.AbstractHibernateStorage; import com.exactpro.sf.embedded.storage.HibernateStorageSettings; +import com.exactpro.sf.storage.StorageException; import com.exactpro.sf.util.LRUMap; public class StatisticsStorage extends AbstractHibernateStorage implements IStatisticsStorage { @@ -61,16 +59,16 @@ public class StatisticsStorage extends AbstractHibernateStorage implements IStat public static final String UNKNOWN_TC_ID = "_unknown_tc_"; private StatisticsReportingStorage reportingStorage; - - private Map environmentsCache = new HashMap(); - - private Map usersCache = new HashMap(); - - private Map actionsCache = Collections.synchronizedMap(new LRUMap(40)); - - private Map msgTypesCache = Collections.synchronizedMap(new LRUMap(40)); - private Map knownBugCache = Collections.synchronizedMap(new LRUMap<>(40)); + private final Map environmentsCache = new HashMap(); + + private final Map usersCache = new HashMap(); + + private final Map actionsCache = Collections.synchronizedMap(new LRUMap(40)); + + private final Map msgTypesCache = Collections.synchronizedMap(new LRUMap(40)); + + private final Map knownBugCache = Collections.synchronizedMap(new LRUMap<>(40)); public StatisticsStorage(HibernateStorageSettings settings) { super(settings); @@ -118,8 +116,8 @@ public SfInstance loadSfInstance(String host, String port, String sfName) { criterions.add(Restrictions.eq("host", host)); criterions.add(Restrictions.eq("port", Integer.parseInt( port ))); criterions.add(Restrictions.eq("name", sfName)); - - List queryResults = this.storage.getAllEntities(SfInstance.class, criterions); + + List queryResults = storage.getAllEntities(SfInstance.class, criterions); if(!queryResults.isEmpty()) { @@ -134,8 +132,8 @@ public SfInstance loadSfInstance(String host, String port, String sfName) { result.setHost(host); result.setPort(Integer.parseInt( port )); result.setName(sfName); - - this.storage.add(result); + + storage.add(result); } @@ -147,8 +145,8 @@ public SfInstance loadSfInstance(String host, String port, String sfName) { @Override public TestCase loadUnknownTestCase() { - - TestCase result = this.storage.getEntityByField(TestCase.class, "testCaseId", UNKNOWN_TC_ID); + + TestCase result = storage.getEntityByField(TestCase.class, "testCaseId", UNKNOWN_TC_ID); if(result == null) { @@ -157,8 +155,8 @@ public TestCase loadUnknownTestCase() { result = new TestCase(); result.setTestCaseId(UNKNOWN_TC_ID); - - this.storage.add(result); + + storage.add(result); } @@ -168,14 +166,14 @@ public TestCase loadUnknownTestCase() { @Override public Environment getEnvironmentEntity(String name) { - - if(this.environmentsCache.containsKey(name)) { - - return this.environmentsCache.get(name); + + if(environmentsCache.containsKey(name)) { + + return environmentsCache.get(name); } else { - - Environment result = this.storage.getEntityByField(Environment.class, "name", name); + + Environment result = storage.getEntityByField(Environment.class, "name", name); if(result == null) { @@ -184,12 +182,12 @@ public Environment getEnvironmentEntity(String name) { result = new Environment(); result.setName(name); - - this.storage.add(result); + + storage.add(result); } - - this.environmentsCache.put(name, result); + + environmentsCache.put(name, result); return result; @@ -199,14 +197,14 @@ public Environment getEnvironmentEntity(String name) { @Override public User getUserEntity(String name) { - - if(this.usersCache.containsKey(name)) { - - return this.usersCache.get(name); + + if(usersCache.containsKey(name)) { + + return usersCache.get(name); } else { - - User result = this.storage.getEntityByField(User.class, "name", name); + + User result = storage.getEntityByField(User.class, "name", name); if(result == null) { @@ -215,12 +213,12 @@ public User getUserEntity(String name) { result = new User(); result.setName(name); - - this.storage.add(result); + + storage.add(result); } - - this.usersCache.put(name, result); + + usersCache.put(name, result); return result; @@ -230,8 +228,8 @@ public User getUserEntity(String name) { @Override public Service getServiceEntity(String name) { - - Service result = this.storage.getEntityByField(Service.class, "name", name); + + Service result = storage.getEntityByField(Service.class, "name", name); if(result == null) { @@ -240,8 +238,8 @@ public Service getServiceEntity(String name) { result = new Service(); result.setName(name); - - this.storage.add(result); + + storage.add(result); } @@ -251,8 +249,8 @@ public Service getServiceEntity(String name) { @Override public Action getActionEntity(String name) { - - Action result = this.actionsCache.get(name); + + Action result = actionsCache.get(name); if(result != null) { @@ -261,8 +259,8 @@ public Action getActionEntity(String name) { return result; } - - result = this.storage.getEntityByField(Action.class, "name", name); + + result = storage.getEntityByField(Action.class, "name", name); if(result == null) { @@ -271,12 +269,12 @@ public Action getActionEntity(String name) { result = new Action(); result.setName(name); - - this.storage.add(result); + + storage.add(result); } - - this.actionsCache.put(name, result); + + actionsCache.put(name, result); return result; @@ -284,16 +282,16 @@ public Action getActionEntity(String name) { @Override public MessageType getMsgTypeEntity(String name) { - - MessageType result = this.msgTypesCache.get(name); + + MessageType result = msgTypesCache.get(name); if(result != null) { return result; } - - result = this.storage.getEntityByField(MessageType.class, "name", name); + + result = storage.getEntityByField(MessageType.class, "name", name); if(result == null) { @@ -302,12 +300,12 @@ public MessageType getMsgTypeEntity(String name) { result = new MessageType(); result.setName(name); - - this.storage.add(result); + + storage.add(result); } - - this.msgTypesCache.put(name, result); + + msgTypesCache.put(name, result); return result; @@ -315,8 +313,8 @@ public MessageType getMsgTypeEntity(String name) { @Override public TestCase loadTestCase(String tcId) { - - TestCase result = this.storage.getEntityByField(TestCase.class, "testCaseId", tcId); + + TestCase result = storage.getEntityByField(TestCase.class, "testCaseId", tcId); if(result == null) { @@ -325,8 +323,8 @@ public TestCase loadTestCase(String tcId) { result = new TestCase(); result.setTestCaseId(tcId); - - this.storage.add(result); + + storage.add(result); } @@ -336,8 +334,8 @@ public TestCase loadTestCase(String tcId) { @Override public Matrix loadMatrix(String name) { - - Matrix result = this.storage.getEntityByField(Matrix.class, "name", name); + + Matrix result = storage.getEntityByField(Matrix.class, "name", name); if(result == null) { @@ -346,8 +344,8 @@ public Matrix loadMatrix(String name) { result = new Matrix(); result.setName(name); - - this.storage.add(result); + + storage.add(result); } @@ -358,21 +356,21 @@ public Matrix loadMatrix(String name) { @Override public KnownBug loadKnownBug(String subject, List categories) { String knownBugJson = StatisticsUtils.buildKnownBugJson(subject, categories); - KnownBug result = this.knownBugCache.get(knownBugJson); + KnownBug result = knownBugCache.get(knownBugJson); if (result != null) { logger.info("KnownBug cache hit"); return result; } // TODO: it's normal for single thread but for multi threads it can be reason of errors, because this logic could be executed from different threads at the same time // TODO: fix this logic in other methods too which loading reference information - result = this.storage.getEntityByField(KnownBug.class, "knownBug", knownBugJson); + result = storage.getEntityByField(KnownBug.class, "knownBug", knownBugJson); if (result == null) { result = new KnownBug(); result.setKnownBug(knownBugJson); - this.storage.add(result); + storage.add(result); } - this.knownBugCache.put(knownBugJson, result); + knownBugCache.put(knownBugJson, result); return result; } @@ -383,22 +381,22 @@ public StatisticsReportingStorage getReportingStorage() { @Override public List getAllSfInstances() { - - return this.storage.getAllEntities(SfInstance.class); + + return storage.getAllEntities(SfInstance.class); } @Override public List getAllTags() { - - return this.storage.getAllEntities(Tag.class); + + return storage.getAllEntities(Tag.class); } @Override public TagGroup getGroupByName(String name) { - - return this.storage.getEntityByField(TagGroup.class, "name", name); + + return storage.getEntityByField(TagGroup.class, "name", name); } @@ -408,61 +406,61 @@ public List getTagsWithoutGroup() { List criterions = new ArrayList<>(); criterions.add(Restrictions.isNull("group")); - - return this.storage.getAllEntities(Tag.class, criterions, "name", true); + + return storage.getAllEntities(Tag.class, criterions, "name", true); } @Override public List getAllTagGroups() { - - return this.storage.getAllEntities(TagGroup.class, new ArrayList(), "name", true); + + return storage.getAllEntities(TagGroup.class, new ArrayList(), "name", true); } @Override public SfInstance getSfInstanceById(long id) { - - return (SfInstance)this.storage.getEntityById(SfInstance.class, id); + + return (SfInstance)storage.getEntityById(SfInstance.class, id); } @Override public List getAllTestCases() { - - return this.storage.getAllEntities(TestCase.class); + + return storage.getAllEntities(TestCase.class); } @Override public TestCase getTestCaseById(long id) { - return (TestCase)this.storage.getEntityById(TestCase.class, id); + return (TestCase)storage.getEntityById(TestCase.class, id); } @Override public Tag getTagByName(String name) { - - return this.storage.getEntityByField(Tag.class, "name", name); + + return storage.getEntityByField(Tag.class, "name", name); } @Override public List getAllRunStatuses() { - - return this.storage.getAllEntities(TestCaseRunStatus.class); + + return storage.getAllEntities(TestCaseRunStatus.class); } @Override public void updateTcrUserComments(long testCaseId, TestCaseRunComments comments) { - - TestCaseRun tcr = (TestCaseRun)this.storage.getEntityById(TestCaseRun.class, testCaseId); + + TestCaseRun tcr = (TestCaseRun)storage.getEntityById(TestCaseRun.class, testCaseId); tcr.setComment(comments.getComment()); tcr.setFixRevision(comments.getFixedVersion()); tcr.setRunStatus(comments.getStatus()); - - this.storage.update(tcr); + + storage.update(tcr); } @@ -472,15 +470,15 @@ public List getTestCasesContains(String namePart) { List criterions = new ArrayList(); criterions.add(Restrictions.ilike("testCaseId", "%" + namePart + "%")); - - return this.storage.getAllEntities(TestCase.class, criterions, "testCaseId", true); + + return storage.getAllEntities(TestCase.class, criterions, "testCaseId", true); } @Override public TestCase getTestCaseByTcId(String id) { - - return this.storage.getEntityByField(TestCase.class, "testCaseId", id); + + return storage.getEntityByField(TestCase.class, "testCaseId", id); } @@ -490,8 +488,8 @@ public List getTagsContains(String namePart) { List criterions = new ArrayList(); criterions.add(Restrictions.ilike("name", "%" + namePart + "%")); - - return this.storage.getAllEntities(Tag.class, criterions, "name", true); + + return storage.getAllEntities(Tag.class, criterions, "name", true); } @@ -501,14 +499,14 @@ public List getGroupsContains(String namePart) { List criterions = new ArrayList(); criterions.add(Restrictions.ilike("name", "%" + namePart + "%")); - - return this.storage.getAllEntities(TagGroup.class, criterions, "name", true); + + return storage.getAllEntities(TagGroup.class, criterions, "name", true); } @Override public void updateSfCurrentID(long matrixRunId, long sfCurrentID) { - MatrixRun matrixRun = (MatrixRun) this.storage.getEntityById(MatrixRun.class, matrixRunId); + MatrixRun matrixRun = (MatrixRun)storage.getEntityById(MatrixRun.class, matrixRunId); String message; if (matrixRun == null) { @@ -526,16 +524,16 @@ public void updateSfCurrentID(long matrixRunId, long sfCurrentID) { } matrixRun.setSfCurrentInstance(currentSfInstance); - this.storage.update(matrixRun); + storage.update(matrixRun); } @Override public TestCaseRun getTestCaseRunById(long id) { - return (TestCaseRun)this.storage.getEntityById(TestCaseRun.class, id); + return (TestCaseRun)storage.getEntityById(TestCaseRun.class, id); } @Override public MatrixRun getMatrixRunById(long id) { - return (MatrixRun) this.storage.getEntityById(MatrixRun.class, id); + return (MatrixRun)storage.getEntityById(MatrixRun.class, id); } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/TestCaseHistoryRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/TestCaseHistoryRow.java index 4a9d1b2b..70228644 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/TestCaseHistoryRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/TestCaseHistoryRow.java @@ -42,8 +42,7 @@ public class TestCaseHistoryRow implements Serializable { public TestCaseHistoryRow(String testCaseId, String matrixName, LocalDateTime started, LocalDateTime finished, int status, String failReason) { - super(); - this.testCaseId = testCaseId; + this.testCaseId = testCaseId; this.matrixName = matrixName; this.started = started; this.finished = finished; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ActionInfoRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ActionInfoRow.java index ed6eee41..fb18d70a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ActionInfoRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ActionInfoRow.java @@ -42,8 +42,7 @@ public class ActionInfoRow implements Serializable { public ActionInfoRow(long rank, String description, String failReason, String action, String msgType, String service, String tag, int status, int hash) { - super(); - this.rank = rank; + this.rank = rank; this.description = description; this.failReason = failReason; this.action = action; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/AggregateReportParameters.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/AggregateReportParameters.java index b1eef611..60f12749 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/AggregateReportParameters.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/AggregateReportParameters.java @@ -51,7 +51,7 @@ public class AggregateReportParameters { private boolean allTags; // All or at least one - private boolean emptyCommentOnly = false; + private boolean emptyCommentOnly; private String sortBy; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ScriptWeatherRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ScriptWeatherRow.java index c55cf8ae..f564b7a3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ScriptWeatherRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/ScriptWeatherRow.java @@ -28,7 +28,7 @@ public enum Weather { private final String value; - private Weather(final String value) { + Weather(String value) { this.value = value; @@ -53,8 +53,7 @@ public ScriptWeatherRow() { } public ScriptWeatherRow(String matrixName, long passed, long conditionallyPassed, long failed) { - super(); - this.matrixName = matrixName; + this.matrixName = matrixName; this.passed = passed; this.conditionallyPassed = conditionallyPassed; this.failed = failed; @@ -62,13 +61,13 @@ public ScriptWeatherRow(String matrixName, long passed, long conditionallyPassed public String getWeatherString() { - if(this.failed == 0) { + if(failed == 0) { return Weather.Good.getValue(); } - if(this.passed == 0 && this.conditionallyPassed == 0) { + if(passed == 0 && conditionallyPassed == 0) { return Weather.Bad.getValue(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupDimension.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupDimension.java index 8b3f6cbd..6a1a3805 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupDimension.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupDimension.java @@ -50,7 +50,7 @@ public TagGroupDimension(long id, String name, List subTags, this.name = name; this.possibleSubTags = subTags; if (subTags != null) { - this.selectedSubTags = new ArrayList<>(this.possibleSubTags); + this.selectedSubTags = new ArrayList<>(possibleSubTags); } this.hasGroup = hasGroup; } @@ -103,7 +103,7 @@ public void setSelectedSubTags(List selectedSubTags) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + (isTag() ? 1231 : 1237); @@ -112,17 +112,22 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } TagGroupDimension other = (TagGroupDimension) obj; - if (id != other.id) - return false; - if (isTag() != other.isTag()) - return false; + if(id != other.id) { + return false; + } + if(isTag() != other.isTag()) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupReportRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupReportRow.java index daf3b809..db3bc083 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupReportRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TagGroupReportRow.java @@ -49,13 +49,7 @@ public class TagGroupReportRow implements Serializable { private String formattedExecTime; public String getPathEnd() { - - if(this.dimensionsPath != null) { - return this.dimensionsPath[dimensionsPath.length-1]; - } else { - return null; - } - + return dimensionsPath != null ? dimensionsPath[dimensionsPath.length - 1] : null; } public String[] getDimensionsPath() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TaggedComparisonRow.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TaggedComparisonRow.java index f5e2895f..ff7aa7df 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TaggedComparisonRow.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TaggedComparisonRow.java @@ -16,12 +16,12 @@ package com.exactpro.sf.embedded.statistics.storage.reporting; import java.io.Serializable; +import java.time.LocalDateTime; import java.util.Map; import com.exactpro.sf.embedded.statistics.entities.SfInstance; import com.exactpro.sf.embedded.statistics.storage.CommonReportRow; import com.exactpro.sf.scriptrunner.StatusType; -import java.time.LocalDateTime; @SuppressWarnings("serial") public class TaggedComparisonRow implements Serializable { @@ -55,7 +55,7 @@ public Long getFirstTestCaseRunId() { } public void setFirstTestCaseRunId(Long firstTestCaseRunId) { - this.firstSet.setTestCaseRunId(firstTestCaseRunId); + firstSet.setTestCaseRunId(firstTestCaseRunId); } public Long getFirstMatrixRunId() { @@ -63,11 +63,11 @@ public Long getFirstMatrixRunId() { } public void setFirstMatrixRunId(Long firstMatrixRunId) { - this.firstSet.setMatrixRunId(firstMatrixRunId); + firstSet.setMatrixRunId(firstMatrixRunId); } public void setFirstStatus(StatusType firstStatus) { - this.firstSet.setStatus(firstStatus); + firstSet.setStatus(firstStatus); } public String getFirstMatrixName() { @@ -75,7 +75,7 @@ public String getFirstMatrixName() { } public void setFirstMatrixName(String firstMatrixName) { - this.firstSet.setMatrixName(firstMatrixName); + firstSet.setMatrixName(firstMatrixName); } public String getFirstFailReason() { @@ -83,7 +83,7 @@ public String getFirstFailReason() { } public void setFirstFailReason(String firstFailReason) { - this.firstSet.setFailReason(firstFailReason); + firstSet.setFailReason(firstFailReason); } public Map getFirstFailedActions() { @@ -91,7 +91,7 @@ public Map getFirstFailedActions() { } public void setFirstFailedActions(Map firstFailedActions) { - this.firstSet.setFailedActions(firstFailedActions); + firstSet.setFailedActions(firstFailedActions); } public String getFirstUserComment() { @@ -99,7 +99,7 @@ public String getFirstUserComment() { } public void setFirstUserComment(String firstUserComment) { - this.firstSet.setUserComment(firstUserComment); + firstSet.setUserComment(firstUserComment); } public String getFirstUserStatus() { @@ -107,7 +107,7 @@ public String getFirstUserStatus() { } public void setFirstUserStatus(String firstUserStatus) { - this.firstSet.setUserStatus(firstUserStatus); + firstSet.setUserStatus(firstUserStatus); } public LocalDateTime getFirstStartTime() { @@ -115,7 +115,7 @@ public LocalDateTime getFirstStartTime() { } public void setFirstStartTime(LocalDateTime firstStartTime) { - this.firstSet.setStartTime(firstStartTime); + firstSet.setStartTime(firstStartTime); } public Long getSecondTestCaseRunId() { @@ -123,7 +123,7 @@ public Long getSecondTestCaseRunId() { } public void setSecondTestCaseRunId(Long secondTestCaseRunId) { - this.secondSet.setTestCaseRunId(secondTestCaseRunId); + secondSet.setTestCaseRunId(secondTestCaseRunId); } public Long getSecondMatrixRunId() { @@ -131,11 +131,11 @@ public Long getSecondMatrixRunId() { } public void setSecondMatrixRunId(Long secondMatrixRunId) { - this.secondSet.setMatrixRunId(secondMatrixRunId); + secondSet.setMatrixRunId(secondMatrixRunId); } public void setSecondStatus(StatusType secondStatus) { - this.secondSet.setStatus(secondStatus); + secondSet.setStatus(secondStatus); } public String getSecondMatrixName() { @@ -143,7 +143,7 @@ public String getSecondMatrixName() { } public void setSecondMatrixName(String secondMatrixName) { - this.secondSet.setMatrixName(secondMatrixName); + secondSet.setMatrixName(secondMatrixName); } public String getSecondFailReason() { @@ -151,7 +151,7 @@ public String getSecondFailReason() { } public void setSecondFailReason(String secondFailReason) { - this.secondSet.setFailReason(secondFailReason); + secondSet.setFailReason(secondFailReason); } public Map getSecondFailedActions() { @@ -159,7 +159,7 @@ public Map getSecondFailedActions() { } public void setSecondFailedActions(Map secondFailedActions) { - this.secondSet.setFailedActions(secondFailedActions); + secondSet.setFailedActions(secondFailedActions); } public String getSecondUserComment() { @@ -167,7 +167,7 @@ public String getSecondUserComment() { } public void setSecondUserComment(String secondUserComment) { - this.secondSet.setUserComment(secondUserComment); + secondSet.setUserComment(secondUserComment); } public String getSecondUserStatus() { @@ -175,7 +175,7 @@ public String getSecondUserStatus() { } public void setSecondUserStatus(String secondUserStatus) { - this.secondSet.setUserStatus(secondUserStatus); + secondSet.setUserStatus(secondUserStatus); } public LocalDateTime getSecondStartTime() { @@ -183,7 +183,7 @@ public LocalDateTime getSecondStartTime() { } public void setSecondStartTime(LocalDateTime secondStartTime) { - this.secondSet.setStartTime(secondStartTime); + secondSet.setStartTime(secondStartTime); } public Long getFirstTestCaseId() { @@ -191,7 +191,7 @@ public Long getFirstTestCaseId() { } public void setFirstTestCaseId(Long firstTestCaseId) { - this.firstSet.setTestCaseId(firstTestCaseId); + firstSet.setTestCaseId(firstTestCaseId); } public LocalDateTime getFirstFinishTime() { @@ -199,7 +199,7 @@ public LocalDateTime getFirstFinishTime() { } public void setFirstFinishTime(LocalDateTime firstFinishTime) { - this.firstSet.setFinishTime(firstFinishTime); + firstSet.setFinishTime(firstFinishTime); } public String getFirstRawTags() { @@ -207,7 +207,7 @@ public String getFirstRawTags() { } public void setFirstRawTags(String firstRawTags) { - this.firstSet.setRawTags(firstRawTags); + firstSet.setRawTags(firstRawTags); } public Integer getFirstRawHash() { @@ -215,7 +215,7 @@ public Integer getFirstRawHash() { } public void setFirstRawHash(Integer firstRawHash) { - this.firstSet.setRawHash(firstRawHash); + firstSet.setRawHash(firstRawHash); } public Long getSecondTestCaseId() { @@ -223,7 +223,7 @@ public Long getSecondTestCaseId() { } public void setSecondTestCaseId(Long secondTestCaseId) { - this.secondSet.setTestCaseId(secondTestCaseId); + secondSet.setTestCaseId(secondTestCaseId); } public LocalDateTime getSecondFinishTime() { @@ -231,7 +231,7 @@ public LocalDateTime getSecondFinishTime() { } public void setSecondFinishTime(LocalDateTime secondFinishTime) { - this.secondSet.setFinishTime(secondFinishTime); + secondSet.setFinishTime(secondFinishTime); } public String getSecondRawTags() { @@ -239,7 +239,7 @@ public String getSecondRawTags() { } public void setSecondRawTags(String secondRawTags) { - this.secondSet.setRawTags(secondRawTags); + secondSet.setRawTags(secondRawTags); } public Integer getSecondRawHash() { @@ -247,7 +247,7 @@ public Integer getSecondRawHash() { } public void setSecondRawHash(Integer secondRawHash) { - this.secondSet.setRawHash(secondRawHash); + secondSet.setRawHash(secondRawHash); } public StatusType getFirstStatus() { @@ -263,7 +263,7 @@ public String getFirstDescription() { } public void setFirstDescription(String firstDescription) { - this.firstSet.setDescription(firstDescription); + firstSet.setDescription(firstDescription); } public String getSecondDescription() { @@ -271,7 +271,7 @@ public String getSecondDescription() { } public void setSecondDescription(String secondDescription) { - this.secondSet.setDescription(secondDescription); + secondSet.setDescription(secondDescription); } public SfInstance getFirstSfInstance() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TestCasesDisplayMode.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TestCasesDisplayMode.java index 0f850bbb..cabdafcd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TestCasesDisplayMode.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/statistics/storage/reporting/TestCasesDisplayMode.java @@ -24,7 +24,7 @@ public enum TestCasesDisplayMode { private final String label; - private TestCasesDisplayMode(String label) { + TestCasesDisplayMode(String label) { this.label = label; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/AbstractHibernateStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/AbstractHibernateStorage.java index 57118173..8df670a3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/AbstractHibernateStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/AbstractHibernateStorage.java @@ -15,6 +15,9 @@ ******************************************************************************/ package com.exactpro.sf.embedded.storage; +import java.util.List; +import java.util.stream.Collectors; + import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; @@ -25,10 +28,6 @@ import com.exactpro.sf.storage.IStorage; import com.exactpro.sf.storage.impl.HibernateStorage; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - public abstract class AbstractHibernateStorage implements IHibernateStorage { private static final Logger logger = LoggerFactory.getLogger(AbstractHibernateStorage.class); @@ -76,16 +75,16 @@ public AbstractHibernateStorage(HibernateStorageSettings settings) { public void add(Object entity) { logger.debug("Try to add entity to statistic db:{}", entity); - - this.storage.add(entity); + + storage.add(entity); } public void update(Object entity) { logger.debug("Try to update entity to statistic db:{}", entity); - - this.storage.update(entity); + + storage.update(entity); } @@ -95,7 +94,7 @@ public void update(List entities) { logger.debug("Try to batch update entities to statistic db:{}", entities.stream().map(Object::toString) .collect(Collectors.joining(", "))); } - this.storage.batchUpdate(entities); + storage.batchUpdate(entities); } public synchronized void tearDown() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/HibernateStorageSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/HibernateStorageSettings.java index 5e0b6eb9..d90b3a01 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/HibernateStorageSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/storage/HibernateStorageSettings.java @@ -18,6 +18,7 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; @@ -82,8 +83,8 @@ public String settingsName() { } public void fillFromMap(Map options) throws Exception { - - for(Map.Entry entry : options.entrySet()) { + + for(Entry entry : options.entrySet()) { if(entry.getKey().startsWith(storagePrefix)) { @@ -101,10 +102,10 @@ public Map toMap() throws Exception { Map description = BeanUtils.describe(this); Map result = new HashMap(); - - for(Map.Entry entry : description.entrySet()) { - - if(!entry.getKey().equals("class")) { + + for(Entry entry : description.entrySet()) { + + if(!"class".equals(entry.getKey())) { result.put(storagePrefix + entry.getKey(), entry.getValue()); @@ -117,28 +118,24 @@ public Map toMap() throws Exception { } public String buildConnectionUrl() { - - String format; - + StringBuilder builder = new StringBuilder(); + + builder.append(protocol); + builder.append(':'); + builder.append(subProtocol); + builder.append("://"); + builder.append(host); + builder.append(':'); + builder.append(port); + builder.append('/'); + builder.append(dbName); + if(StringUtils.isNotEmpty(connectionOptionsQuery)) { - - format = "%s:%s://%s:%s/%s?%s"; - - } else { - - format = "%s:%s://%s:%s/%s"; - + builder.append('?'); + builder.append(connectionOptionsQuery); } - - return String.format(format, - protocol, - subProtocol, - - host, - port, - dbName, - connectionOptionsQuery); - + + return builder.toString(); } @@ -233,31 +230,31 @@ public void setDbms(String dbms) { @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("HibernateStorageSettings", this.protocol) - .append("subProtocol", this.subProtocol) - .append("host", this.host) - .append("port", this.port) - .append("dbName", this.dbName) - .append("connectionOptionsQuery", this.connectionOptionsQuery) - .append("username", this.username) + .append("HibernateStorageSettings", protocol) + .append("subProtocol", subProtocol) + .append("host", host) + .append("port", port) + .append("dbName", dbName) + .append("connectionOptionsQuery", connectionOptionsQuery) + .append("username", username) .append("password", "***") - .append("dialect", this.dialect) - .append("driverClass", this.driverClass).toString(); + .append("dialect", dialect) + .append("driverClass", driverClass).toString(); } @Override public int hashCode() { return new HashCodeBuilder() - .append(this.connectionOptionsQuery) - .append(this.dbName) - .append(this.dialect) - .append(this.driverClass) - .append(this.password) - .append(this.protocol) - .append(this.subProtocol) - .append(this.host) - .append(this.port) - .append(this.username).toHashCode(); + .append(connectionOptionsQuery) + .append(dbName) + .append(dialect) + .append(driverClass) + .append(password) + .append(protocol) + .append(subProtocol) + .append(host) + .append(port) + .append(username).toHashCode(); } @Override @@ -268,17 +265,17 @@ public boolean equals(Object o) { HibernateStorageSettings that = (HibernateStorageSettings)o; return new EqualsBuilder() - .append(this.dbms, that.dbms) - .append(this.connectionOptionsQuery, that.connectionOptionsQuery) - .append(this.dbName, that.dbName) - .append(this.dialect, that.dialect) - .append(this.driverClass, that.driverClass) - .append(this.password, that.password) - .append(this.protocol, that.protocol) - .append(this.subProtocol, that.subProtocol) - .append(this.host, that.host) - .append(this.port, that.port) - .append(this.username, that.username).isEquals(); + .append(dbms, that.dbms) + .append(connectionOptionsQuery, that.connectionOptionsQuery) + .append(dbName, that.dbName) + .append(dialect, that.dialect) + .append(driverClass, that.driverClass) + .append(password, that.password) + .append(protocol, that.protocol) + .append(subProtocol, that.subProtocol) + .append(host, that.host) + .append(port, that.port) + .append(username, that.username).isEquals(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/UpdateService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/UpdateService.java index 31afeebf..71ca766d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/UpdateService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/UpdateService.java @@ -37,6 +37,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.HierarchicalConfiguration; +import org.apache.commons.configuration.XMLConfiguration; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.configuration.workspace.FolderType; import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; @@ -50,12 +57,6 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.HierarchicalConfiguration; -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class UpdateService implements IEmbeddedService { private static final Logger logger = LoggerFactory.getLogger(UpdateService.class); @@ -187,7 +188,7 @@ public synchronized void update() { throw new IllegalStateException("Can't execute update in current state: " + serviceStatus); } - if (this.updating) { + if(updating) { throw new IllegalStateException("Update process already started"); } logger.info("Start updating..."); @@ -304,8 +305,8 @@ public synchronized void tearDown() { logger.info("Tear down"); cancelCheckUpdateTask(); - if (this.updateFuture != null) { - this.updateFuture.cancel(true); + if(updateFuture != null) { + updateFuture.cancel(true); this.updateFuture = null; } @@ -330,11 +331,11 @@ public String getErrorMsg() { } private synchronized void cancelCheckUpdateTask() { - if (this.updateCheckerFuture != null) { + if(updateCheckerFuture != null) { logger.info("Cancelling update checking task..."); - this.updateCheckerFuture.cancel(true); + updateCheckerFuture.cancel(true); try { - this.updateCheckerFuture.get(); + updateCheckerFuture.get(); } catch (CancellationException e) { logger.info("Update checker task was cancelled", e); } catch (InterruptedException e) { @@ -455,9 +456,9 @@ private void updateFailed(Throwable e) { public static class ComponentUpdateInfo { - private String name; + private final String name; - private String version; + private final String version; @JsonCreator public ComponentUpdateInfo(@JsonProperty(value = "name", required = true) String name, diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/configuration/UpdateServiceSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/configuration/UpdateServiceSettings.java index a85dd363..eca87e84 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/configuration/UpdateServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/embedded/updater/configuration/UpdateServiceSettings.java @@ -19,6 +19,7 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.apache.commons.beanutils.BeanUtils; @@ -75,7 +76,7 @@ public String settingsName() { @Override public void fillFromMap(Map options) throws Exception { - for(Map.Entry entry : options.entrySet()) { + for(Entry entry : options.entrySet()) { if(entry.getKey().startsWith(STORAGE_PREFIX)) { BeanUtils.setProperty(this, entry.getKey().replace(STORAGE_PREFIX, ""), entry.getValue()); } @@ -88,7 +89,7 @@ public Map toMap() throws Exception { Map description = BeanUtils.describe(this); Map result = new HashMap<>(); - for(Map.Entry entry : description.entrySet()) { + for(Entry entry : description.entrySet()) { result.put(STORAGE_PREFIX + entry.getKey(), entry.getValue()); } return result; @@ -96,17 +97,21 @@ public Map toMap() throws Exception { public UpdateServiceSettings clone() { UpdateServiceSettings clone = new UpdateServiceSettings(); - clone.host = this.host; - clone.port = this.port; - clone.checkUpdateTimeout = this.checkUpdateTimeout; - clone.timeUnit = this.timeUnit; + clone.host = host; + clone.port = port; + clone.checkUpdateTimeout = checkUpdateTimeout; + clone.timeUnit = timeUnit; return clone; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(this == o) { + return true; + } + if(o == null || getClass() != o.getClass()) { + return false; + } UpdateServiceSettings that = (UpdateServiceSettings) o; return new EqualsBuilder() .append(host, that.host) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/AbstractSettingsProxy.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/AbstractSettingsProxy.java index feda30ec..a648c18b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/AbstractSettingsProxy.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/AbstractSettingsProxy.java @@ -41,30 +41,26 @@ public AbstractSettingsProxy(ICommonSettings settings) { this.descriptors = new HashMap<>(); for (PropertyDescriptor propertyDescriptor : array) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { - this.descriptors.put(propertyDescriptor.getName(), propertyDescriptor); + descriptors.put(propertyDescriptor.getName(), propertyDescriptor); } } } @Override public Set getParameterNames() { - return this.descriptors.keySet(); + return descriptors.keySet(); } @Override public Class getParameterType(String name) { - PropertyDescriptor descriptor = this.descriptors.get(name); - if (descriptor != null) { - return descriptor.getPropertyType(); - } - - return null; + PropertyDescriptor descriptor = descriptors.get(name); + return descriptor != null ? descriptor.getPropertyType() : null; } @SuppressWarnings("unchecked") @Override public T getParameterValue(String name) { - PropertyDescriptor descriptor = this.descriptors.get(name); + PropertyDescriptor descriptor = descriptors.get(name); if (descriptor != null) { try { return (T) descriptor.getReadMethod().invoke(settings); @@ -78,7 +74,7 @@ public T getParameterValue(String name) { @Override public void setParameterValue(String name, Object value) { - PropertyDescriptor descriptor = this.descriptors.get(name); + PropertyDescriptor descriptor = descriptors.get(name); if (descriptor != null) { try { descriptor.getWriteMethod().invoke(settings, value); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/IMessageFactoryProxy.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/IMessageFactoryProxy.java index 1162ed9d..24fd06d7 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/IMessageFactoryProxy.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/IMessageFactoryProxy.java @@ -15,6 +15,9 @@ ******************************************************************************/ package com.exactpro.sf.externalapi; +import java.util.Collections; +import java.util.List; + import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.configuration.suri.SailfishURI; @@ -33,9 +36,9 @@ public interface IMessageFactoryProxy { /** * @deprecated - this method has been deprecated, will be REMOVED in future releases - * Please set true for useStrictMessage in {@link com.exactpro.sf.externalapi.ServiceFactory} for using strict messages in ExternalAPI + * Please set true for useStrictMessage in {@link ServiceFactory} for using strict messages in ExternalAPI * - * Creates instance of {@link com.exactpro.sf.common.messages.IMessage + * Creates instance of {@link IMessage * IMessage} with name passed in arguments. Strict message tries to convert * addition value to target type otherwise throws {@link RuntimeException}. *

@@ -45,7 +48,7 @@ public interface IMessageFactoryProxy { *

* If added value is single value but field in dictionary is collection - * implementation wrapped single value in - * {@link java.util.Collections#checkedList(java.util.List, Class) CheckedList}. + * {@link Collections#checkedList(List, Class) CheckedList}. * All collection added in this implementation also wrapped in this type of * {@code List} * diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactory.java index 316eacf2..5101972c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactory.java @@ -122,7 +122,7 @@ public class ServiceFactory implements IServiceFactory { /** * Creates ServiceFactory with default parameters. - * @param workspaceLayers the sequence of workspace layers {@link com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher} + * @param workspaceLayers the sequence of workspace layers {@link IWorkspaceDispatcher} * @throws IOException * @throws WorkspaceSecurityException * @throws SailfishURIException @@ -135,7 +135,7 @@ public ServiceFactory(File... workspaceLayers) throws IOException, WorkspaceSecu /** * Creates ServiceFactory with default parameters. - * @param workspaceLayers the sequence of workspace layers {@link com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher} + * @param workspaceLayers the sequence of workspace layers {@link IWorkspaceDispatcher} * @param useResourceLayer if true resource layer '{@link #ROOT_PACKAGE}' will be plugged * @throws IOException * @throws WorkspaceSecurityException @@ -182,7 +182,7 @@ public ServiceFactory(int minThreads, int maxThreads, int scheduledThreads, bool this.wd = createWorkspaceDispatcher(useResourceLayer, workspaceLayers); this.staticServiceManager = new DefaultStaticServiceManager(); this.utilManager = new UtilityManager(); - if (useStrictMessages) { + if(useStrictMessages) { this.dictionaryManager = new StrictDictionaryManager(wd, utilManager); } else { this.dictionaryManager = new DictionaryManager(wd, utilManager); @@ -201,11 +201,11 @@ public ServiceFactory(int minThreads, int maxThreads, int scheduledThreads, bool disposables.add(taskExecutor); IMessageStorage emptyMessageStorage = new FakeMessageStorage(); IServiceStorage emptyServiceStorage = new EmptyServiceStorage(); - this.messageFactory = new DictionaryMessageFactory(this.dictionaryManager); + this.messageFactory = new DictionaryMessageFactory(dictionaryManager); this.emptyServiceContext = new DefaultServiceContext(dictionaryManager, emptyMessageStorage, emptyServiceStorage, loggingConfigurator, taskExecutor, dataManager, wd); - this.serviceTypes = new HashSet<>(Arrays.asList(this.staticServiceManager.getServiceURIs())); + this.serviceTypes = new HashSet<>(Arrays.asList(staticServiceManager.getServiceURIs())); } /** @@ -226,9 +226,9 @@ public ServiceFactory(int minThreads, int maxThreads, int scheduledThreads, File @Override public void close() throws Exception { - while (!this.disposables.isEmpty()) { + while(!disposables.isEmpty()) { try { - this.disposables.remove().dispose(); + disposables.remove().dispose(); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } @@ -236,12 +236,12 @@ public void close() throws Exception { } @Override - public IServiceProxy createService(InputStream setting, final IServiceListener listener) throws ServiceFactoryException { + public IServiceProxy createService(InputStream setting, IServiceListener listener) throws ServiceFactoryException { List importResults = new ArrayList<>(); List errors = new ArrayList<>(); try { - this.marshalManager.unmarshalServices(setting, false, importResults, errors); + marshalManager.unmarshalServices(setting, false, importResults, errors); } catch (RuntimeException e) { throw new ServiceFactoryException("Problem during service configuration reading", e); } @@ -251,7 +251,7 @@ public IServiceProxy createService(InputStream setting, final IServiceListener l if (!errors.isEmpty() || importResults.size() != 1) { throw new ServiceFactoryException("Unmarshalling the settings set failed, reason " + errors); } - final ServiceDescription desc = importResults.get(0); + ServiceDescription desc = importResults.get(0); ServiceSettingsProxy settingsProxy = new ServiceSettingsProxy(desc.getSettings()); return createService(desc.getType(), settingsProxy, ServiceName.parse(desc.getName()), listener); } @@ -269,12 +269,12 @@ public Set getServiceTypes() { @Override public Set getDictionaries() { - return this.dictionaryManager.getDictionaryURIs(); + return dictionaryManager.getDictionaryURIs(); } @Override public IDictionaryStructure getDictionary(SailfishURI uri) { - return this.dictionaryManager.getDictionary(uri); + return dictionaryManager.getDictionary(uri); } @Override @@ -282,14 +282,14 @@ public IMessageFactoryProxy getMessageFactory(SailfishURI serviceType) { if (!serviceTypes.contains(serviceType)) { throw new IllegalArgumentException("Unknown service type " + serviceType); } - return this.messageFactory; + return messageFactory; } @Override public SailfishURI registerDictionary(String title, InputStream dictionary, boolean overwrite) throws ServiceFactoryException { try { IDictionaryRegistrator registrator = dictionaryManager.registerDictionary(title, overwrite); - try (OutputStream os = new BufferedOutputStream(new FileOutputStream(this.wd.getFile(FolderType.ROOT, registrator.getPath())))) { + try(OutputStream os = new BufferedOutputStream(new FileOutputStream(wd.getFile(FolderType.ROOT, registrator.getPath())))) { IOUtils.copy(dictionary, os); } return registrator.registrate(); @@ -323,7 +323,7 @@ private IServiceProxy createService(SailfishURI serviceType, ServiceSettingsProx IInitiatorService service; try { - IService tmp = this.staticServiceManager.createService(serviceType); + IService tmp = staticServiceManager.createService(serviceType); if (!(tmp instanceof IInitiatorService)) { throw new ServiceFactoryException("Only IInitiator service supported"); } @@ -332,14 +332,13 @@ private IServiceProxy createService(SailfishURI serviceType, ServiceSettingsProx throw new ServiceFactoryException(String.format("Failed to instantiate service with SailfishURI %s", serviceType), e); } - - if (DISABLED == service.getStatus()) { + if(service.getStatus() == DISABLED) { throw new ServiceFactoryException( String.format("Could not create service %s. Target service '%s' is not presented in plug-ins", serviceType, serviceType)); } if (settingsProxy == null) { - IServiceSettings settings = this.staticServiceManager.createServiceSettings(serviceType); + IServiceSettings settings = staticServiceManager.createServiceSettings(serviceType); settingsProxy = new ServiceSettingsProxy(settings); } @@ -361,7 +360,7 @@ public void storeMessage(IMessage message) { super.storeMessage(message); if (message.getMetaData().isRejected()) { ServiceHandlerRoute route = message.getMetaData().isAdmin() ? ServiceHandlerRoute.FROM_ADMIN : ServiceHandlerRoute.FROM_APP; - this.listener.onMessage(serviceProxy, message, true, route); + listener.onMessage(serviceProxy, message, true, route); } } } @@ -415,10 +414,10 @@ public ListenerServiceMonitor(IServiceProxy service, IServiceListener listener) @Override public void onEvent(ServiceEvent event) { - this.listener.onEvent(this.service, event); + listener.onEvent(service, event); } - }; + } private static class IntServiceHandler extends AbstractServiceHandler { @@ -432,29 +431,29 @@ public IntServiceHandler(IServiceProxy service, IServiceListener listener) { @Override public void sessionOpened(ISession session) throws ServiceHandlerException { - listener.sessionOpened(this.service); + listener.sessionOpened(service); } @Override public void sessionIdle(ISession session, IdleStatus status) throws ServiceHandlerException { - listener.sessionIdle(this.service, status); + listener.sessionIdle(service, status); } @Override public void sessionClosed(ISession session) throws ServiceHandlerException { - listener.sessionClosed(this.service); + listener.sessionClosed(service); } @Override public void putMessage(ISession session, ServiceHandlerRoute route, IMessage message) throws ServiceHandlerException { - listener.onMessage(this.service, message, false, route); + listener.onMessage(service, message, false, route); } @Override public void exceptionCaught(ISession session, Throwable cause) { - listener.exceptionCaught(this.service, cause); + listener.exceptionCaught(service, cause); } - }; + } private static class ServiceProxy implements IServiceProxy { @@ -489,17 +488,17 @@ public ServiceProxy(ServiceName name, IInitiatorService service, SailfishURI sUR @Override public void stop() { - if (STARTED.equals(service.getStatus()) || WARNING.equals(service.getStatus())) { + if(service.getStatus() == STARTED || service.getStatus() == WARNING) { service.dispose(); } else { - throw new IllegalStateException(String.format("Service %s not started", this.name)); + throw new IllegalStateException(String.format("Service %s not started", name)); } } @Override public void start() { if (checkServiceState(service.getStatus(), ERROR, CREATED, DISPOSED, INITIALIZED)) { - this.service.init(this.serviceContext, this.serviceMonitor, this.serviceHandler, this.settingsProxy.getSettings(), this.name); + service.init(serviceContext, serviceMonitor, serviceHandler, settingsProxy.getSettings(), name); service.start(); } else { throw new IllegalStateException(String.format("Service in illegal statate: %s", service.getStatus())); @@ -509,7 +508,7 @@ public void start() { @Override public IMessage send(IMessage message) throws InterruptedException { - if (STARTED.equals(service.getStatus()) || WARNING.equals(service.getStatus())) { + if(service.getStatus() == STARTED || service.getStatus() == WARNING) { IInitiatorService xService = service; xService.getSession().send(message); } else { @@ -537,7 +536,7 @@ public SailfishURI getType() { @Override public ISettingsProxy getSettings() { - return this.settingsProxy; + return settingsProxy; } private boolean checkServiceState(ServiceStatus actual, ServiceStatus... expected) { @@ -554,11 +553,11 @@ public ServiceSettingsProxy(IServiceSettings settings) { public IServiceSettings getSettings() { try { - IServiceSettings result = (IServiceSettings) this.settings.getClass().newInstance(); + IServiceSettings result = (IServiceSettings)settings.getClass().newInstance(); Object value = null; for (PropertyDescriptor descriptor : descriptors.values()) { - value = descriptor.getReadMethod().invoke(this.settings); + value = descriptor.getReadMethod().invoke(settings); descriptor.getWriteMethod().invoke(result, value); } @@ -570,12 +569,12 @@ public IServiceSettings getSettings() { @Override public SailfishURI getDictionary() { - return ((IServiceSettings) this.settings).getDictionaryName(); + return ((IServiceSettings)settings).getDictionaryName(); } @Override public void setDictionary(SailfishURI dictionary) { - ((IServiceSettings) this.settings).setDictionaryName(dictionary); + ((IServiceSettings)settings).setDictionaryName(dictionary); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactoryBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactoryBuilder.java index e8914e69..00cac2df 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactoryBuilder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/ServiceFactoryBuilder.java @@ -29,11 +29,11 @@ public class ServiceFactoryBuilder { private final File[] workspaceLayers; - private int minThreads = 0; + private int minThreads; private int maxThreads = 350; private int scheduledThreads = Runtime.getRuntime().availableProcessors() * 2; - private boolean useResourceLayer = false; - private boolean useStrictMessages = false; + private boolean useResourceLayer; + private boolean useStrictMessages; public ServiceFactoryBuilder(File... workspaceLayers) { this.workspaceLayers = Objects.requireNonNull(workspaceLayers, "'Workspace layers' parameter"); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/impl/StrictDictionaryManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/impl/StrictDictionaryManager.java index 1ab5559e..323dba63 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/impl/StrictDictionaryManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/externalapi/impl/StrictDictionaryManager.java @@ -28,7 +28,7 @@ public class StrictDictionaryManager extends DictionaryManager { - private final static Logger logger = LoggerFactory.getLogger(StrictDictionaryManager.class); + private static final Logger logger = LoggerFactory.getLogger(StrictDictionaryManager.class); public StrictDictionaryManager(IWorkspaceDispatcher workspaceDispatcher, UtilityManager utilityManager) { super(workspaceDispatcher, utilityManager); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/HelpBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/HelpBuilder.java index cad60ec6..907c3bd2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/HelpBuilder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/HelpBuilder.java @@ -151,7 +151,7 @@ public class HelpBuilder { public static final String HTML = ".html"; private static final String TEMPLATE_PACKAGE_PATH = "/com/exactpro/sf/help/template"; - private static final String[] PAGE_RESOURCES = new String[] { "static-help.css", "static-help.js", "ui-bg_flat_75_ffffff_40x100.png", + private static final String[] PAGE_RESOURCES = { "static-help.css", "static-help.js", "ui-bg_flat_75_ffffff_40x100.png", "ui-icons_c02669_256x240.png", "SFicon.png" }; private final HelpTemplateWrapperFactory templateWrapperFactory; @@ -301,7 +301,7 @@ public HelpBuilder(IWorkspaceDispatcher wd, IDictionaryManager dictionaryManager private void build(String rootName, String rootAlias) throws IOException, SailfishURIException, TemplateException { - if (this.actionManager == null) { + if(actionManager == null) { throw new UnsupportedOperationException(); } @@ -380,7 +380,7 @@ private void buildActions(IVersion plugin, HelpJsonContainer jsonParent) throws for (ActionClass loadedAction : unmarshalledActions) { if (loadedAction.getPlugin().equals(plugin)) { - validActions.add((loadedAction)); + validActions.add(loadedAction); } } @@ -636,7 +636,7 @@ private List fillFieldsAndMessages(Method method, ActionClass ac for (Method actionMethod : actionClass.getClassMethods()) { if (method.getName().equals(actionMethod.getName()) && actionMethod.getParameterTypes().length == 2) { FieldsDescriber.describeFields(fields, actionMethod.getParameterTypes()[1]); - break; + return fields; } } return fields; @@ -659,7 +659,7 @@ private void buildFieldsAndMessages(PluginHelpContainer parentObject, List parentObject, List= 2 && superClasses.get(1).getCanonicalName().equals("quickfix.Message"); + boolean isFixMessage = superClasses.size() >= 2 && "quickfix.Message".equals(superClasses.get(1).getCanonicalName()); + //noinspection SimplifiableIfStatement if ((isBaseMessage || isFixMessage) && method.isAnnotationPresent(MessageDirection.class)) { return false; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityName.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityName.java index 5a59f855..5c11e7f9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityName.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityName.java @@ -24,14 +24,14 @@ public enum HelpEntityName { PROVIDERS("Matrix providers"), VALIDATORS("Validators"), PREPROCESSORS("Preprocessors"); - - private String value; - - private HelpEntityName(String value) { + + private final String value; + + HelpEntityName(String value) { this.value = value; } public String getValue() { - return this.value; + return value; } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityType.java index 5c6b7c3f..034b1f40 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/HelpEntityType.java @@ -24,5 +24,5 @@ public enum HelpEntityType { FIELD, MESSAGE, COMPONENT, - ERROR; + ERROR } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/describers/FieldsDescriber.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/describers/FieldsDescriber.java index 78060c36..7f2cb780 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/describers/FieldsDescriber.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/describers/FieldsDescriber.java @@ -18,6 +18,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -79,7 +80,7 @@ public static void describeFields(List fields, Class messageC try { Object obj = paramClass.newInstance(); for (Field c : paramClass.getDeclaredFields()) { - if (c.getName().equals("FIELD")) { + if("FIELD".equals(c.getName())) { newField.setTag(c.get(obj).toString()); break; } @@ -123,7 +124,7 @@ public static void describeFields(List fields, Class messageC } } - if (java.util.HashMap.class.equals(messageClazz)) { + if (HashMap.class.equals(messageClazz)) { return; } @@ -159,35 +160,23 @@ private static void findGettersAndSetters(Method[] methods, Map for (Method m : methods) { if (m.getName().startsWith("get") && m.getParameterTypes().length == 0) { String fname = m.getName().substring(3); - if (getSeen.containsKey(fname)) { - getSeen.put(fname, getSeen.get(fname) + 1); - } else { - getSeen.put(fname, 1); - } + getSeen.merge(fname, 1, Integer::sum); if (!paramTypes.containsKey(fname)) { paramTypes.put(fname, m.getReturnType()); } } // FIX implementation - else if (m.getName().equals("set") && m.getParameterTypes().length == 1) { + else if("set".equals(m.getName()) && m.getParameterTypes().length == 1) { String fname = m.getParameterTypes()[0].getSimpleName(); if (!fname.isEmpty()) { - if (setSeen.containsKey(fname)) { - setSeen.put(fname, setSeen.get(fname) + 1); - } else { - setSeen.put(fname, 1); - } + setSeen.merge(fname, 1, Integer::sum); } } // generic implementation else if ((m.getName().startsWith("set") || m.getName().startsWith("add")) && m.getParameterTypes().length == 1) { String fname = m.getName().substring(3); if (!fname.isEmpty()) { - if (setSeen.containsKey(fname)) { - setSeen.put(fname, setSeen.get(fname) + 1); - } else { - setSeen.put(fname, 1); - } + setSeen.merge(fname, 1, Integer::sum); if (m.getName().startsWith("add")) { paramTypes.put(fname, m.getParameterTypes()[0]); } @@ -231,8 +220,9 @@ private static void describeField(Class clazz, com.exactpro.sf.help.helpmarsh try { Object obj = clazz.newInstance(); for (Field c : clazz.getDeclaredFields()) { - if (!(c.getName().equals("FIELD") || c.getName().equals("serialVersionUID") || (c.getName().equals("MSGTYPE") && c.get(obj) - .equals("")))) { + if(!("FIELD".equals(c.getName()) || + "serialVersionUID".equals(c.getName()) || + ("MSGTYPE".equals(c.getName()) && "".equals(c.get(obj))))) { String valueString = c.getName() + "=" + c.get(obj); validValues.add(valueString); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/FieldJsonContainer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/FieldJsonContainer.java index 190b20f4..7962058b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/FieldJsonContainer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/FieldJsonContainer.java @@ -17,10 +17,12 @@ import com.exactpro.sf.help.helpmarshaller.HelpEntityType; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.As; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import java.util.List; -@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") +@JsonTypeInfo(use= Id.CLASS, include= As.PROPERTY, property="@class") public class FieldJsonContainer extends HelpJsonContainer{ private String javaType; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/HelpJsonContainer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/HelpJsonContainer.java index 2652d7f4..1157ad38 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/HelpJsonContainer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/HelpJsonContainer.java @@ -20,8 +20,10 @@ import com.exactpro.sf.help.helpmarshaller.HelpEntityName; import com.exactpro.sf.help.helpmarshaller.HelpEntityType; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.As; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") +@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "@class") public class HelpJsonContainer { public static final String PLUGIN_ICON = "ui-icon-suitcase"; @@ -103,7 +105,7 @@ public List getChildNodes() { } public void addChild(HelpJsonContainer child) { - this.childNodes.add(child); + childNodes.add(child); } public String getFilePath() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/MethodJsonContainer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/MethodJsonContainer.java index e1b3a5e1..e23cb518 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/MethodJsonContainer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/MethodJsonContainer.java @@ -17,8 +17,10 @@ import com.exactpro.sf.help.helpmarshaller.HelpEntityType; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.As; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") +@JsonTypeInfo(use= Id.CLASS, include= As.PROPERTY, property="@class") public class MethodJsonContainer extends HelpJsonContainer { private Boolean isUtilMethod; @@ -34,9 +36,6 @@ public MethodJsonContainer(String name, String htmlPath, String icon, HelpEntity } public Boolean getIsUtilMethod() { - if (isUtilMethod == null) { - return false; - } - return isUtilMethod; + return isUtilMethod != null && isUtilMethod; } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/URIJsonContainer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/URIJsonContainer.java index 6cf8abe5..ee0d17a9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/URIJsonContainer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/help/helpmarshaller/jsoncontainers/URIJsonContainer.java @@ -18,8 +18,10 @@ import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.help.helpmarshaller.HelpEntityType; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.As; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") +@JsonTypeInfo(use= Id.CLASS, include= As.PROPERTY, property="@class") public class URIJsonContainer extends HelpJsonContainer{ private SailfishURI uri; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/matrixhandlers/MatrixProviderHolder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/matrixhandlers/MatrixProviderHolder.java index 2ea555d9..3aad4d9e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/matrixhandlers/MatrixProviderHolder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/matrixhandlers/MatrixProviderHolder.java @@ -37,12 +37,10 @@ public class MatrixProviderHolder { private final Map uriToFactory = new HashMap<>(); - public MatrixProviderHolder() {} - public void registerMatrixProvider(IVersion version, IMatrixProviderFactory factory) { try { SailfishURI matrixProviderURI = new SailfishURI(version.getAlias(), null, factory.getAlias()); - IMatrixProviderFactory currentFactory = this.uriToFactory.put(matrixProviderURI, factory); + IMatrixProviderFactory currentFactory = uriToFactory.put(matrixProviderURI, factory); if (currentFactory != null && !currentFactory.getClass().equals(factory.getClass())) { logger.warn("Duplicate Matrix provider registration {}", matrixProviderURI); @@ -67,7 +65,7 @@ public Set getMatrixProviderFactoriesByPlugin(IVersion v } public Set getProviderURIs() { - return Collections.unmodifiableSet(this.uriToFactory.keySet()); + return Collections.unmodifiableSet(uriToFactory.keySet()); } public Map getMatrixProviders(String link, SailfishURI matrixProviderURI) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AbstractScriptRunner.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AbstractScriptRunner.java index 8195dc26..d330f841 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AbstractScriptRunner.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AbstractScriptRunner.java @@ -32,7 +32,6 @@ import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; -import com.exactpro.sf.scriptrunner.impl.jsonreport.JsonReport; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.RandomStringUtils; @@ -52,7 +51,6 @@ import com.exactpro.sf.aml.generator.Alert; import com.exactpro.sf.aml.generator.AlertType; import com.exactpro.sf.aml.generator.GeneratedScript; -import com.exactpro.sf.aml.generator.JavaValidator; import com.exactpro.sf.center.IDisposable; import com.exactpro.sf.center.ISFContext; import com.exactpro.sf.common.adapting.IAdapterManager; @@ -68,12 +66,15 @@ import com.exactpro.sf.embedded.statistics.StatisticsService; import com.exactpro.sf.embedded.statistics.entities.Tag; import com.exactpro.sf.scriptrunner.EnvironmentSettings.ReportOutputFormat; +import com.exactpro.sf.scriptrunner.ScriptProgress.IScriptRunProgressListener; import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptState; +import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptStatus; import com.exactpro.sf.scriptrunner.actionmanager.IActionManager; import com.exactpro.sf.scriptrunner.impl.BroadcastScriptReport; import com.exactpro.sf.scriptrunner.impl.ScriptReportWithLogs; import com.exactpro.sf.scriptrunner.impl.StatisticScriptReport; import com.exactpro.sf.scriptrunner.impl.htmlreport.HtmlReport; +import com.exactpro.sf.scriptrunner.impl.jsonreport.JsonReport; import com.exactpro.sf.scriptrunner.junit40.SFJUnitRunner; import com.exactpro.sf.scriptrunner.languagemanager.ILanguageFactory; import com.exactpro.sf.scriptrunner.languagemanager.LanguageManager; @@ -84,15 +85,15 @@ public abstract class AbstractScriptRunner implements IDisposable { - private final static Logger logger = LoggerFactory.getLogger(AbstractScriptRunner.class); + private static final Logger logger = LoggerFactory.getLogger(AbstractScriptRunner.class); - protected final static String LS = System.getProperty("line.separator"); - protected final static String PACKAGE_NAME = "com.exactpro.sf.testscript"; - protected final static int DEFAULT_TIMEOUT = 1000; - protected final static String forbiddenChars = " ?#;"; + protected static final String LS = System.getProperty("line.separator"); + protected static final String PACKAGE_NAME = "com.exactpro.sf.testscript"; + protected static final int DEFAULT_TIMEOUT = 1000; + protected static final String forbiddenChars = " ?#;"; protected final List listeners; - protected final ScriptProgress.IScriptRunProgressListener progressListener; + protected final IScriptRunProgressListener progressListener; protected final IPauseListener pauseListener; protected final IScriptRunListener stateListener; @@ -104,7 +105,7 @@ public abstract class AbstractScriptRunner implements IDisposable { protected volatile State runnerState; protected volatile boolean isDisposing; - protected volatile boolean shutdown = false; + protected volatile boolean shutdown; protected final SimpleDateFormat scriptFolderSuffix; protected final Map testScripts; protected final Deque addedTestScripts; @@ -114,38 +115,38 @@ public abstract class AbstractScriptRunner implements IDisposable { protected Thread tScriptCompiler; protected Thread tScriptExecutor; - protected final static Date startDate = new Date(); + protected static final Date startDate = new Date(); private final ScriptRunnerSettings settings; private final PreprocessorLoader preprocessorLoader; private final ValidatorLoader validatorLoader; - private StatisticsService statisticsService; - private IEnvironmentManager environmentManager; - private ITestScriptStorage testScriptStorage; - private IAdapterManager adapterManager; - private IStaticServiceManager staticServiceManager; - private String compilerClassPath; + private final StatisticsService statisticsService; + private final IEnvironmentManager environmentManager; + private final ITestScriptStorage testScriptStorage; + private final IAdapterManager adapterManager; + private final IStaticServiceManager staticServiceManager; + private final String compilerClassPath; protected enum State { - INIT, DISPOSING, DISPOSED; + INIT, DISPOSING, DISPOSED } public AbstractScriptRunner( - final IWorkspaceDispatcher wd, - final IDictionaryManager dictionaryManager, - final IActionManager actionManager, - final IUtilityManager utilityManager, - final LanguageManager languageManager, - final PreprocessorLoader preprocessorLoader, - final ValidatorLoader validatorLoader, - final ScriptRunnerSettings settings, - final StatisticsService statisticsService, - final IEnvironmentManager environmentManager, - final ITestScriptStorage testScriptStorage, - final IAdapterManager adapterManager, - final IStaticServiceManager staticServiceManager, - final String compilerClassPath) { + IWorkspaceDispatcher wd, + IDictionaryManager dictionaryManager, + IActionManager actionManager, + IUtilityManager utilityManager, + LanguageManager languageManager, + PreprocessorLoader preprocessorLoader, + ValidatorLoader validatorLoader, + ScriptRunnerSettings settings, + StatisticsService statisticsService, + IEnvironmentManager environmentManager, + ITestScriptStorage testScriptStorage, + IAdapterManager adapterManager, + IStaticServiceManager staticServiceManager, + String compilerClassPath) { this.workspaceDispatcher = wd; this.dictionaryManager = dictionaryManager; @@ -189,7 +190,7 @@ public AbstractScriptRunner( } public TestScriptDescription getTestScriptDescription(long id) { - return this.testScripts.get(id); + return testScripts.get(id); } public long enqueueScript(String scriptSettingsPath, String scriptMatrixPath, String matrixDescription, @@ -206,7 +207,7 @@ public long enqueueScript(String scriptSettingsPath, String scriptMatrixPath, St // copy files: WorkFolderPaths workFolderPaths = copyFilesToWorkFolder(matrixFileName, scriptMatrixPath, scriptSettingsPath, workFolder); - TestScriptDescription scriptDescription = new TestScriptDescription(this.stateListener, new Date(), + TestScriptDescription scriptDescription = new TestScriptDescription(stateListener, new Date(), scriptMatrixPath, scriptSettingsPath, workFolderPaths.getMatrixPath(), @@ -227,7 +228,7 @@ public long enqueueScript(String scriptSettingsPath, String scriptMatrixPath, St tags, staticVariables); - scriptDescription.setStatus(TestScriptDescription.ScriptStatus.NONE); + scriptDescription.setStatus(ScriptStatus.NONE); scriptDescription.setLanguageURI(languageURI); IScriptProgress scriptProgress = new ScriptProgress(scriptDescription.getId(), progressListener); @@ -250,7 +251,7 @@ public long enqueueScript(String scriptSettingsPath, String scriptMatrixPath, St BroadcastScriptReport aggregateReport = new BroadcastScriptReport(aggregateReportListeners); - reportListeners.add(new ScriptReportWithLogs(aggregateReport, this.settings.getExcludedMessages())); + reportListeners.add(new ScriptReportWithLogs(aggregateReport, settings.getExcludedMessages())); // user-defined listeners if (userListeners != null) { reportListeners.addAll(userListeners); @@ -268,18 +269,17 @@ public long enqueueScript(String scriptSettingsPath, String scriptMatrixPath, St scriptDescription.setContext(context); - - this.testScripts.put(scriptDescription.getId(), scriptDescription); + testScripts.put(scriptDescription.getId(), scriptDescription); if (scriptDescription.getAutoRun()) { scriptDescription.scriptInitialized(); synchronized (addedTestScripts) { - this.addedTestScripts.add(scriptDescription.getId()); + addedTestScripts.add(scriptDescription.getId()); } } else { scriptDescription.scriptPending(); synchronized (pendingTestScriptsToPrepare) { - this.pendingTestScriptsToPrepare.add(scriptDescription.getId()); + pendingTestScriptsToPrepare.add(scriptDescription.getId()); } } @@ -433,8 +433,8 @@ public void compileScript(long id) { logger.info("compileScript({})", id); synchronized (pendingTestScriptsToPrepare) { synchronized (addedTestScripts) { - if (this.pendingTestScriptsToPrepare.remove(id)) { - this.addedTestScripts.add(id); + if(pendingTestScriptsToPrepare.remove(id)) { + addedTestScripts.add(id); } } } @@ -452,8 +452,8 @@ public void dispose() { if (runnerState != State.DISPOSED && runnerState != State.DISPOSING) { isDisposing = true; runnerState = State.DISPOSING; - joinThread(this.tScriptCompiler); - joinThread(this.tScriptExecutor); + joinThread(tScriptCompiler); + joinThread(tScriptExecutor); runnerState = State.DISPOSED; } logger.info("Script runner was disposed"); @@ -487,8 +487,8 @@ public void removeScriptRunListener(IScriptRunListener listener) { } protected void fireEvent(TestScriptDescription testScriptDescription) { - synchronized (this.listeners) { - for (IScriptRunListener listener : this.listeners) { + synchronized(listeners) { + for(IScriptRunListener listener : listeners) { try { listener.onScriptRunEvent(testScriptDescription); } catch ( Throwable e ) { @@ -526,7 +526,7 @@ protected void onRunFinished(TestScriptDescription descr) { fireEvent(descr); // update script run status after report is complete } - protected GeneratedScript generateJavaSourcesFromMatrix(final TestScriptDescription description) throws ScriptRunException, IOException { + protected GeneratedScript generateJavaSourcesFromMatrix(TestScriptDescription description) throws ScriptRunException, IOException { File matrixFile = new File(description.getMatrixPath()); @@ -549,12 +549,14 @@ protected GeneratedScript generateJavaSourcesFromMatrix(final TestScriptDescript settings.setStaticVariables(description.getStaticVariables()); List preprocessors = preprocessorLoader.getPreprocessors(); - for (IPreprocessor preprocessor : preprocessors) + for(IPreprocessor preprocessor : preprocessors) { settings.addPreprocessor(preprocessor); + } List validators = validatorLoader.getValidators(); - for (IValidator validator : validators) + for(IValidator validator : validators) { settings.addValidator(validator); + } try { @@ -654,7 +656,7 @@ protected WorkFolderPaths copyFilesToWorkFolder(String matrixFileName, String or workFolderPath + File.separator + origMatrixFile.getName()); } - protected GeneratedScript prepareScript(final TestScriptDescription description) throws Exception { + protected GeneratedScript prepareScript(TestScriptDescription description) throws Exception { logger.info("Prepare script started [{}]", description.getMatrixFileName()); GeneratedScript script = generateJavaSourcesFromMatrix(description); @@ -662,8 +664,8 @@ protected GeneratedScript prepareScript(final TestScriptDescription description) File binFolder = workspaceDispatcher.createFolder(FolderType.REPORT, description.getWorkFolder(), "bin"); // parent class loader must be specified for new web-gui - ILanguageFactory languageFactory = this.languageManager.getLanguageFactory(description.getLanguageURI()); - ClassLoader classLoader = languageFactory.createClassLoader(binFolder.toURI().toURL(), this.getClass().getClassLoader()); + ILanguageFactory languageFactory = languageManager.getLanguageFactory(description.getLanguageURI()); + ClassLoader classLoader = languageFactory.createClassLoader(binFolder.toURI().toURL(), getClass().getClassLoader()); // load Script Settings File scriptFile = workspaceDispatcher.getFile(FolderType.REPORT, description.getSettingsPath()); @@ -683,7 +685,7 @@ protected GeneratedScript prepareScript(final TestScriptDescription description) return script; } - protected void compileScript(final GeneratedScript script, final TestScriptDescription description) throws InterruptedException { + protected void compileScript(GeneratedScript script, TestScriptDescription description) throws InterruptedException { logger.info("Compile script #{} started (matrix {})", description.getId(), description.getMatrixFileName()); Thread t = new Thread(new Runnable() { @@ -706,7 +708,7 @@ public void run() { } } }, "Script compiler #"+description.getId()); - t.setPriority(this.settings.getCompilerPriority()); + t.setPriority(settings.getCompilerPriority()); t.start(); while (t.isAlive()) { @@ -753,7 +755,7 @@ protected void scriptExceptionProcessing(TestScriptDescription descr, Throwable // Init Report - if (description == null || description.equals("")) { + if(description == null || "".equals(description)) { description = IScriptReport.NO_DESCRIPTION; } @@ -777,7 +779,7 @@ protected void scriptExceptionProcessing(TestScriptDescription descr, Throwable } } - protected void cancelScript(final TestScriptDescription description) { + protected void cancelScript(TestScriptDescription description) { logger.info("Script #{} (matrix {}) has been canceled", description.getId(), description.getMatrixFileName()); ScriptContext scriptContext = description.getContext(); @@ -856,7 +858,7 @@ private Logger createScriptLogger(ScriptSettings scriptSettings, String reportFo return LoggerFactory.getLogger(scriptLogger.getName()); } - protected class InternalProgressListener implements ScriptProgress.IScriptRunProgressListener { + protected class InternalProgressListener implements IScriptRunProgressListener { @Override public void onProgressChanged(long id) { TestScriptDescription testScriptDescription = testScripts.get(id); @@ -934,7 +936,7 @@ public Throwable call() throws Exception catch (Throwable e) { logger.error(e.getMessage(), e); - this.scriptContext.getScriptConfig().getLogger().error("Problem during testscript running", e); + scriptContext.getScriptConfig().getLogger().error("Problem during testscript running", e); result = e; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AdaptersLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AdaptersLoader.java index 8b4ac316..cc9f5d1e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AdaptersLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AdaptersLoader.java @@ -25,8 +25,8 @@ public class AdaptersLoader { - private final static String SETTINGS_ADAPTERS_KEY = "Adapters"; - private final static String SETTINGS_ADAPTER_KEY = "Adapter"; + private static final String SETTINGS_ADAPTERS_KEY = "Adapters"; + private static final String SETTINGS_ADAPTER_KEY = "Adapter"; private final List adapters = new LinkedList<>(); @@ -43,13 +43,13 @@ private void loadAdaptersSettings(HierarchicalConfiguration config) { AdapterDescription adapterDescription = new AdapterDescription(); adapterDescription.load(sub); - this.adapters.add(adapterDescription); + adapters.add(adapterDescription); } } public List getAdapters() { - return this.adapters; + return adapters; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AsyncScriptRunner.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AsyncScriptRunner.java index d9888fb6..99ba1196 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AsyncScriptRunner.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/AsyncScriptRunner.java @@ -15,7 +15,7 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner; -import java.util.AbstractMap; +import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -53,23 +53,23 @@ public class AsyncScriptRunner extends AbstractScriptRunner { - private final static Logger logger = LoggerFactory.getLogger(AsyncScriptRunner.class); + private static final Logger logger = LoggerFactory.getLogger(AsyncScriptRunner.class); public AsyncScriptRunner( - final IWorkspaceDispatcher wd, - final IDictionaryManager dictionaryManager, - final IActionManager actionManager, - final IUtilityManager utilityManager, - final LanguageManager languageManager, - final PreprocessorLoader preprocessorLoader, - final ValidatorLoader validatorLoader, - final ScriptRunnerSettings settings, - final StatisticsService statisticsService, - final IEnvironmentManager environmentManager, - final ITestScriptStorage testScriptStorage, - final IAdapterManager adapterManager, - final IStaticServiceManager staticServiceManager, - final String compilerClassPath) { + IWorkspaceDispatcher wd, + IDictionaryManager dictionaryManager, + IActionManager actionManager, + IUtilityManager utilityManager, + LanguageManager languageManager, + PreprocessorLoader preprocessorLoader, + ValidatorLoader validatorLoader, + ScriptRunnerSettings settings, + StatisticsService statisticsService, + IEnvironmentManager environmentManager, + ITestScriptStorage testScriptStorage, + IAdapterManager adapterManager, + IStaticServiceManager staticServiceManager, + String compilerClassPath) { super(wd, dictionaryManager, actionManager, utilityManager, languageManager, preprocessorLoader, validatorLoader, settings, statisticsService, environmentManager, testScriptStorage, adapterManager, staticServiceManager, compilerClassPath); tScriptCompiler = new Thread(new ScriptCompiler(), "ScriptCompiler"); tScriptExecutor = new Thread(new ScriptExecutor(), "ScriptExecutor"); @@ -79,15 +79,15 @@ public AsyncScriptRunner( class ScriptCompiler implements Runnable { private final ExecutorService executorService = Executors.newFixedThreadPool(2); - private final Queue> scriptsForCompileQueue = new ConcurrentLinkedQueue<>(); + private final Queue> scriptsForCompileQueue = new ConcurrentLinkedQueue<>(); @Override public void run() { while (!isDisposing) { try { if (!scriptsForCompileQueue.isEmpty()) { - final Map.Entry entry = scriptsForCompileQueue.poll(); - final TestScriptDescription descrForCompile = testScripts.get(entry.getKey()); + Entry entry = scriptsForCompileQueue.poll(); + TestScriptDescription descrForCompile = testScripts.get(entry.getKey()); if (descrForCompile == null) { logger.warn("Can't find script [{}]. Probably it was removed", entry.getKey()); @@ -118,7 +118,7 @@ public void run() { Thread.sleep(100); - final Long testScript; + Long testScript; synchronized (addedTestScripts) { testScript = addedTestScripts.poll(); } @@ -127,7 +127,7 @@ public void run() { continue; } - final TestScriptDescription descrForPrep = testScripts.get(testScript); + TestScriptDescription descrForPrep = testScripts.get(testScript); if (descrForPrep == null) { logger.warn("Can't find script [{}]. Probably it was removed", testScript); @@ -150,7 +150,7 @@ public void run() { public void run() { try { GeneratedScript generatedScript = prepareScript(descrForPrep); - Map.Entry entry = new AbstractMap.SimpleEntry<>(testScript, generatedScript); + Entry entry = new SimpleEntry<>(testScript, generatedScript); scriptsForCompileQueue.add(entry); } catch (Exception e) { scriptExceptionProcessing(descrForPrep, e); @@ -281,22 +281,24 @@ private void interuptScripts(Map> runningScriptMap) { } pullScripts(); - for (Long tsId : this.prepared) { + for(Long tsId : prepared) { TestScriptDescription descr = testScripts.get(tsId); descr.scriptNotStarted(); onRunFinished(descr); logger.info("TestScript {} was not started", tsId); } - this.prepared.clear(); + prepared.clear(); } private void startScript(Map> runningScriptMap) throws InterruptedException { - if (this.prepared.isEmpty()) - return; - if (runningScriptMap.size() >= MAX_THREADS) - return; + if(prepared.isEmpty()) { + return; + } + if(runningScriptMap.size() >= MAX_THREADS) { + return; + } - Iterator iterator = this.prepared.iterator(); + Iterator iterator = prepared.iterator(); while (iterator.hasNext() && runningScriptMap.size() < MAX_THREADS) { Long currentTestScript = iterator.next(); @@ -384,7 +386,7 @@ private void pullScripts() { testScriptId = preparedTestScripts.poll(); if (testScriptId != null) { logger.info("TestScript {} was taken from waiting queue", testScriptId); - this.prepared.add(testScriptId); + prepared.add(testScriptId); } } } @@ -393,8 +395,8 @@ private void pullScripts() { private boolean tryToLockServices(TestScriptDescription descr) { List services = descr.getContext().getServiceList(); - if (Collections.disjoint(this.locksServices, services)) { - this.locksServices.addAll(services); + if(Collections.disjoint(locksServices, services)) { + locksServices.addAll(services); logger.info("TestScript {} locked services {}", descr.getId(), services); return true; } @@ -403,7 +405,7 @@ private boolean tryToLockServices(TestScriptDescription descr) { private void unlockServices(TestScriptDescription descr) { List services = descr.getContext().getServiceList(); - this.locksServices.removeAll(services); + locksServices.removeAll(services); logger.info("TestScript {} unlocked services {}", descr.getId(), services); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/DebugController.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/DebugController.java index 1a5f23f5..91d51103 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/DebugController.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/DebugController.java @@ -25,9 +25,9 @@ public class DebugController { private static final Logger logger = LoggerFactory.getLogger(DebugController.class); private static final String PAUSED = "Paused by user: "; - private final AtomicReference currentStataus = new AtomicReference(ControllerStatus.RUNNED); - private long id; - private IPauseListener pauseListener; + private final AtomicReference currentStataus = new AtomicReference(ControllerStatus.RUNNED); + private final long id; + private final IPauseListener pauseListener; private String reason; private long timeout; @@ -38,8 +38,8 @@ public DebugController(long id, IPauseListener pauseListener) { // Called from GUI only (user press Resume button) public synchronized void resumeScript() { - this.currentStataus.compareAndSet(ControllerStatus.PAUSED, ControllerStatus.RUNNED); - this.notifyAll(); + currentStataus.compareAndSet(ControllerStatus.PAUSED, ControllerStatus.RUNNED); + notifyAll(); } // Called from GUI only (user press Pause button) @@ -47,13 +47,13 @@ public synchronized void pauseScript() { // change script state to PAUSED this.reason = PAUSED; this.timeout = 0; - this.currentStataus.compareAndSet(ControllerStatus.RUNNED, ControllerStatus.PAUSED); + currentStataus.compareAndSet(ControllerStatus.RUNNED, ControllerStatus.PAUSED); } // Called from GUI only (user press Stop button) public synchronized void stopScript() { - this.currentStataus.set(ControllerStatus.STOPPED); - this.notifyAll(); + currentStataus.set(ControllerStatus.STOPPED); + notifyAll(); } // Called from AskForContinue only @@ -61,7 +61,7 @@ public synchronized void pauseScript(long timeout, String reason) { // change script state to PAUSED this.timeout = timeout; this.reason = reason; - this.currentStataus.compareAndSet(ControllerStatus.RUNNED, ControllerStatus.PAUSED); + currentStataus.compareAndSet(ControllerStatus.RUNNED, ControllerStatus.PAUSED); } // Called from GUI only (user press Next Step button) @@ -71,24 +71,24 @@ public synchronized void pauseScriptOnNextStep() { // this.reason = PAUSED; this.timeout = 0; - this.notifyAll(); - this.currentStataus.compareAndSet(ControllerStatus.RUNNED, ControllerStatus.PAUSED); + notifyAll(); + currentStataus.compareAndSet(ControllerStatus.RUNNED, ControllerStatus.PAUSED); } // Called from from AskForContinue or before each script step public synchronized void doWait(String description) throws InterruptedException { - ControllerStatus status = this.currentStataus.get(); + ControllerStatus status = currentStataus.get(); switch (status) { case RUNNED: return; case PAUSED: - this.pauseListener.onScriptPaused(id, this.reason + description, this.timeout); - if (this.timeout > 0) { - this.wait(this.timeout); + pauseListener.onScriptPaused(id, reason + description, timeout); + if(timeout > 0) { + wait(timeout); } else { - this.wait(); + wait(); } - this.pauseListener.onScriptResumed(id); + pauseListener.onScriptResumed(id); break; case STOPPED: throw new InterruptedException("Stopped by user"); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/EnvironmentSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/EnvironmentSettings.java index 44af3aa9..cc9c9835 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/EnvironmentSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/EnvironmentSettings.java @@ -25,6 +25,7 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.configuration.HierarchicalConfiguration; +import org.apache.commons.configuration.HierarchicalConfiguration.Node; import org.apache.commons.lang3.StringUtils; import org.mvel2.math.MathProcessor; import org.slf4j.Logger; @@ -47,7 +48,7 @@ public enum StorageType { private final String name; - private StorageType(String name) { + StorageType(String name) { this.name = name; } @@ -75,7 +76,7 @@ public enum ReportOutputFormat { private final String name; - private ReportOutputFormat(String name) { + ReportOutputFormat(String name) { this.name = name; } @@ -108,9 +109,9 @@ public enum RelevantMessagesSortingMode { ARRIVAL_TIME("arrival_time"), FAILED_FIELDS("failed_fields"); - private String name; + private final String name; - private RelevantMessagesSortingMode(String name) { + RelevantMessagesSortingMode(String name) { this.name = name; } @@ -131,17 +132,17 @@ public static RelevantMessagesSortingMode parse(String value) { } } - private final static String GENERAL_KEY = "GeneralSettings"; - private final static String ASYNC_RUN_MATRIX_KEY = "AsyncRunMatrix"; - private final static String NOTIFICATION_IF_SOME_SERVICES_NOT_STARTED = "NotificationIfSomeServicesNotStarted"; - private final static String MATRIX_COMPILER_PRIORITY = "MatrixCompilerPriority"; - private final static String EXCLUDED_MESSAGES_FROM_REPORT = "ExcludedMessagesFromReport"; - private final static String COMPARISON_PRECISION = "ComparisonPrecision"; - - private final static String SCRIPT_RUN = "ScriptRun"; - private final static String FAIL_UNEXPECTED_KEY = "FailUnexpected"; - private final static String REPORT_OUTPUT_FORMAT = "ReportOutputFormat"; - private final static String RELEVANT_MESSAGES_SORTING_MODE = "RelevantMessagesSortingMode"; + private static final String GENERAL_KEY = "GeneralSettings"; + private static final String ASYNC_RUN_MATRIX_KEY = "AsyncRunMatrix"; + private static final String NOTIFICATION_IF_SOME_SERVICES_NOT_STARTED = "NotificationIfSomeServicesNotStarted"; + private static final String MATRIX_COMPILER_PRIORITY = "MatrixCompilerPriority"; + private static final String EXCLUDED_MESSAGES_FROM_REPORT = "ExcludedMessagesFromReport"; + private static final String COMPARISON_PRECISION = "ComparisonPrecision"; + + private static final String SCRIPT_RUN = "ScriptRun"; + private static final String FAIL_UNEXPECTED_KEY = "FailUnexpected"; + private static final String REPORT_OUTPUT_FORMAT = "ReportOutputFormat"; + private static final String RELEVANT_MESSAGES_SORTING_MODE = "RelevantMessagesSortingMode"; private static final String MAX_STORAGE_QUEUE_SIZE = "MaxStorageQueueSize"; private StorageType storageType = StorageType.DB; @@ -164,28 +165,28 @@ public static RelevantMessagesSortingMode parse(String value) { public EnvironmentSettings(HierarchicalConfiguration hierarchicalConfiguration) { this.config = hierarchicalConfiguration; if (config.configurationsAt(GENERAL_KEY).isEmpty()) { - config.getRootNode().addChild(new HierarchicalConfiguration.Node(GENERAL_KEY)); + config.getRootNode().addChild(new Node(GENERAL_KEY)); } if (config.configurationsAt(SCRIPT_RUN).isEmpty()) { - config.getRootNode().addChild(new HierarchicalConfiguration.Node(SCRIPT_RUN)); + config.getRootNode().addChild(new Node(SCRIPT_RUN)); } } @Override public EnvironmentSettings clone() { - EnvironmentSettings result = new EnvironmentSettings(this.config); - result.fileStoragePath = this.fileStoragePath; - result.storeAdminMessages = this.storeAdminMessages; - result.asyncRunMatrix = this.asyncRunMatrix; - result.notificationIfServicesNotStarted = this.notificationIfServicesNotStarted; - result.matrixCompilerPriority = this.matrixCompilerPriority; - result.excludedMessages = this.excludedMessages; - result.failUnexpected = this.failUnexpected; - result.storageType = this.storageType; - result.reportOutputFormat = this.reportOutputFormat; - result.relevantMessagesSortingMode = this.relevantMessagesSortingMode; - result.comparisonPrecision = this.comparisonPrecision; - result.maxQueueSize = this.maxQueueSize; + EnvironmentSettings result = new EnvironmentSettings(config); + result.fileStoragePath = fileStoragePath; + result.storeAdminMessages = storeAdminMessages; + result.asyncRunMatrix = asyncRunMatrix; + result.notificationIfServicesNotStarted = notificationIfServicesNotStarted; + result.matrixCompilerPriority = matrixCompilerPriority; + result.excludedMessages = excludedMessages; + result.failUnexpected = failUnexpected; + result.storageType = storageType; + result.reportOutputFormat = reportOutputFormat; + result.relevantMessagesSortingMode = relevantMessagesSortingMode; + result.comparisonPrecision = comparisonPrecision; + result.maxQueueSize = maxQueueSize; return result; } @@ -207,7 +208,7 @@ public void set(EnvironmentSettings other) { } public String getFileStoragePath() { - return this.fileStoragePath; + return fileStoragePath; } public void setFileStoragePath(String path) { @@ -286,7 +287,7 @@ public Set getExcludedMessages() { return excludedMessages; } - @Description(value = "Exclude messages from information block about all messages in report") + @Description("Exclude messages from information block about all messages in report") @ValidateRegex(regex = IDictionaryValidator.NAME_REGEX) public void setExcludedMessages(Set excludedMessages) { this.excludedMessages = CollectionUtils.isEmpty(excludedMessages) ? Collections.emptySet() : ImmutableSet.copyOf(excludedMessages); @@ -312,8 +313,9 @@ public void setComparisonPrecision(BigDecimal comparisonPrecision) { @Override public void load(HierarchicalConfiguration config) { - if ( !(config.configurationsAt(GENERAL_KEY).isEmpty()) ) - loadGeneralSettings(config.configurationAt(GENERAL_KEY)); + if(!config.configurationsAt(GENERAL_KEY).isEmpty()) { + loadGeneralSettings(config.configurationAt(GENERAL_KEY)); + } if (!config.configurationsAt(SCRIPT_RUN).isEmpty()){ loadScriptRunSettings(config.configurationAt(SCRIPT_RUN)); @@ -348,7 +350,7 @@ private static Set parseSet(HierarchicalConfiguration config, String pro } private void update() { - if (!(config.configurationsAt(GENERAL_KEY).isEmpty())) { + if(!config.configurationsAt(GENERAL_KEY).isEmpty()) { updateGeneralSettings(config.configurationAt(GENERAL_KEY)); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java index 7771f624..4458c34a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IConnectionManager.java @@ -44,9 +44,9 @@ public interface IConnectionManager extends IDisposable Future removeEnvironment(String envName, IServiceNotifyListener notifyListener); - Future addEnvironment(final String envName, final IServiceNotifyListener notifyListener); + Future addEnvironment(String envName, IServiceNotifyListener notifyListener); - Future renameEnvironment(final String oldEnvName, final String newEnvName, final IServiceNotifyListener notifyListener); + Future renameEnvironment(String oldEnvName, String newEnvName, IServiceNotifyListener notifyListener); List getEnvironmentList(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IPauseListener.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IPauseListener.java index beb52ae9..fbc7192e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IPauseListener.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IPauseListener.java @@ -17,7 +17,7 @@ public interface IPauseListener { - public void onScriptPaused(long id, String reason, long timeout); - public void onScriptResumed(long id); + void onScriptPaused(long id, String reason, long timeout); + void onScriptResumed(long id); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptProgress.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptProgress.java index 0d4c3ea6..553e5a87 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptProgress.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptProgress.java @@ -17,48 +17,48 @@ public interface IScriptProgress { - public long getCurrentActions(); + long getCurrentActions(); - public long getCurrentExecutedActions(); + long getCurrentExecutedActions(); - public int getCurrentTC(); + int getCurrentTC(); - public int getExecutedTC(); + int getExecutedTC(); - public long getFailed(); + long getFailed(); - public void setFailed(long failed); + void setFailed(long failed); - public int getLoaded(); + int getLoaded(); - public long getConditionallyPassed(); + long getConditionallyPassed(); - public long getPassed(); + long getPassed(); - public void setConditionallyPassed(long conditionallyPassed); + void setConditionallyPassed(long conditionallyPassed); - public void setPassed(long passed); + void setPassed(long passed); - public long getTotalActions(); + long getTotalActions(); - public long getTotalExecutedActions(); + long getTotalExecutedActions(); - public void increaseFailed(); + void increaseFailed(); - public void increasePassed(); + void increasePassed(); - public void increaseConditionallyPassed(); + void increaseConditionallyPassed(); - public void incrementActions(); + void incrementActions(); - public void incrementExecutedTC(); + void incrementExecutedTC(); - public void setCurrentActions(long i); + void setCurrentActions(long i); - public void setCurrentTC(int executed); + void setCurrentTC(int executed); - public void setLoaded(int size); + void setLoaded(int size); - public void setTotalActions(long i); + void setTotalActions(long i); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptReport.java index 466833a8..86c71ee0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/IScriptReport.java @@ -32,7 +32,7 @@ // TODO: split ScriptReport and listening functionality public interface IScriptReport { - public static final String NO_DESCRIPTION = "No description"; + String NO_DESCRIPTION = "No description"; /* * Start of Matrix execution diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/Outcome.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/Outcome.java index 11160bdd..07159dbc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/Outcome.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/Outcome.java @@ -38,8 +38,8 @@ public static StatusType getStatusType(Status type) { } } - private String group; - private String name; + private final String group; + private final String name; private Status status = Status.NOT_CHECKED; public Outcome(String group, String name) @@ -49,11 +49,11 @@ public Outcome(String group, String name) } public String getGroup() { - return this.group; + return group; } public String getName() { - return this.name; + return name; } public Outcome setStatus(Status status) { @@ -62,11 +62,11 @@ public Outcome setStatus(Status status) { } public Status getStatus() { - return this.status; + return status; } @Override public String toString() { - return this.group+":"+this.name+" = "+this.status; + return group + ":" + name + " = " + status; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/OutcomeCollector.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/OutcomeCollector.java index 35458017..05f57e39 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/OutcomeCollector.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/OutcomeCollector.java @@ -49,13 +49,13 @@ public OutcomeCollector() { * Clear outcome state */ public void clear() { - for (List list : this.completed.values()) { + for(List list : completed.values()) { list.clear(); } - this.completed.clear(); - this.groups.clear(); - this.groupOrder.clear(); - this.defined.clear(); + completed.clear(); + groups.clear(); + groupOrder.clear(); + defined.clear(); } /** @@ -66,11 +66,11 @@ public void clear() { */ public void storeOutcome(Outcome outcome) { logger.debug("storeOutcome: {}", outcome); - Group group = this.groups.get(outcome.getGroup()); + Group group = groups.get(outcome.getGroup()); if (group == null) { group = new Group(); - this.groups.put(outcome.getGroup(), group); - this.groupOrder.add(outcome.getGroup()); + groups.put(outcome.getGroup(), group); + groupOrder.add(outcome.getGroup()); } if (outcome.getStatus() == Status.PASSED) { @@ -96,7 +96,7 @@ public void storeOutcome(Outcome outcome) { * {@code true} if Outcome completed and all verifications are passed. */ public Status getOutcomeStatus(String group, String name) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { logger.debug("getOutcomeStatus: {}:{} grp {} not started", group, name, group); return Status.PASSED; @@ -117,7 +117,7 @@ public Status getOutcomeStatus(String group, String name) { } public Status getGroupStatus(String group) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { logger.error("getGroupStatus: group {} not exist", group); throw new EPSCommonException("getGroupStatus: group \""+group+"\" not exist"); @@ -134,42 +134,33 @@ public Status getGroupStatus(String group) { public int getPassedCount(String group, String name) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { return 0; } Integer cnt = grp.passed.get(name); - if (cnt == null) { - cnt = 0; - } - return cnt; - } + return cnt == null ? 0 : cnt; + } public int getConditionallyPassedCount(String group, String name) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { return 0; } Integer cnt = grp.conditionallyPassed.get(name); - if (cnt == null) { - cnt = 0; - } - return cnt; + return cnt == null ? 0 : cnt; } public int getFailedCount(String group, String name) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { return 0; } Integer cnt = grp.failedCounter.get(name); - if (cnt == null) { - cnt = 0; - } - return cnt; + return cnt == null ? 0 : cnt; } /** @@ -177,11 +168,11 @@ public int getFailedCount(String group, String name) { * @return all completed outcomes */ public Map> getOutcomes() { - return this.completed; + return completed; } public List getGroupOrder() { - return this.groupOrder; + return groupOrder; } /** @@ -189,7 +180,7 @@ public List getGroupOrder() { * @return all possible outcomes */ public Map> getDefinedOutcomes() { - return this.defined; + return defined; } /** @@ -199,7 +190,7 @@ public Map> getDefinedOutcomes() { */ public void onOutcomeComplete(String group, String name) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { throw new NullPointerException("Group="+group+", name="+name); } @@ -213,7 +204,7 @@ public void onOutcomeComplete(String group, String name) } logger.debug("onOutcomeComplete: {}:{} groupPassed: {} groupConditionallyPassed: {}", group, name, grp.groupPassed, grp.groupConditionallyPassed); - Set set = this.defined.computeIfAbsent(group, k -> new HashSet<>()); + Set set = defined.computeIfAbsent(group, k -> new HashSet<>()); set.add(name); } @@ -224,7 +215,7 @@ public void onOutcomeComplete(String group, String name) */ public void onGroupComplete(String group) { - Group grp = this.groups.get(group); + Group grp = groups.get(group); if (grp == null) { throw new NullPointerException("Group is null: "+group); } @@ -233,7 +224,7 @@ public void onGroupComplete(String group) grp.name = "Unexpected"; } - List list = this.completed.computeIfAbsent(group, k -> new LinkedList<>()); + List list = completed.computeIfAbsent(group, k -> new LinkedList<>()); list.add(grp.name); @@ -265,17 +256,17 @@ class Group /** * Set when first result of outcome is PASSED or all possible variants are FAILED */ - boolean groupPassed = false; + boolean groupPassed; /** * Set when first result of outcome is CONDITIONALLY PASSED or all * possible variants are FAILED */ - boolean groupConditionallyPassed = false; + boolean groupConditionallyPassed; } class Counter { - private Map counter = new HashMap<>(); + private final Map counter = new HashMap<>(); public void add(String name) { Integer cnt = counter.get(name); @@ -290,7 +281,7 @@ public Integer get(String name) { } public int getCount() { - return this.counter.size(); + return counter.size(); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishAction.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishAction.java index e189adb5..46bf607a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishAction.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishAction.java @@ -27,7 +27,7 @@ public class SailFishAction { * Create MetaContainer for AML 2 action */ protected static MetaContainer createMetaContainer(MetaContainer parent, String name, String failUnexpected, String doublePrecision, String systemPrecision) { - MetaContainer result = new com.exactpro.sf.aml.script.MetaContainer(); + MetaContainer result = new MetaContainer(); if (parent != null) { parent.add(name, result); if (failUnexpected == null) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishTestCase.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishTestCase.java index 612c3640..818a64cd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishTestCase.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SailFishTestCase.java @@ -24,23 +24,23 @@ public class SailFishTestCase { static final Logger logger = LoggerFactory.getLogger(SailFishTestCase.class); - private IScriptReport report = null; - private ScriptRun scriptRun = null; - protected ScriptContext context = null; + private IScriptReport report; + private ScriptRun scriptRun; + protected ScriptContext context; protected IScriptReport getReport() { - return this.report; + return report; } protected ScriptRun getScriptRun() { - return this.scriptRun; + return scriptRun; } protected ScriptContext getContext() { - return this.context; + return context; } public void setReport(IScriptReport report) diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java index 71fe13a9..cdb61cc8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptContext.java @@ -59,13 +59,13 @@ public class ScriptContext private final String userName; - private boolean conditionallyPassed = false; + private boolean conditionallyPassed; private final Set knownBugs = new HashSet<>(); private String actionName; - private Exception exception = null; - private boolean interrupt = false; + private Exception exception; + private boolean interrupt; private ScriptRun scriptRun; - private Set unexpectedMessage; + private final Set unexpectedMessage; private CheckPoint tCStartCheckPoint; private long scriptStartTime; private String testCaseName; @@ -114,12 +114,12 @@ public ScriptContext(ISFContext context, IScriptProgress scriptProgress, IScript public void reset() { this.actionName = null; this.exception = null; - this.outcomes.clear(); - this.receivedMessages.clear(); - this.unexpectedMessage.clear(); + outcomes.clear(); + receivedMessages.clear(); + unexpectedMessage.clear(); this.tCStartCheckPoint = null; this.conditionallyPassed = false; - this.knownBugs.clear(); + knownBugs.clear(); } public String getUserName() { @@ -139,7 +139,9 @@ public Exception getException() { } public void setException(Exception exception) { - if (this.exception == null) this.exception = exception; + if(this.exception == null) { + this.exception = exception; + } } public boolean isInterrupt() { @@ -167,32 +169,32 @@ public IEnvironmentManager getEnvironmentManager() { } public OutcomeCollector getOutcomeCollector() { - return this.outcomes; + return outcomes; } public void onOutcomeComplete(String group, String name) { - this.outcomes.onOutcomeComplete(group, name); + outcomes.onOutcomeComplete(group, name); } public void onGroupComplete(String group) { - this.outcomes.onGroupComplete(group); + outcomes.onGroupComplete(group); } public void storeOutcome(Outcome outcome) { - this.outcomes.storeOutcome(outcome); + outcomes.storeOutcome(outcome); } public Status getOutcomeStatus(String group, String name) { - return this.outcomes.getOutcomeStatus(group, name); + return outcomes.getOutcomeStatus(group, name); } public Status getOutcomeGroupStatus(String group) { - return this.outcomes.getGroupStatus(group); + return outcomes.getGroupStatus(group); } public IScriptProgress getScriptProgress() { - return this.scriptProgress; + return scriptProgress; } public ScriptRun getScriptRun() { @@ -213,7 +215,7 @@ public Set getUnexpectedMessage() { } public void addUnexpectedMessages(Set setUnexpectedMessages){ - this.unexpectedMessage.addAll(setUnexpectedMessages); + unexpectedMessage.addAll(setUnexpectedMessages); } public CheckPoint getTCStartCheckPoint() { @@ -225,7 +227,7 @@ public void setTCStartCheckPoint(CheckPoint tCStartCheckPoint) { } public long getScriptStartTime() { - return this.scriptStartTime; + return scriptStartTime; } public void setScriptStartTime(long time) { @@ -233,7 +235,7 @@ public void setScriptStartTime(long time) { } public String getTestCaseName() { - return this.testCaseName; + return testCaseName; } public void setTestCaseName(String testCaseName) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptProgress.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptProgress.java index 38b66dde..8fc07aaa 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptProgress.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptProgress.java @@ -18,17 +18,17 @@ public class ScriptProgress implements IScriptProgress { - private int loaded = 0; - private int executedTC = 0; - private int currentTC = 0; - private long currentActions = 0; - private long currentExecutedActions = 0; - private long totalActions = 0; - private long totalExecutedActions = 0; + private int loaded; + private int executedTC; + private int currentTC; + private long currentActions; + private long currentExecutedActions; + private long totalActions; + private long totalExecutedActions; - private long passed = 0; - private long conditionallyPassed = 0; - private long failed = 0; + private long passed; + private long conditionallyPassed; + private long failed; @@ -54,7 +54,7 @@ public void setLoaded(int loaded) { this.loaded = loaded; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -66,7 +66,7 @@ public void setExecutedTC(int executed) { executedTC = executed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -74,7 +74,7 @@ public void incrementExecutedTC() { executedTC++; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -87,7 +87,7 @@ public void setCurrentTC(int executed) { currentTC = executed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -100,7 +100,7 @@ public void setCurrentActions(long actions) { currentActions = actions; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -113,7 +113,7 @@ public void setCurrentExecutedActions(long executedActions) { currentExecutedActions = executedActions; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -126,7 +126,7 @@ public void setTotalActions(long totalActions) { this.totalActions = totalActions; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -138,7 +138,7 @@ public void setTotalExecutedActions(long totalExecutedActions) { this.totalExecutedActions = totalExecutedActions; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -147,7 +147,7 @@ public void incrementActions() currentExecutedActions++; totalExecutedActions++; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } public interface IScriptRunProgressListener @@ -167,7 +167,7 @@ public long getPassed() { @Override public void setPassed(long passed) { this.passed = passed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -175,7 +175,7 @@ public void increasePassed() { ++this.passed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -186,14 +186,14 @@ public long getFailed() { @Override public void setFailed(long failed) { this.failed = failed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override public void increaseFailed() { ++this.failed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override @@ -204,13 +204,13 @@ public long getConditionallyPassed() { @Override public void setConditionallyPassed(long conditionallyPassed) { this.conditionallyPassed = conditionallyPassed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } @Override public void increaseConditionallyPassed() { ++this.conditionallyPassed; - this.listener.onProgressChanged(this.testScriptRunId); + listener.onProgressChanged(testScriptRunId); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptSettings.java index 3b102895..1bf44019 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ScriptSettings.java @@ -42,7 +42,7 @@ public class ScriptSettings implements ICommonSettings private String fileLayout; private boolean addMessagetoReport; private String scriptFolder; - private Map properties; + private final Map properties; public ScriptSettings() { @@ -52,7 +52,7 @@ public ScriptSettings() public String getTestScriptClassName() { - return this.testScriptClassName; + return testScriptClassName; } @@ -64,7 +64,7 @@ public void setTestScriptClassName(String testScriptClassName) public boolean isAddMessagesToReport() { - return this.addMessagetoReport; + return addMessagetoReport; } @@ -76,7 +76,7 @@ public void setAddMessagesToReport(boolean value) public IScriptReport getScriptReport() { - return this.scriptReport; + return scriptReport; } public void setScriptReport(IScriptReport scriptReport) @@ -87,19 +87,19 @@ public void setScriptReport(IScriptReport scriptReport) public String getProperty(String name) { - return this.properties.get(name); - } + return properties.get(name); + } public Set getPropertiesKeys() { - return this.properties.keySet(); + return properties.keySet(); } public String getScriptName() { - return this.scriptName; + return scriptName; } @@ -160,20 +160,24 @@ public void load(HierarchicalConfiguration config) HierarchicalConfiguration testScriptConfig = config.configurationAt(TESTSCRIPT_KEY); String scriptNamePar = config.getString("TestScript[@name]"); - - if ( scriptNamePar == null ) - throw new ScriptRunException("There is no \"name\" attribute at \"TestScript\" element in the script configuration file"); + + if(scriptNamePar == null) { + throw new ScriptRunException("There is no \"name\" attribute at \"TestScript\" element in the script configuration file"); + } this.scriptName = scriptNamePar; - - if ( !(testScriptConfig.configurationsAt(PROPERTIES_KEY).isEmpty()) ) - loadProperties(testScriptConfig.configurationAt(PROPERTIES_KEY)); - - if ( !(testScriptConfig.configurationsAt(LOGGING_KEY).isEmpty()) ) - loadLoggingProperties(testScriptConfig.configurationAt(LOGGING_KEY)); - - if ( !(testScriptConfig.configurationsAt(TESTREPORT_KEY).isEmpty()) ) - loadTestReportProperties(testScriptConfig.configurationAt(TESTREPORT_KEY)); + + if(!testScriptConfig.configurationsAt(PROPERTIES_KEY).isEmpty()) { + loadProperties(testScriptConfig.configurationAt(PROPERTIES_KEY)); + } + + if(!testScriptConfig.configurationsAt(LOGGING_KEY).isEmpty()) { + loadLoggingProperties(testScriptConfig.configurationAt(LOGGING_KEY)); + } + + if(!testScriptConfig.configurationsAt(TESTREPORT_KEY).isEmpty()) { + loadTestReportProperties(testScriptConfig.configurationAt(TESTREPORT_KEY)); + } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusDescription.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusDescription.java index 1bd4421c..f416dd3e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusDescription.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusDescription.java @@ -75,11 +75,7 @@ public StatusDescription(StatusType status, String description, boolean updateTe this.updateTestCaseStatus = updateTestCaseStatus; - if (knownBugs == null) { - this.knownBugs = Collections.emptySet(); - } else { - this.knownBugs = Collections.unmodifiableSet(knownBugs); - } + this.knownBugs = knownBugs == null ? Collections.emptySet() : Collections.unmodifiableSet(knownBugs); } public StatusDescription(StatusType status, String description, Throwable cause, boolean updateTestCaseStatus, Set knownBugs) @@ -92,11 +88,7 @@ public StatusDescription(StatusType status, String description, Throwable cause, this.updateTestCaseStatus = updateTestCaseStatus; - if (knownBugs == null) { - this.knownBugs = Collections.emptySet(); - } else { - this.knownBugs = Collections.unmodifiableSet(knownBugs); - } + this.knownBugs = knownBugs == null ? Collections.emptySet() : Collections.unmodifiableSet(knownBugs); } public StatusType getStatus() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusType.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusType.java index 3e07aaf7..aff0c777 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusType.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/StatusType.java @@ -28,7 +28,7 @@ public enum StatusType private final int id; - private StatusType(int id) { + StatusType(int id) { this.id = id; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SyncScriptRunner.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SyncScriptRunner.java index ff0656c8..66b1914c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SyncScriptRunner.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/SyncScriptRunner.java @@ -41,23 +41,23 @@ public class SyncScriptRunner extends AbstractScriptRunner { - private final static Logger logger = LoggerFactory.getLogger(SyncScriptRunner.class); + private static final Logger logger = LoggerFactory.getLogger(SyncScriptRunner.class); public SyncScriptRunner( - final IWorkspaceDispatcher wd, - final IDictionaryManager dictionaryManager, - final IActionManager actionManager, - final IUtilityManager utilityManager, - final LanguageManager languageManager, - final PreprocessorLoader preprocessorLoader, - final ValidatorLoader validatorLoader, - final ScriptRunnerSettings settings, - final StatisticsService statisticsService, - final IEnvironmentManager environmentManager, - final ITestScriptStorage testScriptStorage, - final IAdapterManager adapterManager, - final IStaticServiceManager staticServiceManager, - final String compilerClassPath) { + IWorkspaceDispatcher wd, + IDictionaryManager dictionaryManager, + IActionManager actionManager, + IUtilityManager utilityManager, + LanguageManager languageManager, + PreprocessorLoader preprocessorLoader, + ValidatorLoader validatorLoader, + ScriptRunnerSettings settings, + StatisticsService statisticsService, + IEnvironmentManager environmentManager, + ITestScriptStorage testScriptStorage, + IAdapterManager adapterManager, + IStaticServiceManager staticServiceManager, + String compilerClassPath) { super(wd, dictionaryManager, actionManager, utilityManager, languageManager, preprocessorLoader, validatorLoader, settings, statisticsService, environmentManager, testScriptStorage, adapterManager, staticServiceManager, compilerClassPath); tScriptCompiler = new Thread(new ScriptCompiler(), "ScriptCompiler"); tScriptExecutor = new Thread(new ScriptExecutor(), "ScriptExecutor"); @@ -84,8 +84,9 @@ public void run() { testScript = addedTestScripts.poll(); } - if (testScript == null) - continue; + if(testScript == null) { + continue; + } descr = testScripts.get(testScript); @@ -178,8 +179,9 @@ public void run() { currentTestScript = preparedTestScripts.poll(); } - if (currentTestScript == null) - continue; + if(currentTestScript == null) { + continue; + } TestScriptDescription descr = testScripts.get(currentTestScript); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptDescription.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptDescription.java index aa668f88..c515db83 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptDescription.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptDescription.java @@ -31,8 +31,8 @@ import com.exactpro.sf.SerializeUtil; import com.exactpro.sf.aml.AMLException; -import com.exactpro.sf.aml.generator.AlertCollector; import com.exactpro.sf.aml.generator.AggregateAlert; +import com.exactpro.sf.aml.generator.AlertCollector; import com.exactpro.sf.aml.generator.AlertType; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.embedded.statistics.entities.Tag; @@ -40,7 +40,7 @@ public class TestScriptDescription implements Closeable { - private final static AtomicLong scriptIdCounter = new AtomicLong(); + private static final AtomicLong scriptIdCounter = new AtomicLong(); private final String originalMatrixPath; // relative (to MATRIX folder) path to matrix private final String originalSettingsPath; // relative (to CFG folder) path to 'script.xml' @@ -104,7 +104,7 @@ public class TestScriptDescription implements Closeable private long matrixRunId; - private boolean canceled = false; + private boolean canceled; private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); @@ -222,8 +222,8 @@ public enum ScriptState PENDING(8, false), PAUSED(9, false); - private int weight; - private boolean terminate; + private final int weight; + private final boolean terminate; ScriptState(int weight, boolean terminate) { this.weight = weight; @@ -249,16 +249,16 @@ public enum ScriptStatus { CANCELED("CANCELED", 5), RUN_FAILED("RUN FAILED", 6); - private String title; - private int weight; + private final String title; + private final int weight; - private ScriptStatus(String title, int weight) { + ScriptStatus(String title, int weight) { this.title = title; this.weight = weight; } public String getTitle() { - return this.title; + return title; } public int getWeight() { @@ -428,19 +428,19 @@ public String getSettingsPath() { } public String getMatrixFileName() { - return this.matrixFileName; + return matrixFileName; } public boolean getContinueOnFailed() { - return this.continueOnFailed; + return continueOnFailed; } public boolean getAutoStart() { - return this.autoStart; + return autoStart; } public boolean getAutoRun() { - return this.autoRun; + return autoRun; } public SailfishURI getLanguageURI() { @@ -551,13 +551,13 @@ public void setFinishedTime(long finishedTime) { } public void notifyListener() { - this.listener.onScriptRunEvent(this); + listener.onScriptRunEvent(this); } public String getPauseReason() { try { readLock.lock(); - return this.pauseReason; + return pauseReason; } finally { readLock.unlock(); } @@ -566,7 +566,7 @@ public String getPauseReason() { public long getPauseTimeout() { try { readLock.lock(); - return this.pauseTimeout; + return pauseTimeout; } finally { readLock.unlock(); } @@ -583,11 +583,7 @@ public String getUsername() { public String getServices() { try { readLock.lock(); - if (context == null) { - return null; - } else { - return context.getServiceList().toString(); - } + return context == null ? null : context.getServiceList().toString(); } finally { readLock.unlock(); } @@ -688,7 +684,7 @@ public static String getCauseMessage(Throwable cause){ int size = aggregatedAlerts.size(); sb.append("Found ").append(size).append(" error(s) during preparing script:"); for (AggregateAlert aggregatedAlert : aggregatedAlerts) { - sb.append(aggregatedAlert.toString()).append(System.lineSeparator()); + sb.append(aggregatedAlert).append(System.lineSeparator()); } } else { sb.append("Found unknown errors during preparing script.").append(System.lineSeparator()).append("Returned message is \"") @@ -698,11 +694,7 @@ public static String getCauseMessage(Throwable cause){ } else if (causeCause instanceof InvocationTargetException) { InvocationTargetException e = (InvocationTargetException) causeCause; Throwable target = e.getTargetException(); - if (target.getCause() != null) { - return "Found error during running script: " + target.getCause().getMessage(); - } else { - return "Found error during running script: " + target.getMessage(); - } + return "Found error during running script: " + (target.getCause() != null ? target.getCause().getMessage() : target.getMessage()); } else { return causeCause.getMessage(); } @@ -712,10 +704,7 @@ public static String getCauseMessage(Throwable cause){ public String getProblem(){ try { readLock.lock(); - if (cause == null) { - return null; - } - return cause.getMessage(); + return cause == null ? null : cause.getMessage(); } finally { readLock.unlock(); } @@ -780,7 +769,7 @@ public void scriptCanceled() { } } - public void scriptInitFailed(final Throwable cause) { + public void scriptInitFailed(Throwable cause) { try { writeLock.lock(); changeState(ScriptState.FINISHED, ScriptStatus.INIT_FAILED); @@ -841,7 +830,7 @@ public void scriptRan() { } } - public void scriptPaused(final String pauseReason, final long pauseTimeout) { + public void scriptPaused(String pauseReason, long pauseTimeout) { try { writeLock.lock(); if (changeState(ScriptState.PAUSED, null)) { @@ -877,7 +866,7 @@ public void scriptNotStarted() { } } - public void scriptRunFailed(final Throwable cause) { + public void scriptRunFailed(Throwable cause) { try { writeLock.lock(); changeState(ScriptState.FINISHED, ScriptStatus.RUN_FAILED); @@ -914,14 +903,14 @@ public void close() throws IOException { writeLock.lock(); // stop class loader - if (this.classLoader != null && this.classLoader.getClass().isAssignableFrom(Closeable.class)) { - ((Closeable) this.classLoader).close(); + if(classLoader != null && classLoader.getClass().isAssignableFrom(Closeable.class)) { + ((Closeable)classLoader).close(); } this.classLoader = null; // stop script logger - if (this.scriptLogger != null) { - org.apache.log4j.Logger.getLogger(this.scriptLogger.getName()).removeAllAppenders(); + if(scriptLogger != null) { + org.apache.log4j.Logger.getLogger(scriptLogger.getName()).removeAllAppenders(); } this.scriptLogger = null; } finally { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptProgressListener.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptProgressListener.java index 651c8c8b..78733d26 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptProgressListener.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/TestScriptProgressListener.java @@ -19,7 +19,7 @@ public class TestScriptProgressListener implements IProgressListener { - private TestScriptDescription description; + private final TestScriptDescription description; public TestScriptProgressListener(TestScriptDescription description) { this.description = description; @@ -27,11 +27,11 @@ public TestScriptProgressListener(TestScriptDescription description) { @Override public void onProgressChanged(int progress) { - this.description.setProgress(progress); + description.setProgress(progress); } @Override public void onDetermineLanguage(SailfishURI languageURI) { - this.description.setLanguageURI(languageURI); + description.setLanguageURI(languageURI); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ZipReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ZipReport.java index e3d0ebbe..3119b548 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ZipReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ZipReport.java @@ -214,11 +214,7 @@ private void zipFile(IWorkspaceDispatcher dispatcher, ZipOutputStream zip, Strin } } private String buildPath(String path, String file) { - if (StringUtils.isEmpty(path)) { - return file; - } else { - return FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, file)); - } + return StringUtils.isEmpty(path) ? file : FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, file)); } private void removeFiles(File reportFolder) throws IOException { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionInfo.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionInfo.java index 50ec00e1..c032954d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionInfo.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionInfo.java @@ -23,7 +23,6 @@ import java.util.Map; import java.util.Set; -import com.exactpro.sf.scriptrunner.AbstractInfo; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -34,6 +33,7 @@ import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.configuration.suri.SailfishURIRule; import com.exactpro.sf.configuration.suri.SailfishURIUtils; +import com.exactpro.sf.scriptrunner.AbstractInfo; import com.google.common.collect.ImmutableMap; @SuppressWarnings("serial") @@ -46,10 +46,6 @@ public class ActionInfo extends AbstractInfo implements Cloneable, Serializable private Map commonColumns = Collections.emptyMap(); private String[] allowedMessageTypes; - public ActionInfo() { - // TODO Auto-generated constructor stub - } - public String getActionName() { return uri.getResourceName(); } @@ -150,15 +146,15 @@ public void setAllowedMessageTypes(String[] allowedMessageTypes) { public ActionInfo clone() { ActionInfo that = new ActionInfo(); - that.setURI(this.uri); - that.compatibleLanguageURIs.addAll(this.compatibleLanguageURIs); - that.setAnnotations(this.annotations); - that.setCustomColumns(this.customColumns); - that.setCommonColumns(this.commonColumns); - that.setMessageType(this.messageType); - that.setRequirements(this.requirements); - that.setReturnType(this.returnType); - that.setDescription(this.description); + that.setURI(uri); + that.compatibleLanguageURIs.addAll(compatibleLanguageURIs); + that.setAnnotations(annotations); + that.setCustomColumns(customColumns); + that.setCommonColumns(commonColumns); + that.setMessageType(messageType); + that.setRequirements(requirements); + that.setReturnType(returnType); + that.setDescription(description); return that; } @@ -176,13 +172,13 @@ public boolean equals(Object o) { ActionInfo that = (ActionInfo)o; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.uri, that.uri); - builder.append(this.compatibleLanguageURIs, that.compatibleLanguageURIs); - builder.append(this.requirements, that.requirements); - builder.append(this.returnType, that.returnType); - builder.append(this.messageType, that.messageType); - builder.append(this.annotations, that.annotations); - builder.append(this.customColumns, that.customColumns); + builder.append(uri, that.uri); + builder.append(compatibleLanguageURIs, that.compatibleLanguageURIs); + builder.append(requirements, that.requirements); + builder.append(returnType, that.returnType); + builder.append(messageType, that.messageType); + builder.append(annotations, that.annotations); + builder.append(customColumns, that.customColumns); return builder.isEquals(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionManager.java index abe25342..527e11c5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionManager.java @@ -77,7 +77,7 @@ public class ActionManager implements IActionManager, ILoadableManager { @Override protected Map, IActionCaller> initialValue() { return new HashMap<>(); - }; + } }; private class PluginComponent { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionRequirements.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionRequirements.java index 1c063f46..6e787fdd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionRequirements.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/ActionRequirements.java @@ -34,8 +34,8 @@ import com.exactpro.sf.scriptrunner.actionmanager.exceptions.ActionManagerException; public class ActionRequirements { - private Set requiredColumns = new HashSet(); - private Set deprecatedColumns = new HashSet(); + private final Set requiredColumns = new HashSet(); + private final Set deprecatedColumns = new HashSet(); protected ActionRequirements(CommonColumns commonColumns, CustomColumns customColumns) { if(commonColumns != null) { @@ -98,8 +98,8 @@ public boolean equals(Object o) { ActionRequirements that = (ActionRequirements)o; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.requiredColumns, that.requiredColumns); - builder.append(this.deprecatedColumns, that.deprecatedColumns); + builder.append(requiredColumns, that.requiredColumns); + builder.append(deprecatedColumns, that.deprecatedColumns); return builder.isEquals(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/IActionCaller.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/IActionCaller.java index b9fd669c..8c5e29f7 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/IActionCaller.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/IActionCaller.java @@ -24,9 +24,9 @@ import com.exactpro.sf.scriptrunner.actionmanager.exceptions.ActionNotFoundException; public interface IActionCaller { - public T call(String actionName, IActionContext actionContext) throws ActionCallException, ActionNotFoundException, InterruptedException; - public T call(String actionName, IActionContext actionContext, IMessage iMessage) throws ActionCallException, ActionNotFoundException, InterruptedException; - public T call(String actionName, IActionContext actionContext, BaseMessage baseMessage) throws ActionCallException, ActionNotFoundException, InterruptedException; - public T call(String actionName, IActionContext actionContext, Object message) throws ActionCallException, ActionNotFoundException, InterruptedException; - public T call(String actionName, IActionContext actionContext, HashMap hashMap) throws ActionCallException, ActionNotFoundException, InterruptedException; + T call(String actionName, IActionContext actionContext) throws ActionCallException, ActionNotFoundException, InterruptedException; + T call(String actionName, IActionContext actionContext, IMessage iMessage) throws ActionCallException, ActionNotFoundException, InterruptedException; + T call(String actionName, IActionContext actionContext, BaseMessage baseMessage) throws ActionCallException, ActionNotFoundException, InterruptedException; + T call(String actionName, IActionContext actionContext, Object message) throws ActionCallException, ActionNotFoundException, InterruptedException; + T call(String actionName, IActionContext actionContext, HashMap hashMap) throws ActionCallException, ActionNotFoundException, InterruptedException; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionContext.java index 31844171..6bd37d9b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionContext.java @@ -34,49 +34,49 @@ import com.exactpro.sf.util.KnownBugException; public interface IActionContext { - public CheckPoint getCheckPoint(); - public String getDescription(); - public SailfishURI getDictionaryURI(); - public String getId(); - public long getLine(); - public Object getMessage(String reference); + CheckPoint getCheckPoint(); + String getDescription(); + SailfishURI getDictionaryURI(); + String getId(); + long getLine(); + Object getMessage(String reference); /** * @deprecated Used in AML 2 only */ @Deprecated - public MessageCount getMessageCount(); - public IFilter getMessageCountFilter(); - public MetaContainer getMetaContainer(); + MessageCount getMessageCount(); + IFilter getMessageCountFilter(); + MetaContainer getMetaContainer(); /** * @deprecated Used in AML 2 only */ @Deprecated - public Map getNegativeMap(); - public String getReference(); - public IActionReport getReport(); - public IActionServiceManager getServiceManager(); + Map getNegativeMap(); + String getReference(); + IActionReport getReport(); + IActionServiceManager getServiceManager(); // from ScriptContext - public String getEnvironmentName(); - public long getScriptStartTime(); - public String getTestCaseName(); + String getEnvironmentName(); + long getScriptStartTime(); + String getTestCaseName(); // from DebugController - public void pauseScript(long timeout, String reason) throws InterruptedException; + void pauseScript(long timeout, String reason) throws InterruptedException; // from IScriptConfig - public Logger getLogger(); + Logger getLogger(); // from IDictionaryManager IDictionaryStructure getDictionary(SailfishURI dictionaryURI) throws RuntimeException; // from IMessageStorage - public Iterable loadMessages(int count, MessageFilter filter); - public void storeMessage(IMessage message); + Iterable loadMessages(int count, MessageFilter filter); + void storeMessage(IMessage message); - public String getServiceName(); + String getServiceName(); // from ScriptContext - public Set getServicesNames(); - public long getTimeout(); - public boolean isAddToReport(); - public boolean isCheckGroupsOrder(); - public boolean isReorderGroups(); + Set getServicesNames(); + long getTimeout(); + boolean isAddToReport(); + boolean isCheckGroupsOrder(); + boolean isReorderGroups(); /** * @deprecated @@ -85,9 +85,9 @@ public interface IActionContext { * {@link MetaContainer} can be obtained by calling {@link #getMetaContainer()} method. */ @Deprecated - public T getSystemColumn(String name); + T getSystemColumn(String name); - public IDataManager getDataManager(); + IDataManager getDataManager(); Set getUncheckedFields(); ClassLoader getPluginClassLoader(String pluginAlias); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionReport.java index f634c6c0..627e1b37 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionReport.java @@ -20,9 +20,9 @@ public interface IActionReport extends IGroupReport { * @deprecated Please use {@link #createEmbeddedReport(String, String)} */ @Deprecated - default public IGroupReport createActionGroup(String name, String description) { + default IGroupReport createActionGroup(String name, String description) { return createEmbeddedReport(name, description); } - public IActionReport createEmbeddedReport(String name, String description); + IActionReport createEmbeddedReport(String name, String description); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionServiceManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionServiceManager.java index 39f6eeaa..29c487c9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionServiceManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/IActionServiceManager.java @@ -26,16 +26,16 @@ public interface IActionServiceManager { // from IConnectionManager - public Service getService(ServiceName serviceName); - public ServiceName[] getServiceNames(); - public IService[] getStartedServices(); - public IServiceSettings getServiceSettings(ServiceName serviceName); - public Future addService(ServiceName serviceName, SailfishURI uri, IServiceSettings settings, IServiceNotifyListener exceptionListener); - public Future updateService(ServiceName serviceName, IServiceSettings settings, IServiceNotifyListener exceptionListener); - public Future initService(ServiceName serviceName, IServiceNotifyListener exceptionListener); - public Future disposeService(ServiceName serviceName, IServiceNotifyListener exceptionListener); - public Future removeService(ServiceName serviceName, IServiceNotifyListener exceptionListener); - public Future startService(ServiceName serviceName, IServiceNotifyListener exceptionListener); + Service getService(ServiceName serviceName); + ServiceName[] getServiceNames(); + IService[] getStartedServices(); + IServiceSettings getServiceSettings(ServiceName serviceName); + Future addService(ServiceName serviceName, SailfishURI uri, IServiceSettings settings, IServiceNotifyListener exceptionListener); + Future updateService(ServiceName serviceName, IServiceSettings settings, IServiceNotifyListener exceptionListener); + Future initService(ServiceName serviceName, IServiceNotifyListener exceptionListener); + Future disposeService(ServiceName serviceName, IServiceNotifyListener exceptionListener); + Future removeService(ServiceName serviceName, IServiceNotifyListener exceptionListener); + Future startService(ServiceName serviceName, IServiceNotifyListener exceptionListener); - public ServiceInfo getServiceInfo(ServiceName serviceName); + ServiceInfo getServiceInfo(ServiceName serviceName); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionContextWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionContextWrapper.java index f75abe93..de6af703 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionContextWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionContextWrapper.java @@ -304,7 +304,7 @@ public IDataManager getDataManager() { @Override public Set getUncheckedFields() { - return this.unchekedFields; + return unchekedFields; } public ActionContextWrapper setUncheckedFields(Set uncheckedFields) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionReport.java index b638e64d..774f8bc9 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/actionmanager/actioncontext/impl/ActionReport.java @@ -44,7 +44,7 @@ public class ActionReport implements IActionReport { private final boolean updateStatus; private final IWorkspaceDispatcher workspaceDispatcher; - private Set elementStats = new HashSet<>(); + private final Set elementStats = new HashSet<>(); private Pair description; private ActionReport parent; private ActionReport child; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/BroadcastScriptReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/BroadcastScriptReport.java index 00f68c98..72550eea 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/BroadcastScriptReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/BroadcastScriptReport.java @@ -15,14 +15,11 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.impl; -import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; -import com.exactpro.sf.scriptrunner.reportbuilder.textformatter.TextColor; -import com.exactpro.sf.scriptrunner.reportbuilder.textformatter.TextStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,18 +34,20 @@ import com.exactpro.sf.scriptrunner.OutcomeCollector; import com.exactpro.sf.scriptrunner.ScriptContext; import com.exactpro.sf.scriptrunner.StatusDescription; +import com.exactpro.sf.scriptrunner.reportbuilder.textformatter.TextColor; +import com.exactpro.sf.scriptrunner.reportbuilder.textformatter.TextStyle; public class BroadcastScriptReport implements IScriptReport { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private final List listeners; - private boolean actionCreated = false; + private boolean actionCreated; - private boolean testCaseCreated = false; + private boolean testCaseCreated; - public BroadcastScriptReport(final List listeners) { + public BroadcastScriptReport(List listeners) { this.listeners = new CopyOnWriteArrayList<>(listeners); } @@ -149,7 +148,7 @@ public void createAction(String name, String serviceName, String action, String @Override public boolean isActionCreated() { - return this.actionCreated; + return actionCreated; } @Override @@ -320,8 +319,9 @@ public IReportStats getReportStats() { for (IScriptReport listener: listeners) { try { IReportStats stats = listener.getReportStats(); - if (stats != null) - return stats; + if(stats != null) { + return stats; + } } catch (Exception e) { logger.error("Error while firing get report stats with {} listener", listener.getClass().getName(), e); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java index 96e66a1f..b9c2aeac 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultConnectionManager.java @@ -56,6 +56,7 @@ import com.exactpro.sf.scriptrunner.IServiceNotifyListener; import com.exactpro.sf.scriptrunner.services.IServiceFactory; import com.exactpro.sf.services.ChangeEnvironmentEvent; +import com.exactpro.sf.services.ChangeEnvironmentEvent.Status; import com.exactpro.sf.services.CollectorServiceHandler; import com.exactpro.sf.services.DefaultServiceContext; import com.exactpro.sf.services.EnvironmentEvent; @@ -68,6 +69,7 @@ import com.exactpro.sf.services.OptionalServiceHandlerWrapper; import com.exactpro.sf.services.ServiceDescription; import com.exactpro.sf.services.ServiceEvent; +import com.exactpro.sf.services.ServiceEvent.Level; import com.exactpro.sf.services.ServiceEvent.Type; import com.exactpro.sf.services.ServiceEventFactory; import com.exactpro.sf.services.ServiceException; @@ -108,11 +110,11 @@ public final class DefaultConnectionManager implements IConnectionManager { private final Set usedServices; public DefaultConnectionManager( - final IServiceFactory staticServiceFactory, - final IServiceStorage storage, - final IEnvironmentStorage envStorage, - final IVariableSetStorage variableSetStorage, - final IServiceContext serviceContext) { + IServiceFactory staticServiceFactory, + IServiceStorage storage, + IEnvironmentStorage envStorage, + IVariableSetStorage variableSetStorage, + IServiceContext serviceContext) { this.staticServiceFactory = Objects.requireNonNull(staticServiceFactory, "'Static service factory' parameter"); @@ -140,7 +142,7 @@ public DefaultConnectionManager( for (ServiceDescription serviceDescription : this.storage.getServiceDescriptions()) { serviceName = new ServiceName(serviceDescription.getEnvironment(), serviceDescription.getName()); IService service = staticServiceFactory.createService(serviceDescription.getType()); - if (this.services.put(serviceName, new ServiceContainer(service, serviceDescription)) != null) { + if(services.put(serviceName, new ServiceContainer(service, serviceDescription)) != null) { logger.warn("Service {} already exists", serviceName); } initService(serviceName, null); @@ -152,27 +154,27 @@ public DefaultConnectionManager( @Override public Service getService(ServiceName serviceName) { try { - this.lock.readLock().lock(); + lock.readLock().lock(); - final ServiceContainer serviceContainer = this.services.get(serviceName); + ServiceContainer serviceContainer = services.get(serviceName); return serviceContainer != null ? (Service) serviceContainer.getService() : null; } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @Override public void dispose() { try { - this.lock.writeLock().lock(); + lock.writeLock().lock(); try { - if (!this.serviceExecutor.isShutdown()) { + if(!serviceExecutor.isShutdown()) { - this.serviceExecutor.shutdown(); + serviceExecutor.shutdown(); - if (!this.serviceExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS)) { + if(!serviceExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS)) { logger.warn("Some Threads from ConnectionManager remained alive"); } } @@ -181,13 +183,13 @@ public void dispose() { logger.error(e.getMessage(), e); } - for (Entry entry : this.services.entrySet()) { + for(Entry entry : services.entrySet()) { try { logger.info("Disposing [{}] service started...", entry.getKey()); - final ServiceContainer serviceContainer = entry.getValue(); + ServiceContainer serviceContainer = entry.getValue(); disposeService(serviceContainer.getService()); @@ -198,12 +200,12 @@ public void dispose() { } } } finally { - this.lock.writeLock().unlock(); + lock.writeLock().unlock(); } } @Override - public Future addService(final ServiceDescription serviceDescription, final IServiceNotifyListener notifyListener) { + public Future addService(ServiceDescription serviceDescription, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(() -> addServiceWithoutNewThread(serviceDescription.clone(), notifyListener)); } @@ -211,7 +213,7 @@ public Future addService(final ServiceDescription serviceDescription, final I * @param serviceDescription * @param notifyListener */ - private void addServiceWithoutNewThread(ServiceDescription serviceDescription, final IServiceNotifyListener notifyListener) { + private void addServiceWithoutNewThread(ServiceDescription serviceDescription, IServiceNotifyListener notifyListener) { ServiceName serviceName = serviceDescription.getServiceName(); try { @@ -241,11 +243,11 @@ private void addServiceWithoutNewThread(ServiceDescription serviceDescription, f ServiceContainer current = new ServiceContainer(service, serviceDescription); logger.info("Start adding service to storage: {}", serviceName); - this.storage.addServiceDescription(serviceDescription); + storage.addServiceDescription(serviceDescription); logger.info("Service was successfully added to storage: {}", serviceName); logger.info("Start adding ServiceContainer: {}", serviceName); - this.services.put(serviceName, current); + services.put(serviceName, current); logger.info("ServiceContainer was successfully added: {}", serviceName); try { @@ -253,8 +255,8 @@ private void addServiceWithoutNewThread(ServiceDescription serviceDescription, f } catch (ServiceException | EPSCommonException ignore) { // we must ignore service exception during add } finally { - ServiceEvent event = ServiceEventFactory.createServiceChangeUpdateEvent(serviceName, ServiceEvent.Level.INFO, - ServiceEvent.Type.CREATED, "Service created", "", null); + ServiceEvent event = ServiceEventFactory.createServiceChangeUpdateEvent(serviceName, Level.INFO, + Type.CREATED, "Service created", "", null); environmentMonitor.onEvent(event); } logger.info("Service {} has been added", serviceName); @@ -267,7 +269,7 @@ private void addServiceWithoutNewThread(ServiceDescription serviceDescription, f } @Override - public Future removeService(final ServiceName serviceName, final IServiceNotifyListener notifyListener) { + public Future removeService(ServiceName serviceName, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(new Runnable() { @Override public void run() { @@ -281,7 +283,7 @@ protected void removeServiceWithoutNewThread(ServiceName serviceName, IServiceNo lock.writeLock().lock(); logger.info("Start delete service: {}", serviceName); - ServiceContainer serviceContainer = this.services.get(serviceName); + ServiceContainer serviceContainer = services.get(serviceName); if (serviceContainer == null) { throw new ServiceException("Could not find " + serviceName + " service"); @@ -292,17 +294,17 @@ protected void removeServiceWithoutNewThread(ServiceName serviceName, IServiceNo disposeService(serviceContainer.getService()); try { - ServiceEvent event = ServiceEventFactory.createServiceChangeUpdateEvent(serviceName, ServiceEvent.Level.INFO, - ServiceEvent.Type.DISPOSED, "Service deleted", "", null); + ServiceEvent event = ServiceEventFactory.createServiceChangeUpdateEvent(serviceName, Level.INFO, + Type.DISPOSED, "Service deleted", "", null); environmentMonitor.onEvent(event); } catch (EPSCommonException ignore){} logger.info("Start delete service {} from storage", serviceName); - this.storage.removeServiceDescription(description); + storage.removeServiceDescription(description); logger.info("Service was successfully deleted from storage: {}", serviceName); logger.info("Start delete ServiceContainer {}", serviceName); - this.services.remove(serviceName); + services.remove(serviceName); logger.info("ServiceContainer was successfully deleted: {}", serviceName); logger.info("Service {} has been removed", serviceName); @@ -315,7 +317,7 @@ protected void removeServiceWithoutNewThread(ServiceName serviceName, IServiceNo } @Override - public Future updateService(final ServiceDescription serviceDescription, final IServiceNotifyListener notifyListener) { + public Future updateService(ServiceDescription serviceDescription, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(new Runnable() { @Override public void run() { @@ -323,7 +325,7 @@ public void run() { try { lock.writeLock().lock(); - final ServiceContainer serviceContainer = services.get(serviceName); + ServiceContainer serviceContainer = services.get(serviceName); if (serviceContainer == null) { throw new StorageException("ServiceContainer " + serviceName + " does not exist"); @@ -346,7 +348,7 @@ public void run() { } @Override - public Future initService(final ServiceName serviceName, final IServiceNotifyListener notifyListener) { + public Future initService(ServiceName serviceName, IServiceNotifyListener notifyListener) { if (serviceName == null) { throw new ServiceException("serviceName is null"); } @@ -359,10 +361,10 @@ public void run() { }); } - protected void initServiceWithoutNewThread(final ServiceName serviceName, final IServiceNotifyListener notifyListener) { + protected void initServiceWithoutNewThread(ServiceName serviceName, IServiceNotifyListener notifyListener) { try { lock.readLock().lock(); - final ServiceContainer serviceContainer = services.get(serviceName); + ServiceContainer serviceContainer = services.get(serviceName); if (serviceContainer == null) { throw new ServiceException("Could not find " + serviceName + " serviceContainer"); @@ -372,10 +374,10 @@ protected void initServiceWithoutNewThread(final ServiceName serviceName, final ServiceDescription description = serviceContainer.getServiceDescription(); if (service == null) { - throw new ServiceException("Could not find " + serviceName.toString() + " service"); + throw new ServiceException("Could not find " + serviceName + " service"); } if (description == null) { - throw new ServiceException("Could not find " + serviceName.toString() + " ServiceDescription"); + throw new ServiceException("Could not find " + serviceName + " ServiceDescription"); } if (description.getServiceHandlerClassName() == null) { throw new ServiceException("HandlerClassName is null for [" + description.getName() + "] service"); @@ -418,7 +420,7 @@ protected void initServiceWithoutNewThread(final ServiceName serviceName, final "Got following errors during dictionary validation:\n"); for (DictionaryValidationError error : errors) { - message.append(error.toString() + "\n"); + message.append(error + "\n"); } String eventMessage = message.toString(); @@ -465,7 +467,7 @@ protected void initServiceWithoutNewThread(final ServiceName serviceName, final } @Override - public Future startService(final ServiceName serviceName, final IServiceNotifyListener notifyListener) { + public Future startService(ServiceName serviceName, IServiceNotifyListener notifyListener) { if (serviceName == null) { throw new ServiceException("serviceName is null"); } @@ -475,7 +477,7 @@ public Future startService(final ServiceName serviceName, final IServiceNotif public void run() { try { lock.readLock().lock(); - final ServiceContainer serviceContainer = services.get(serviceName); + ServiceContainer serviceContainer = services.get(serviceName); if (serviceContainer == null) { throw new ServiceException("Could not find " + serviceName + " serviceContainer"); @@ -484,7 +486,7 @@ public void run() { IService service = serviceContainer.getService(); if (service == null) { - throw new ServiceException("Could not find " + serviceName.toString() + " service"); + throw new ServiceException("Could not find " + serviceName + " service"); } if (service.getStatus() == ServiceStatus.INITIALIZED) { @@ -492,7 +494,7 @@ public void run() { service.start(); } } else { - throw new ServiceException("Service " + serviceName.toString() + " already started or not initialized"); + throw new ServiceException("Service " + serviceName + " already started or not initialized"); } } catch (Exception e) { @@ -506,7 +508,7 @@ public void run() { } @Override - public Future disposeService(final ServiceName serviceName, final IServiceNotifyListener notifyListener) { + public Future disposeService(ServiceName serviceName, IServiceNotifyListener notifyListener) { if (serviceName == null) { throw new ServiceException("serviceName is null"); } @@ -516,7 +518,7 @@ public Future disposeService(final ServiceName serviceName, final IServiceNot public void run() { try { lock.readLock().lock(); - final ServiceContainer serviceContainer = services.get(serviceName); + ServiceContainer serviceContainer = services.get(serviceName); if (serviceContainer == null) { throw new ServiceException("Could not find " + serviceName + " serviceContainer"); } @@ -547,7 +549,7 @@ public void run() { } @Override - public Future removeEnvironment(final String envName, final IServiceNotifyListener notifyListener) { + public Future removeEnvironment(String envName, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(new Runnable() { @Override public void run() { @@ -564,7 +566,7 @@ public void run() { } envStorage.remove(envName); - EnvironmentEvent event = new ChangeEnvironmentEvent(envName, "Environment has been deleted", ChangeEnvironmentEvent.Status.DELETED); + EnvironmentEvent event = new ChangeEnvironmentEvent(envName, "Environment has been deleted", Status.DELETED); environmentMonitor.onEvent(event); } else { throw new IllegalArgumentException("Environment " + envName + " has not been deleted"); @@ -582,22 +584,22 @@ public void run() { @Override public List getEnvironmentList() { try { - this.lock.readLock().lock(); + lock.readLock().lock(); return envStorage.list(); } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @Override - public Future addEnvironment(final String envName, final IServiceNotifyListener notifyListener) { + public Future addEnvironment(String envName, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(new Runnable() { @Override public void run() { try { lock.writeLock().lock(); envStorage.add(envName); - EnvironmentEvent event = new ChangeEnvironmentEvent(envName, "Environment was added", ChangeEnvironmentEvent.Status.ADDED); + EnvironmentEvent event = new ChangeEnvironmentEvent(envName, "Environment was added", Status.ADDED); environmentMonitor.onEvent(event); } catch (Exception e) { exceptionNotify(notifyListener, e); @@ -610,7 +612,7 @@ public void run() { } @Override - public Future renameEnvironment(final String oldEnvName, final String newEnvName, final IServiceNotifyListener notifyListener) { + public Future renameEnvironment(String oldEnvName, String newEnvName, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(new Runnable() { @Override public void run() { @@ -636,7 +638,7 @@ public void run() { Set startedServices = new HashSet<>(); Set environmentServices = new HashSet<>(); for (Entry entry : services.entrySet()) { - final ServiceContainer serviceContainer = entry.getValue(); + ServiceContainer serviceContainer = entry.getValue(); if (entry.getKey().getEnvironment().equals(oldEnvName)) { environmentServices.add(entry.getKey()); if (serviceContainer.getService().getStatus() == ServiceStatus.STARTED @@ -664,7 +666,7 @@ public void run() { addServiceWithoutNewThread(description, notifyListener); } - ChangeEnvironmentEvent event = new ChangeEnvironmentEvent(oldEnvName, "Environment was renamed", ChangeEnvironmentEvent.Status.RENAMED); + ChangeEnvironmentEvent event = new ChangeEnvironmentEvent(oldEnvName, "Environment was renamed", Status.RENAMED); event.setNewEnvName(newEnvName); environmentMonitor.onEvent(event); } catch (Exception e) { @@ -680,20 +682,20 @@ public void run() { @Override public ServiceName[] getServiceNames() { try { - this.lock.readLock().lock(); - return this.services.keySet().toArray(new ServiceName[this.services.size()]); + lock.readLock().lock(); + return services.keySet().toArray(new ServiceName[services.size()]); } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @Override public IService[] getStartedServices() { try { - this.lock.readLock().lock(); + lock.readLock().lock(); List returned = new ArrayList<>(); - for (final ServiceContainer serviceContainer : this.services.values()) { + for(ServiceContainer serviceContainer : services.values()) { if (serviceContainer.getService().getStatus() == ServiceStatus.STARTED || serviceContainer.getService().getStatus() == ServiceStatus.WARNING) { returned.add(serviceContainer.getService()); @@ -702,7 +704,7 @@ public IService[] getStartedServices() { return returned.toArray(new IService[returned.size()]); } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @@ -729,7 +731,7 @@ private List getStartedServices(String environmentName) { @Override public void cleanup(List services) { try { - this.lock.readLock().lock(); + lock.readLock().lock(); logger.debug("cleaning up services: {}", services); for(String serviceName : services) { @@ -758,23 +760,23 @@ public void cleanup(List services) { logger.debug("cleanup completed"); } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @Override public ServiceDescription[] getServicesDescriptions() { try { - this.lock.readLock().lock(); + lock.readLock().lock(); List descriptions = new ArrayList<>(); - for (final ServiceContainer serviceContainer : this.services.values()) { + for(ServiceContainer serviceContainer : services.values()) { descriptions.add(serviceContainer.getServiceDescription().clone()); } return descriptions.toArray(new ServiceDescription[descriptions.size()]); } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @@ -782,11 +784,11 @@ public ServiceDescription[] getServicesDescriptions() { @Override public ServiceDescription getServiceDescription(ServiceName serviceName) { try { - this.lock.readLock().lock(); - final ServiceContainer serviceContainer = services.get(serviceName); + lock.readLock().lock(); + ServiceContainer serviceContainer = services.get(serviceName); return serviceContainer != null ? serviceContainer.getServiceDescription().clone() : null; } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @@ -801,7 +803,7 @@ public synchronized void setServiceUsed(String[] names) throws InterruptedExcept for (String name : names) { - while (this.usedServices.contains(name)) { + while(usedServices.contains(name)) { try { logger.info("wait for unlock service {} begin", name); wait(); @@ -810,7 +812,7 @@ public synchronized void setServiceUsed(String[] names) throws InterruptedExcept } } - this.usedServices.add(name); + usedServices.add(name); setStoreMessageMode(name, true); } @@ -826,7 +828,7 @@ public synchronized void setServiceNotUsed(String[] names) { Arrays.sort(names); for (String name : names) { - this.usedServices.remove(name); + usedServices.remove(name); setStoreMessageMode(name, false); } @@ -836,7 +838,7 @@ public synchronized void setServiceNotUsed(String[] names) { @Override public synchronized Set getUsedServices() { - return new HashSet<>(this.usedServices); + return new HashSet<>(usedServices); } @Override @@ -870,7 +872,7 @@ protected void exceptionNotify(IServiceNotifyListener notifyListener, Exception } @Override - public Future copyService(final ServiceName from, final ServiceName to, final IServiceNotifyListener notifyListener) { + public Future copyService(ServiceName from, ServiceName to, IServiceNotifyListener notifyListener) { return serviceExecutor.submit(new Runnable() { @Override public void run() { @@ -879,7 +881,7 @@ public void run() { if (services.containsKey(to)) { throw new StorageException("Service " + to + " already exits"); } - final ServiceContainer serviceContainer = services.get(from); + ServiceContainer serviceContainer = services.get(from); if (serviceContainer == null) { throw new ServiceException("Could not find " + from + " ServiceContainer"); @@ -912,8 +914,8 @@ public void run() { @Override public IServiceSettings getServiceSettings(ServiceName serviceName) { try { - this.lock.readLock().lock(); - ServiceContainer serviceContainer = this.services.get(serviceName); + lock.readLock().lock(); + ServiceContainer serviceContainer = services.get(serviceName); if (serviceContainer == null) { throw new ServiceException("Could not find " + serviceName + " ServiceContainer"); @@ -930,7 +932,7 @@ public IServiceSettings getServiceSettings(ServiceName serviceName) { return result; } finally { - this.lock.readLock().unlock(); + lock.readLock().unlock(); } } @@ -1050,7 +1052,7 @@ private void disposeService(IService service) { } private void setStoreMessageMode(String serviceName, boolean store) { - ServiceContainer serviceContainer = this.services.get(ServiceName.parse(serviceName)); + ServiceContainer serviceContainer = services.get(ServiceName.parse(serviceName)); if (serviceContainer != null) { OptionalServiceHandlerWrapper handler = serviceContainer.getHandlerWrapper(); handler.storeMessages(store); @@ -1060,7 +1062,7 @@ private void setStoreMessageMode(String serviceName, boolean store) { private Set loadProcessedMessageTypes(ServiceDescription description) throws SailfishURIException { String value = description.getSettings().getStoredMessageTypes(); if (StringUtils.isNotBlank(value)) { - value = ServiceUtil.loadStringFromAlias(this.serviceContext.getDataManager(), value, ","); + value = ServiceUtil.loadStringFromAlias(serviceContext.getDataManager(), value, ","); return stream(value.split(",")) .map(type -> type.trim()) .filter(StringUtils::isNoneEmpty) @@ -1093,7 +1095,7 @@ OptionalServiceHandlerWrapper getHandlerWrapper() { } void setOriginServiceHandler(IServiceHandler serviceHandler) { - this.handlerWrapper.setOriginServiceHandler(serviceHandler); + handlerWrapper.setOriginServiceHandler(serviceHandler); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultEnvironmentMonitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultEnvironmentMonitor.java index cd91fe8e..8b42f42e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultEnvironmentMonitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultEnvironmentMonitor.java @@ -24,9 +24,9 @@ public class DefaultEnvironmentMonitor implements IEnvironmentMonitor { - private IConnectionManager manager; + private final IConnectionManager manager; - private IServiceStorage storage; + private final IServiceStorage storage; public DefaultEnvironmentMonitor(IConnectionManager manager, IServiceStorage storage) { this.manager = manager; @@ -35,7 +35,7 @@ public DefaultEnvironmentMonitor(IConnectionManager manager, IServiceStorage sto @Override public void onEvent(ServiceEvent event) { - this.storage.addServiceEvent(this.manager.getServiceDescription(event.getServiceName()), event); + storage.addServiceEvent(manager.getServiceDescription(event.getServiceName()), event); for (IEnvironmentListener listener : manager.getEnvironmentListeners()) { listener.onEvent(event); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultScriptConfig.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultScriptConfig.java index a4bda53c..7628982f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultScriptConfig.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/DefaultScriptConfig.java @@ -52,40 +52,40 @@ public DefaultScriptConfig(ScriptSettings settings, String reportFolder, String @Override public String getName() { - return this.scriptSettings.getScriptName(); + return scriptSettings.getScriptName(); } @Override public Set getPropertiesKeys() { - return this.scriptSettings.getPropertiesKeys(); + return scriptSettings.getPropertiesKeys(); } @Override public String getProperty(String name) { - return this.scriptSettings.getProperty(name); + return scriptSettings.getProperty(name); } @Override public String getReportFolder() { - return this.reportFolder; + return reportFolder; } @Override public Logger getLogger() { - return this.scriptLogger; + return scriptLogger; } @Override public boolean isAddMessagesToReport() { - return this.scriptSettings.isAddMessagesToReport(); + return scriptSettings.isAddMessagesToReport(); } @Override public String getDescription() { - return this.description; + return description; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportAppender.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportAppender.java index 3a57fd40..8f5e1902 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportAppender.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportAppender.java @@ -19,6 +19,7 @@ import java.util.List; import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.Level; import org.apache.log4j.spi.LoggingEvent; import com.exactpro.sf.scriptrunner.LoggerRow; @@ -36,7 +37,7 @@ public ReportAppender(){ header.add("Class"); header.add("Message"); header.add("StackTrace"); - setThreshold(org.apache.log4j.Level.WARN); //No debug and info messages + setThreshold(Level.WARN); //No debug and info messages } List rows; @@ -61,8 +62,9 @@ public void setHeader(List header) { @Override public void close() { - if(this.closed) - return; + if(closed) { + return; + } this.closed = true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportTable.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportTable.java index bd625fc1..aa1edf6d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportTable.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ReportTable.java @@ -34,7 +34,7 @@ public class ReportTable { private final List header; private final List> rows = new ArrayList<>(); - private boolean hasCheckPoints = false; + private boolean hasCheckPoints; public ReportTable(String name, List header) { if(StringUtils.isBlank(name)) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ScriptReportWithLogs.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ScriptReportWithLogs.java index 50deb10a..75f63dde 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ScriptReportWithLogs.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/ScriptReportWithLogs.java @@ -66,7 +66,7 @@ public class ScriptReportWithLogs implements IScriptReport { private long startTime; private String lastTestCaseName; - public ScriptReportWithLogs(final IScriptReport report, final Set excludedMessages) { + public ScriptReportWithLogs(IScriptReport report, Set excludedMessages) { this.report = report; this.excludedMessages = excludedMessages.isEmpty() ? excludedMessages : excludedMessages.stream() .map(String::toLowerCase) @@ -150,7 +150,7 @@ private void onTestCase(StatusDescription status) { } // Reporting log messages: - if (reportAppender.getRows().size() > 0) { + if(!reportAppender.getRows().isEmpty()) { report.createLogTable(reportAppender.getHeader(), reportAppender.getRows()); } } finally { @@ -290,7 +290,7 @@ private void addMessageTable(IEnvironmentManager environmentManager, IDictionary boolean hasCheckPoints = false; for (MessageRow msg : messages) { - if (this.excludedMessages.contains(StringUtils.lowerCase(msg.getMsgName()))) { + if(excludedMessages.contains(StringUtils.lowerCase(msg.getMsgName()))) { continue; } @@ -333,8 +333,9 @@ private void addMessageTable(IEnvironmentManager environmentManager, IDictionary } private void markUnexpected(MessageRow message, Set unexpectedMessages) { - if (unexpectedMessages.isEmpty()) + if(unexpectedMessages.isEmpty()) { return; + } Iterator iter = unexpectedMessages.iterator(); while (iter.hasNext()) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/StatisticScriptReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/StatisticScriptReport.java index 5a8d4b64..bf73e2f5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/StatisticScriptReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/StatisticScriptReport.java @@ -15,8 +15,6 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.impl; -import java.util.Arrays; -import java.util.HashSet; import java.util.List; import java.util.Set; @@ -65,9 +63,9 @@ public void createReport(ScriptContext context, String name, String description, //this.environmentName = environmentName; - if(this.statisticsService != null) { + if(statisticsService != null) { - this.statisticsService.matrixStarted(matrixName, reportFolder, scriptRunId, environmentName, userName, tags, + statisticsService.matrixStarted(matrixName, reportFolder, scriptRunId, environmentName, userName, tags, context.getScriptDescriptionId()); } @@ -76,14 +74,14 @@ public void createReport(ScriptContext context, String name, String description, @Override public void createException(Throwable cause) { - if(this.statisticsService != null && actionCouter == 1) { + if(statisticsService != null && actionCouter == 1) { statisticsService.matrixEception(matrixName, cause); } } @Override public void closeReport() { - if(this.statisticsService != null) { + if(statisticsService != null) { statisticsService.matrixFinished(matrixName); } } @@ -94,8 +92,8 @@ public void createTestCase(String reference, String description, int order, int String name = ReportUtils.generateTestCaseName(reference, matrixOrder, type); logger.debug("Create test case {}", name); - if(this.statisticsService != null) { - this.statisticsService.testCaseStarted(this.matrixName, tcId, name.replaceAll("\\W", "_"), + if(statisticsService != null) { + statisticsService.testCaseStarted(matrixName, tcId, name.replaceAll("\\W", "_"), description, order, tcHash, tags); } @@ -105,7 +103,7 @@ public void createTestCase(String reference, String description, int order, int @Override public void closeTestCase(StatusDescription status) { - if(this.statisticsService != null) { + if(statisticsService != null) { String failReason = null; @@ -115,7 +113,7 @@ public void closeTestCase(StatusDescription status) { } - this.statisticsService.testCaseFinished(this.matrixName, status.getStatus(), failReason, status.getKnownBugs()); + statisticsService.testCaseFinished(matrixName, status.getStatus(), failReason, status.getKnownBugs()); } @@ -127,9 +125,9 @@ public void closeTestCase(StatusDescription status) { public void createAction(String name, String serviceName, String action, String msg, String description, Object inputParameters, CheckPoint checkPoint, String tag, int hash, List verificationsOrder) { - if(this.statisticsService != null) { + if(statisticsService != null) { - this.statisticsService.actionStarted(matrixName, serviceName, action, msg, description, actionCouter++, tag, + statisticsService.actionStarted(matrixName, serviceName, action, msg, description, actionCouter++, tag, hash); } @@ -140,9 +138,9 @@ public void createAction(String name, String serviceName, String action, String public void createAction(String name, String serviceName, String action, String msg, String description, List inputParameters, CheckPoint checkPoint, String tag, int hash, List verificationsOrder) { - if(this.statisticsService != null) { + if(statisticsService != null) { - this.statisticsService.actionStarted(matrixName, serviceName, action, msg, description, actionCouter++, tag, + statisticsService.actionStarted(matrixName, serviceName, action, msg, description, actionCouter++, tag, hash); } @@ -152,7 +150,7 @@ public void createAction(String name, String serviceName, String action, String @Override public void closeAction(StatusDescription status, Object actionResult) { - if(this.statisticsService != null) { + if(statisticsService != null) { String failReason = null; @@ -162,7 +160,7 @@ public void closeAction(StatusDescription status, Object actionResult) { } - this.statisticsService.actionFinished(matrixName, status.getStatus(), failReason); + statisticsService.actionFinished(matrixName, status.getStatus(), failReason); } @@ -170,8 +168,8 @@ public void closeAction(StatusDescription status, Object actionResult) { @Override public void createVerification(String name, String description, StatusDescription status, ComparisonResult result) { - if (this.statisticsService != null) { - this.statisticsService.addKnownBugsToActionRun(matrixName, result); + if(statisticsService != null) { + statisticsService.addKnownBugsToActionRun(matrixName, result); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/HtmlReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/HtmlReport.java index 62c9bd3c..ba0659fd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/HtmlReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/HtmlReport.java @@ -16,7 +16,11 @@ package com.exactpro.sf.scriptrunner.impl.htmlreport; import static com.exactpro.sf.common.messages.structures.StructureUtils.getAttributeValue; +import static com.exactpro.sf.scriptrunner.StatusType.CONDITIONALLY_FAILED; +import static com.exactpro.sf.scriptrunner.StatusType.CONDITIONALLY_PASSED; import static com.exactpro.sf.scriptrunner.StatusType.FAILED; +import static com.exactpro.sf.scriptrunner.StatusType.PASSED; +import static com.exactpro.sf.scriptrunner.StatusType.SKIPPED; import static java.util.Comparator.comparingLong; import java.io.BufferedWriter; @@ -145,24 +149,24 @@ public class HtmlReport implements IScriptReport { private Report report; private TestCase testCase; private Action action; - private Deque actionGroups = new ArrayDeque<>(); + private final Deque actionGroups = new ArrayDeque<>(); - private int totalTestCases = 0; - private int passedTestCases = 0; - private int cpTestCases = 0; - private int failedTestCases = 0; - private int notAppTestCases = 0; + private int totalTestCases; + private int passedTestCases; + private int cpTestCases; + private int failedTestCases; + private int notAppTestCases; - private int nodeId = 0; - private int verificationId = 0; + private int nodeId; + private int verificationId; private int sequenceId = 100000; private OutcomeCollector outcomes; private IReportStats reportStats = new ReportStats(); - private ArrayList containers = new ArrayList<>(); + private final ArrayList containers = new ArrayList<>(); private Map dataMap; - private RelevantMessagesSortingMode relevantMessagesSortingMode; + private final RelevantMessagesSortingMode relevantMessagesSortingMode; public HtmlReport(String reportFolder, IWorkspaceDispatcher workspaceDispatcher, IDictionaryManager dictionaryManager, RelevantMessagesSortingMode relevantMessagesSortingMode) { this.reportFolder = reportFolder; @@ -313,8 +317,8 @@ public void closeTestCase(StatusDescription status) { } writeElements(testCaseWriter, testCase.getElements(), 5); - boolean passed = status.getStatus() == StatusType.PASSED; - boolean conditionallyPassed = status.getStatus() == StatusType.CONDITIONALLY_PASSED; + boolean passed = status.getStatus() == PASSED; + boolean conditionallyPassed = status.getStatus() == CONDITIONALLY_PASSED; long duration = testCase.getFinishTime().getTime() - testCase.getStartTime().getTime(); writeLine(testCaseWriter, "", 4); @@ -495,7 +499,7 @@ public void closeAction(StatusDescription status, Object actionResult) { MachineLearningData data = action.getMachineLearningData(); - if(data != null && status.getStatus() == StatusType.FAILED) { + if(data != null && status.getStatus() == FAILED) { data.setPeriodEnd(finishTime); dataMap.put(action.getId(), data); } @@ -552,7 +556,7 @@ public void closeGroup(StatusDescription status) { private void writeStatus(Writer writer, StatusDescription status, int indentSize) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException { logger.debug("writeStatus - context: {}, status: {}, description: {}", currentContext, status.getStatus(), status.getDescription()); - if(status.getStatus() != StatusType.PASSED) { + if(status.getStatus() != PASSED) { createNode(writer, "Status", NodeType.STATUS, status.getStatus(), null, indentSize); TemplateWrapper statusTableTemplate = templateWrapperFactory.createWrapper("status_table.ftlh"); @@ -631,7 +635,7 @@ private void writeVerifications(Writer writer, List verifications, } Verification first = verifications.get(0); - if(first.getStatusDescription().getStatus() == StatusType.FAILED){ + if(first.getStatusDescription().getStatus() == FAILED) { writeLine(writer, "
", indentSize); writeLine(writer, "
", indentSize); writeLine(writer, "
", indentSize); @@ -641,7 +645,7 @@ private void writeVerifications(Writer writer, List verifications, Verification v = verifications.get(i); if(i == MAX_VERIFICATIONS) { - String fileName = testCase.getName() + "_verifications_" + (++verificationId) + ".html"; + String fileName = testCase.getName() + "_verifications_" + ++verificationId + ".html"; writeLine(writer, "", indentSize); @@ -661,7 +665,7 @@ private void writeVerifications(Writer writer, List verifications, boolean hasDescription = StringUtils.isNotBlank(description); boolean hasParameters = parameters != null && !parameters.isEmpty(); - boolean isPassed = status == StatusType.PASSED; + boolean isPassed = status == PASSED; boolean isVerificationNode = hasParameters || !isPassed; boolean isContainOnlyComparison = hasParameters && isPassed; @@ -1009,12 +1013,12 @@ public void createException(Throwable cause) { } private void writeException(Writer writer, Throwable cause) { - createNode(writer, "Status", NodeType.STATUS, StatusType.FAILED, null, 5); + createNode(writer, "Status", NodeType.STATUS, FAILED, null, 5); try { TemplateWrapper statusTableTemplate = templateWrapperFactory.createWrapper("status_table.ftlh"); - statusTableTemplate.setData("status", StatusType.FAILED); + statusTableTemplate.setData("status", FAILED); statusTableTemplate.setData("description", cause.getClass() + ": " + cause.getMessage()); statusTableTemplate.setData("exception", cause); statusTableTemplate.setData("id", ++nodeId * 1000); @@ -1038,7 +1042,7 @@ public void createTable(ReportTable table) { updateReport(); break; case TESTCASE: - if(tableName.equals("Messages")) { + if("Messages".equals(tableName)) { createNode(testCaseWriter, "Table: All messages", NodeType.INFO, null, MessageLevel.INFO, 5); try { @@ -1222,68 +1226,68 @@ private void createNode(Writer writer, String nodeTitle, String nodeDescription, } private String getNodeClass(NodeType nodeType, StatusType statusType, MessageLevel messageLevel) { - String nodeClass = ""; - - if (nodeType == NodeType.TESTCASE && statusType == StatusType.PASSED) - nodeClass = "testcase_passed"; - else if (nodeType == NodeType.TESTCASE && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "testcase_conditionally_passed"; - else if (nodeType == NodeType.TESTCASE && statusType == StatusType.FAILED) - nodeClass = "testcase_failed"; - else if (nodeType == NodeType.TESTCASE && statusType == StatusType.SKIPPED) - nodeClass = "testcase_skipped"; - else if (nodeType == NodeType.DESCRIPTION) - nodeClass = "description"; - else if (nodeType == NodeType.ACTION && statusType == StatusType.PASSED) - nodeClass = "action_passed"; - else if (nodeType == NodeType.ACTION && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "action_conditionally_passed"; - else if (nodeType == NodeType.ACTION && statusType == StatusType.FAILED) - nodeClass = "action_failed"; - else if (nodeType == NodeType.ACTION && statusType == StatusType.SKIPPED) - nodeClass = "action_skipped"; - else if (nodeType == NodeType.INPUT) - nodeClass = "inputparams"; - else if (nodeType == NodeType.INFO) - nodeClass = "info_" + messageLevel.toString().toLowerCase(); - else if (nodeType == NodeType.STATUS && statusType == StatusType.PASSED) - nodeClass = "statustype_passed"; - else if (nodeType == NodeType.STATUS && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "statustype_conditionally_passed"; - else if (nodeType == NodeType.STATUS && statusType == StatusType.CONDITIONALLY_FAILED) - nodeClass = "statustype_conditionally_failed"; - else if (nodeType == NodeType.STATUS && statusType == StatusType.FAILED) - nodeClass = "statustype_failed"; - else if (nodeType == NodeType.EXCEPTION && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "conditionally_exceptiontype"; - else if (nodeType == NodeType.EXCEPTION) - nodeClass = "exceptiontype"; - else if (nodeType == NodeType.ALERTS) - nodeClass = "alerttype"; - else if (nodeType == NodeType.VERIFICATION && statusType == StatusType.PASSED) - nodeClass = "verification_passed"; - else if (nodeType == NodeType.VERIFICATION && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "verification_conditionally_passed"; - else if (nodeType == NodeType.VERIFICATION && statusType == StatusType.FAILED) - nodeClass = "verification_failed"; - else if (nodeType == NodeType.VERIFICATION && statusType == StatusType.SKIPPED) - nodeClass = "verification_skipped"; - else if (nodeType == NodeType.COMPARISON && statusType == StatusType.PASSED) - nodeClass = "comparisontype_passed"; - else if (nodeType == NodeType.COMPARISON && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "comparisontype_conditionally_passed"; - else if (nodeType == NodeType.COMPARISON && statusType != StatusType.PASSED) - nodeClass = "comparisontype_notpassed"; - else if (nodeType == NodeType.MATRIX && statusType == StatusType.PASSED) - nodeClass = "matrix_passed"; - else if (nodeType == NodeType.MATRIX && statusType == StatusType.CONDITIONALLY_PASSED) - nodeClass = "matrix_conditionally_passed"; - else if (nodeType == NodeType.MATRIX && statusType == StatusType.FAILED) - nodeClass = "matrix_failed"; - else if (nodeType == NodeType.MATRIX && statusType == StatusType.SKIPPED) - nodeClass = "matrix_skipped"; - - return nodeClass; + + if(nodeType == NodeType.TESTCASE && statusType == PASSED) { + return "testcase_passed"; + } else if(nodeType == NodeType.TESTCASE && statusType == CONDITIONALLY_PASSED) { + return "testcase_conditionally_passed"; + } else if(nodeType == NodeType.TESTCASE && statusType == FAILED) { + return "testcase_failed"; + } else if(nodeType == NodeType.TESTCASE && statusType == SKIPPED) { + return "testcase_skipped"; + } else if(nodeType == NodeType.DESCRIPTION) { + return "description"; + } else if(nodeType == NodeType.ACTION && statusType == PASSED) { + return "action_passed"; + } else if(nodeType == NodeType.ACTION && statusType == CONDITIONALLY_PASSED) { + return "action_conditionally_passed"; + } else if(nodeType == NodeType.ACTION && statusType == FAILED) { + return "action_failed"; + } else if(nodeType == NodeType.ACTION && statusType == SKIPPED) { + return "action_skipped"; + } else if(nodeType == NodeType.INPUT) { + return "inputparams"; + } else if(nodeType == NodeType.INFO) { + return "info_" + messageLevel.toString().toLowerCase(); + } else if(nodeType == NodeType.STATUS && statusType == PASSED) { + return "statustype_passed"; + } else if(nodeType == NodeType.STATUS && statusType == CONDITIONALLY_PASSED) { + return "statustype_conditionally_passed"; + } else if(nodeType == NodeType.STATUS && statusType == CONDITIONALLY_FAILED) { + return "statustype_conditionally_failed"; + } else if(nodeType == NodeType.STATUS && statusType == FAILED) { + return "statustype_failed"; + } else if(nodeType == NodeType.EXCEPTION && statusType == CONDITIONALLY_PASSED) { + return "conditionally_exceptiontype"; + } else if(nodeType == NodeType.EXCEPTION) { + return "exceptiontype"; + } else if(nodeType == NodeType.ALERTS) { + return "alerttype"; + } else if(nodeType == NodeType.VERIFICATION && statusType == PASSED) { + return "verification_passed"; + } else if(nodeType == NodeType.VERIFICATION && statusType == CONDITIONALLY_PASSED) { + return "verification_conditionally_passed"; + } else if(nodeType == NodeType.VERIFICATION && statusType == FAILED) { + return "verification_failed"; + } else if(nodeType == NodeType.VERIFICATION && statusType == SKIPPED) { + return "verification_skipped"; + } else if(nodeType == NodeType.COMPARISON && statusType == PASSED) { + return "comparisontype_passed"; + } else if(nodeType == NodeType.COMPARISON && statusType == CONDITIONALLY_PASSED) { + return "comparisontype_conditionally_passed"; + } else if(nodeType == NodeType.COMPARISON && statusType != PASSED) { + return "comparisontype_notpassed"; + } else if(nodeType == NodeType.MATRIX && statusType == PASSED) { + return "matrix_passed"; + } else if(nodeType == NodeType.MATRIX && statusType == CONDITIONALLY_PASSED) { + return "matrix_conditionally_passed"; + } else if(nodeType == NodeType.MATRIX && statusType == FAILED) { + return "matrix_failed"; + } else if(nodeType == NodeType.MATRIX && statusType == SKIPPED) { + return "matrix_skipped"; + } + + return ""; } private String getStatusClass(StatusType status) { @@ -1395,12 +1399,7 @@ private IMessageStructure getMessageStructure(MsgMetaData metaData) { } IDictionaryStructure dictionaryStructure = dictionaryManager.getDictionary(dictionaryURI); - - if(dictionaryStructure == null) { - return null; - } - - return dictionaryStructure.getMessages().get(metaData.getMsgName()); + return dictionaryStructure == null ? null : dictionaryStructure.getMessages().get(metaData.getMsgName()); } private List convert(ComparisonResult result, String parentRaw, int counter, int nestingLevel) { @@ -1654,7 +1653,7 @@ private enum NodeType { } private interface IReportEntryContainer { - public void write(Writer writer); + void write(Writer writer); } private class ReportTestcaseContainer implements IReportEntryContainer { @@ -1669,21 +1668,21 @@ public ReportTestcaseContainer(TestCase testcase) { public void write(Writer writer) { Long duration = null; StatusType status = null; - if (this.testcase.getStatus() != null && this.testcase.getFinishTime() != null) { - status = this.testcase.getStatus().getStatus(); - duration = this.testcase.getFinishTime().getTime() - this.testcase.getStartTime().getTime(); + if(testcase.getStatus() != null && testcase.getFinishTime() != null) { + status = testcase.getStatus().getStatus(); + duration = testcase.getFinishTime().getTime() - testcase.getStartTime().getTime(); } TemplateWrapper reportTestCaseLinkTemplate; try { reportTestCaseLinkTemplate = templateWrapperFactory.createWrapper("report_test_case_link.ftlh"); - reportTestCaseLinkTemplate.setData("name", this.testcase.getName()); - reportTestCaseLinkTemplate.setData("fileName", this.testcase.getName().replaceAll("\\W", "_")); - reportTestCaseLinkTemplate.setData("description", this.testcase.getDescription()); + reportTestCaseLinkTemplate.setData("name", testcase.getName()); + reportTestCaseLinkTemplate.setData("fileName", testcase.getName().replaceAll("\\W", "_")); + reportTestCaseLinkTemplate.setData("description", testcase.getDescription()); reportTestCaseLinkTemplate.setData("status", status); reportTestCaseLinkTemplate.setData("duration", duration); - reportTestCaseLinkTemplate.setData("tags", this.testcase.getTags()); + reportTestCaseLinkTemplate.setData("tags", testcase.getTags()); reportTestCaseLinkTemplate.write(writer, 5); } catch (TemplateException | IOException e) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Action.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Action.java index 062dac06..7c63ab74 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Action.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Action.java @@ -15,11 +15,12 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.impl.htmlreport.data; -import com.exactpro.sf.aml.script.CheckPoint; +import java.util.List; + import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import java.util.List; +import com.exactpro.sf.aml.script.CheckPoint; public class Action extends BaseEntity { private static final int NEXT_AFTER_ROOT = 1; @@ -33,10 +34,6 @@ public class Action extends BaseEntity { private CheckPoint checkPoint; private List verificationsOrder; - public Action() { - super(); - } - public int getId() { return id; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionGroup.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionGroup.java index 9cb087b2..c63e9a47 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionGroup.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionGroup.java @@ -23,11 +23,11 @@ public class ActionGroup extends BaseEntity { public ActionGroup copyWithStatus(StatusType status) { ActionGroup copy = new ActionGroup(); - copy.setName(this.getName()); - copy.setDescription(this.getDescription()); + copy.setName(getName()); + copy.setDescription(getDescription()); copy.setStatus(status); - copy.setLinkToReport(this.linkToReport); - for (Object element : this.getElements()) { + copy.setLinkToReport(linkToReport); + for(Object element : getElements()) { copy.addElement(element); } return copy; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionParameter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionParameter.java index 13e4fa64..fcad0d17 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionParameter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/ActionParameter.java @@ -19,7 +19,7 @@ import org.apache.commons.lang3.builder.ToStringStyle; public class ActionParameter { - private String id; + private final String id; private final String name; private final String value; private final int level; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/BaseEntity.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/BaseEntity.java index 74564227..ea2233f6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/BaseEntity.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/BaseEntity.java @@ -29,9 +29,9 @@ public abstract class BaseEntity { private String name; private String description; - private List elements; - private Set allKnownBugs; - private Set reproducedBugs; + private final List elements; + private final Set allKnownBugs; + private final Set reproducedBugs; public BaseEntity() { elements = new ArrayList<>(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/MachineLearningData.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/MachineLearningData.java index 15820080..d9e80f59 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/MachineLearningData.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/MachineLearningData.java @@ -27,6 +27,7 @@ import com.exactpro.sf.comparison.ComparisonResult; import com.exactpro.sf.comparison.ComparisonUtil; +@Deprecated // Used only in old HTML report public class MachineLearningData { private final String name; private final String namespace; @@ -34,7 +35,6 @@ public class MachineLearningData { private final String protocol; private final long periodStart; private long periodEnd; - private boolean problemExplanation = false; private final Map expected; private final List actuals = new ArrayList<>(); @@ -88,10 +88,6 @@ public Map getExpected() { return expected; } - public boolean isProblemExplanation() { - return problemExplanation; - } - public void addActual(ComparisonResult actual) { Objects.requireNonNull(actual, "actual cannot be null"); MsgMetaData metaData = Objects.requireNonNull(actual.getMetaData(), "metaData cannot be null"); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Message.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Message.java index 5db8835f..51a72e52 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Message.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Message.java @@ -28,7 +28,7 @@ public class Message { private MessageLevel level; private String title; private String message; - private List submessages; + private final List submessages; private Throwable cause; public Message() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Report.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Report.java index d33a0b2b..629ecc0a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Report.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Report.java @@ -31,12 +31,8 @@ public class Report extends BaseEntity { private String user; private long id; private Date date; - private SetMultimap allKnownBugs = LinkedHashMultimap.create(); - private SetMultimap reproducedBugs = LinkedHashMultimap.create(); - - public Report() { - super(); - } + private final SetMultimap allKnownBugs = LinkedHashMultimap.create(); + private final SetMultimap reproducedBugs = LinkedHashMultimap.create(); public String getHost() { return host; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/TestCase.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/TestCase.java index 3e97f932..1a528284 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/TestCase.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/TestCase.java @@ -15,11 +15,6 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.impl.htmlreport.data; -import com.exactpro.sf.common.util.Utils; -import com.exactpro.sf.scriptrunner.StatusDescription; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - import java.util.Collections; import java.util.Date; import java.util.Map; @@ -27,6 +22,12 @@ import java.util.function.Function; import java.util.stream.Collectors; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.exactpro.sf.common.util.Utils; +import com.exactpro.sf.scriptrunner.StatusDescription; + public class TestCase extends BaseEntity { private String id; private int order; @@ -36,10 +37,6 @@ public class TestCase extends BaseEntity { private StatusDescription status; private Map tags = Collections.emptyMap(); //maps tag name to css class - public TestCase() { - super(); - } - public String getId() { return id; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Verification.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Verification.java index 0ca2833b..52236b9a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Verification.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/Verification.java @@ -15,16 +15,17 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.impl.htmlreport.data; -import com.exactpro.sf.scriptrunner.StatusDescription; -import com.exactpro.sf.scriptrunner.impl.htmlreport.HtmlReport.ContextType; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; +import java.util.List; + import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; +import com.exactpro.sf.scriptrunner.StatusDescription; +import com.exactpro.sf.scriptrunner.impl.htmlreport.HtmlReport.ContextType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; public class Verification extends BaseEntity { private static final Logger logger = LoggerFactory.getLogger(Verification.class); @@ -44,10 +45,6 @@ public class Verification extends BaseEntity { mapper.registerModule(module); } - public Verification() { - super(); - } - public int getId() { return id; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/VerificationSerializer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/VerificationSerializer.java index 7e36582d..30de7d28 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/VerificationSerializer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/htmlreport/data/VerificationSerializer.java @@ -16,14 +16,14 @@ package com.exactpro.sf.scriptrunner.impl.htmlreport.data; +import java.io.IOException; +import java.util.List; + import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import java.io.IOException; -import java.util.List; - public class VerificationSerializer extends StdSerializer { public VerificationSerializer(Class clazz) { @@ -45,13 +45,7 @@ public void serialize(Verification value, JsonGenerator gen, SerializerProvider int newLvl = parameter.getLevel(); - int nextLvl; - - if (i < lastIndex) { - nextLvl = parameters.get(i + 1).getLevel(); - } else { - nextLvl = newLvl; - } + int nextLvl = i < lastIndex ? parameters.get(i + 1).getLevel() : newLvl; if (newLvl > level) { gen.writeStartObject(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/IJsonReportNode.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/IJsonReportNode.java index 5d6bcc02..1e5a2bd4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/IJsonReportNode.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/IJsonReportNode.java @@ -28,13 +28,15 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.As; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import java.util.Arrays; import java.util.Collection; @JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, + use = Id.NAME, + include = As.PROPERTY, property = "actionNodeType") @JsonSubTypes({ @Type(value = Action.class, name = "action"), diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/JsonReport.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/JsonReport.java index 11cc243a..fc356587 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/JsonReport.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/JsonReport.java @@ -15,6 +15,28 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.impl.jsonreport; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.ArrayUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.SerializeUtil; import com.exactpro.sf.aml.AMLBlockType; import com.exactpro.sf.aml.generator.AggregateAlert; @@ -25,33 +47,49 @@ import com.exactpro.sf.configuration.workspace.FolderType; import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; import com.exactpro.sf.configuration.workspace.WorkspaceStructureException; -import com.exactpro.sf.scriptrunner.*; +import com.exactpro.sf.scriptrunner.IReportStats; +import com.exactpro.sf.scriptrunner.IScriptProgress; +import com.exactpro.sf.scriptrunner.IScriptReport; +import com.exactpro.sf.scriptrunner.LoggerRow; +import com.exactpro.sf.scriptrunner.MessageLevel; +import com.exactpro.sf.scriptrunner.OutcomeCollector; +import com.exactpro.sf.scriptrunner.ReportEntity; +import com.exactpro.sf.scriptrunner.ReportUtils; +import com.exactpro.sf.scriptrunner.ScriptContext; +import com.exactpro.sf.scriptrunner.ScriptRunException; +import com.exactpro.sf.scriptrunner.StatusDescription; +import com.exactpro.sf.scriptrunner.TestScriptDescription; import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptState; import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptStatus; import com.exactpro.sf.scriptrunner.impl.ReportStats; import com.exactpro.sf.scriptrunner.impl.ReportTable; -import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.*; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Action; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Alert; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Bug; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ContextType; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.CustomLink; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.CustomMessage; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.CustomTable; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.LogEntry; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Message; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.OutcomeSummary; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Parameter; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportException; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportProperties; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportRoot; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Status; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.TestCase; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.TestCaseMetadata; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.Verification; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.VerificationEntry; import com.exactpro.sf.scriptrunner.reportbuilder.textformatter.TextColor; import com.exactpro.sf.scriptrunner.reportbuilder.textformatter.TextStyle; import com.exactpro.sf.util.BugDescription; -import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.google.common.collect.Sets; -import org.apache.commons.lang3.ArrayUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; @SuppressWarnings("MismatchedQueryAndUpdateOfCollection, unused, FieldCanBeLocal") public class JsonReport implements IScriptReport { @@ -59,15 +97,15 @@ public class JsonReport implements IScriptReport { private static final ObjectMapper mapper; private static final String REPORT_ROOT_FILE_NAME = "report"; - private static long actionIdCounter = 0; + private static long actionIdCounter; private ScriptContext scriptContext; private Context context; private IReportStats reportStats; private boolean isActionCreated; - private Map> messageToActionIdMap; - private IWorkspaceDispatcher dispatcher; - private String reportRootDirectoryPath; + private final Map> messageToActionIdMap; + private final IWorkspaceDispatcher dispatcher; + private final String reportRootDirectoryPath; private final TestScriptDescription testScriptDescription; //Main bean of report @@ -75,9 +113,9 @@ public class JsonReport implements IScriptReport { static { mapper = new ObjectMapper(); - mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY) - .withCreatorVisibility(JsonAutoDetect.Visibility.NONE).withSetterVisibility(JsonAutoDetect.Visibility.NONE) - .withGetterVisibility(JsonAutoDetect.Visibility.NONE).withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); + mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(Visibility.ANY) + .withCreatorVisibility(Visibility.NONE).withSetterVisibility(Visibility.NONE) + .withGetterVisibility(Visibility.NONE).withIsGetterVisibility(Visibility.NONE)); mapper.registerModule(new JavaTimeModule()); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS")); } @@ -95,19 +133,19 @@ public JsonReport(String reportRootDirectoryPath, IWorkspaceDispatcher dispatche } private void assertState(ContextType... states) { - if (Arrays.stream(states).noneMatch(i -> this.context.cur.equals(i))) { - throw new RuntimeException(String.format("Incorrect report state '%s' ('%s' expected)", this.context.cur, Arrays.toString(states))); + if(Arrays.stream(states).noneMatch(i -> context.cur == i)) { + throw new RuntimeException(String.format("Incorrect report state '%s' ('%s' expected)", context.cur, Arrays.toString(states))); } } private File getFile(String fileName, String extension) { fileName = fileName.replaceAll("\\W", "_"); if (!fileName.endsWith(extension)) { - fileName = fileName.concat(extension); + fileName = fileName + extension; } try { - return this.dispatcher.createFile(FolderType.REPORT, true, reportRootDirectoryPath, "reportData", fileName); + return dispatcher.createFile(FolderType.REPORT, true, reportRootDirectoryPath, "reportData", fileName); } catch (WorkspaceStructureException e) { throw new ScriptRunException("unable to create report file", e); } @@ -129,7 +167,7 @@ private void exportToFile(Object data, String fileName) { } if (data instanceof TestCase) { - this.reportRoot.getMetadata().add(new TestCaseMetadata(((TestCase) data), jsonpFile, jsonFile)); + reportRoot.getMetadata().add(new TestCaseMetadata((TestCase)data, jsonpFile, jsonFile)); } } @@ -157,7 +195,7 @@ private void initProperties() { cause = SerializeUtil.serializeToBase64(testScriptDescription.getCause()); } - this.reportRoot.setReportProperties( + reportRoot.setReportProperties( new ReportProperties(state, status, matrixFile, timestamp, environmentNameAttr, languageURI, workFolder, passed, conditionallyPassed, failed, total, services, range, autostart, cause)); } @@ -172,31 +210,31 @@ private void revertContext() { @SuppressWarnings("unchecked") private T getCurrentContextNode() { - return (T) this.context.node; + return (T)context.node; } public void createReport(ScriptContext scriptContext, String name, String description, long scriptRunId, String environmentName, String userName) { this.scriptContext = scriptContext; - this.reportRoot.setStartTime(Instant.now()); + reportRoot.setStartTime(Instant.now()); try { - this.reportRoot.setHostName(InetAddress.getLocalHost().getHostName()); + reportRoot.setHostName(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { - this.reportRoot.setHostName("n/a"); + reportRoot.setHostName("n/a"); } - this.reportRoot.setName(name); - this.reportRoot.setUserName(userName); - this.reportRoot.setScriptRunId(scriptRunId); - this.reportRoot.setVersion(SFLocalContext.getDefault().getVersion()); - this.reportRoot.setBranchName(SFLocalContext.getDefault().getBranchName()); + reportRoot.setName(name); + reportRoot.setUserName(userName); + reportRoot.setScriptRunId(scriptRunId); + reportRoot.setVersion(SFLocalContext.getDefault().getVersion()); + reportRoot.setBranchName(SFLocalContext.getDefault().getBranchName()); - this.reportRoot.setPlugins(SFLocalContext.getDefault().getPluginVersions().stream().filter(i -> !i.isGeneral()) + reportRoot.setPlugins(SFLocalContext.getDefault().getPluginVersions().stream().filter(i -> !i.isGeneral()) .collect(Collectors.toMap(IVersion::getAlias, IVersion::buildVersion))); - this.reportRoot.setDescription(description); + reportRoot.setDescription(description); setContext(ContextType.SCRIPT, null); } @@ -235,13 +273,13 @@ public void closeTestCase(StatusDescription status) { TestCase curTestCase = getCurrentContextNode(); curTestCase.setStatus(new Status(status)); curTestCase.setFinishTime(Instant.now()); - this.reportRoot.getBugs().addAll(curTestCase.getBugs()); + reportRoot.getBugs().addAll(curTestCase.getBugs()); exportToFile(curTestCase, curTestCase.getName()); exportToFile(reportRoot, REPORT_ROOT_FILE_NAME); revertContext(); - this.reportStats.updateTestCaseStatus(status.getStatus()); + reportStats.updateTestCaseStatus(status.getStatus()); } public void createAction(String name, String serviceName, String action, String msg, String description, Object inputParameters, @@ -279,7 +317,7 @@ public void closeAction(StatusDescription status, Object actionResult) { curAction.setFinishTime(Instant.now()); if (status.isUpdateTestCaseStatus()) { - this.reportStats.updateActions(status.getStatus()); + reportStats.updateActions(status.getStatus()); } isActionCreated = false; @@ -296,7 +334,7 @@ public void closeAction(StatusDescription status, Object actionResult) { for (Long id : curAction.getRelatedMessages()) { //noinspection ConstantConditions - this.messageToActionIdMap.computeIfAbsent(id, k -> new HashSet<>()).add(curAction.getId()); + messageToActionIdMap.computeIfAbsent(id, k -> new HashSet<>()).add(curAction.getId()); } } @@ -385,8 +423,8 @@ public void createException(Throwable cause) { if (getCurrentContextNode() != null) { getCurrentContextNode().addException(cause); } else { - if (this.reportRoot.getException() == null) { - this.reportRoot.setException(new ReportException(cause)); + if(reportRoot.getException() == null) { + reportRoot.setException(new ReportException(cause)); } } } @@ -397,20 +435,20 @@ public void createTable(ReportTable table) { IJsonReportNode currentNode = getCurrentContextNode(); - if (table.getName().equals("Messages")) { + if("Messages".equals(table.getName())) { List messages = table.getRows().stream().map(Message::new).collect(Collectors.toList()); if (currentNode instanceof Action) { long actionId = ((Action) currentNode).getId(); for (Message message : messages) { - this.messageToActionIdMap.computeIfAbsent(message.getId(), k -> new HashSet<>()).add(actionId); + messageToActionIdMap.computeIfAbsent(message.getId(), k -> new HashSet<>()).add(actionId); } } if (currentNode instanceof TestCase) { for (Message message : messages) { - message.setRelatedActions(this.messageToActionIdMap.computeIfAbsent(message.getId(), k -> new HashSet<>())); + message.setRelatedActions(messageToActionIdMap.computeIfAbsent(message.getId(), k -> new HashSet<>())); } } currentNode.addSubNodes(messages); @@ -445,7 +483,7 @@ public IReportStats getReportStats() { public void closeReport() { assertState(null, ContextType.SCRIPT); - this.reportRoot.setFinishTime(Instant.now()); + reportRoot.setFinishTime(Instant.now()); initProperties(); exportToFile(reportRoot, REPORT_ROOT_FILE_NAME); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/Action.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/Action.java index c08798d4..2e37625b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/Action.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/Action.java @@ -16,8 +16,6 @@ package com.exactpro.sf.scriptrunner.impl.jsonreport.beans; -import com.exactpro.sf.scriptrunner.impl.jsonreport.IJsonReportNode; - import java.time.Instant; import java.util.ArrayList; import java.util.Collection; @@ -25,6 +23,8 @@ import java.util.List; import java.util.Set; +import com.exactpro.sf.scriptrunner.impl.jsonreport.IJsonReportNode; + public class Action implements IJsonReportNode { private long id; @@ -51,26 +51,26 @@ public Action() { @Override public void addSubNodes(Collection nodes) { for (IJsonReportNode child : nodes) { if (child instanceof Message) { - this.relatedMessages.add(((Message) child).getId()); + relatedMessages.add(((Message)child).getId()); } else if (child instanceof Action || child instanceof CustomMessage || child instanceof CustomTable || child instanceof CustomLink) { - this.subNodes.add(child); + subNodes.add(child); } else if (child instanceof Bug) { - this.bugs.add((Bug) child); + bugs.add((Bug)child); } else if (child instanceof Verification) { - this.subNodes.add(child); + subNodes.add(child); if (((Verification) child).getMessageId() != null) { - this.relatedMessages.add(((Verification) child).getMessageId()); + relatedMessages.add(((Verification)child).getMessageId()); } } else if (child instanceof LogEntry) { - this.logs.add((LogEntry) child); + logs.add((LogEntry)child); } else { - throw new IllegalArgumentException("unsupported child node type: " + child.getClass().toString()); + throw new IllegalArgumentException("unsupported child node type: " + child.getClass()); } } } @Override public void addException(Throwable t) { - if (this.status == null) { + if(status == null) { this.status = new Status(t); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/ReportRoot.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/ReportRoot.java index 2a30ea6c..92a4d680 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/ReportRoot.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/ReportRoot.java @@ -163,6 +163,4 @@ public void setReportProperties(ReportProperties reportProperties) { this.reportProperties = reportProperties; } - public ReportRoot() { - } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/TestCase.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/TestCase.java index aa1b81a6..24250512 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/TestCase.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/impl/jsonreport/beans/TestCase.java @@ -16,8 +16,6 @@ package com.exactpro.sf.scriptrunner.impl.jsonreport.beans; -import com.exactpro.sf.scriptrunner.impl.jsonreport.IJsonReportNode; - import java.time.Instant; import java.util.ArrayList; import java.util.Collection; @@ -25,6 +23,8 @@ import java.util.List; import java.util.Set; +import com.exactpro.sf.scriptrunner.impl.jsonreport.IJsonReportNode; + public class TestCase implements IJsonReportNode { private final List actions; private final List logs; @@ -58,23 +58,23 @@ public TestCase() { @Override public void addSubNodes(Collection nodes) { for (IJsonReportNode child : nodes) { if (child instanceof Action || child instanceof CustomMessage) { - this.actions.add(child); + actions.add(child); } else if (child instanceof Message) { - this.messages.add((Message) child); + messages.add((Message)child); } else if (child instanceof Bug) { - this.bugs.add((Bug) child); + bugs.add((Bug)child); } else if (child instanceof LogEntry) { - this.logs.add((LogEntry) child); + logs.add((LogEntry)child); } else if (child instanceof Verification) { - this.verifications.add((Verification) child); + verifications.add((Verification)child); } else { - throw new IllegalArgumentException("unsupported child node type: " + child.getClass().toString()); + throw new IllegalArgumentException("unsupported child node type: " + child.getClass()); } } } @Override public void addException(Throwable t) { - if (this.status == null) { + if(status == null) { this.status = new Status(t); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/junit40/SFJUnitRunner.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/junit40/SFJUnitRunner.java index b0fab660..a6efa3f0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/junit40/SFJUnitRunner.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/junit40/SFJUnitRunner.java @@ -15,6 +15,19 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.junit40; +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.aml.AMLBlockType; import com.exactpro.sf.aml.AddToReport; import com.exactpro.sf.aml.AfterMatrix; @@ -37,22 +50,10 @@ import com.exactpro.sf.scriptrunner.StatusType; import com.exactpro.sf.storage.ScriptRun; import com.google.common.collect.ImmutableSet; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Set; public class SFJUnitRunner { - private static Logger logger = LoggerFactory.getLogger(SFJUnitRunner.class); + private static final Logger logger = LoggerFactory.getLogger(SFJUnitRunner.class); public void run(Class testcaseClass, ScriptContext context) throws ScriptRunException { @@ -381,10 +382,11 @@ private static class TestExecutionComparator implements Comparator o2.getSeqnum() ) - return 1; + if(o1.getSeqnum() < o2.getSeqnum()) { + return -1; + } else if(o1.getSeqnum() > o2.getSeqnum()) { + return 1; + } return 0; } } @@ -405,8 +407,9 @@ private void executeBeforeScript(ScriptContext scriptContext) scriptContext.setScriptRun(scriptRun); // Init Report - if (description == null || description.equals("")) - description = IScriptReport.NO_DESCRIPTION; + if(description == null || "".equals(description)) { + description = IScriptReport.NO_DESCRIPTION; + } IScriptReport report = scriptContext.getReport(); report.createReport(scriptContext, scriptName, description, scriptRun.getId().longValue(), scriptContext.getEnvironmentName(), scriptContext.getUserName()); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/AutoLanguageFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/AutoLanguageFactory.java index f6134f2f..75578757 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/AutoLanguageFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/AutoLanguageFactory.java @@ -67,6 +67,6 @@ public boolean isCompatible(Method method) { @Override public ClassLoader createClassLoader(URL binFolder, ClassLoader parent) { - return new URLClassLoader(new URL[] { binFolder }, this.getClass().getClassLoader()); + return new URLClassLoader(new URL[] { binFolder }, getClass().getClassLoader()); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/ICompatibilityChecker.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/ICompatibilityChecker.java index 325b1ea2..c3350345 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/ICompatibilityChecker.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/ICompatibilityChecker.java @@ -18,5 +18,5 @@ import java.lang.reflect.Method; public interface ICompatibilityChecker { - public boolean isCompatible(Method method); + boolean isCompatible(Method method); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java index 2bf7c1fb..0995ee69 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/languagemanager/LanguageManager.java @@ -37,8 +37,6 @@ public class LanguageManager implements ILoadableManager { @SuppressWarnings("serial") private final Map uriToFactory = new TreeMap() {{ put(AutoLanguageFactory.URI, AUTO); }}; - public LanguageManager() {} - @Override public void load(ILoadableManagerContext context) { ClassLoader classLoader = context.getClassLoaders()[0]; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextColor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextColor.java index 4eaf6065..45af0d46 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextColor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextColor.java @@ -23,9 +23,9 @@ public enum TextColor { ORANGE("conditionally_passed"), GREY("na"); - private String cssClass; + private final String cssClass; - private TextColor(String cssClass) { + TextColor(String cssClass) { this.cssClass = cssClass; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextStyle.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextStyle.java index c206b5be..3d02fb29 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextStyle.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/reportbuilder/textformatter/TextStyle.java @@ -18,9 +18,9 @@ public enum TextStyle { BOLD("font-weight: bold;"), NORMAL("font-weight: normal; font-style: normal;"), ITALIC("font-style: italic;"); - private String cssRule; + private final String cssRule; - private TextStyle(String cssRule) { + TextStyle(String cssRule) { this.cssRule = cssRule; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/IUtilityCaller.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/IUtilityCaller.java index 691158a4..d8c3147f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/IUtilityCaller.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/IUtilityCaller.java @@ -19,5 +19,5 @@ import com.exactpro.sf.scriptrunner.utilitymanager.exceptions.UtilityNotFoundException; public interface IUtilityCaller { - public T call(String utilityName, Object... args) throws UtilityCallException, UtilityNotFoundException, InterruptedException; + T call(String utilityName, Object... args) throws UtilityCallException, UtilityNotFoundException, InterruptedException; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityInfo.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityInfo.java index 648acb53..290e64c5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityInfo.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityInfo.java @@ -17,22 +17,17 @@ import java.util.Arrays; -import com.exactpro.sf.scriptrunner.AbstractInfo; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import com.exactpro.sf.configuration.suri.SailfishURI; +import com.exactpro.sf.scriptrunner.AbstractInfo; public class UtilityInfo extends AbstractInfo implements Cloneable { private String[] parameterNames; private Class[] parameterTypes; - public UtilityInfo() { - // TODO Auto-generated constructor stub - } - public String[] getParameterNames() { return Arrays.copyOf(parameterNames, parameterNames.length); } @@ -53,11 +48,11 @@ protected void setParameterTypes(Class[] parameterTypes) { public UtilityInfo clone() { UtilityInfo that = new UtilityInfo(); - that.setURI(this.uri); + that.setURI(uri); that.setParameterNames(getParameterNames()); that.setParameterTypes(getParameterTypes()); - that.setReturnType(this.returnType); - that.setDescription(this.description); + that.setReturnType(returnType); + that.setDescription(description); return that; } @@ -75,11 +70,11 @@ public boolean equals(Object o) { UtilityInfo that = (UtilityInfo)o; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.uri, that.uri); - builder.append(this.parameterNames, that.parameterNames); - builder.append(this.parameterTypes, that.parameterTypes); - builder.append(this.returnType, that.returnType); - builder.append(this.description, that.description); + builder.append(uri, that.uri); + builder.append(parameterNames, that.parameterNames); + builder.append(parameterTypes, that.parameterTypes); + builder.append(returnType, that.returnType); + builder.append(description, that.description); return builder.isEquals(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManager.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManager.java index 16c6d1f9..c4e7d60a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManager.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManager.java @@ -18,7 +18,6 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -46,11 +45,9 @@ public class UtilityManager implements IUtilityManager { @Override protected Map, IUtilityCaller> initialValue() { return new HashMap<>(); - }; + } }; - public UtilityManager() {} - /** * Loads utilities from specified class * diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManagerUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManagerUtils.java index af13caf9..8cc15544 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManagerUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/utilitymanager/UtilityManagerUtils.java @@ -15,23 +15,25 @@ ******************************************************************************/ package com.exactpro.sf.scriptrunner.utilitymanager; +import static org.apache.commons.lang3.ClassUtils.isAssignable; + import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Arrays; -import com.exactpro.sf.aml.Description; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.ObjectUtils; +import com.exactpro.sf.aml.Description; import com.exactpro.sf.configuration.suri.SailfishURI; public class UtilityManagerUtils { - private static final Object[] NULL_ARGUMENT_ARRAY = new Object[] { null }; + private static final Object[] NULL_ARGUMENT_ARRAY = { null }; public static boolean checkArgs(Object[] args, Class... argTypes) { - return ClassUtils.isAssignable(ClassUtils.toClass(args), argTypes, true); + return isAssignable(ClassUtils.toClass(args), argTypes, true); } @SuppressWarnings("unchecked") @@ -70,11 +72,7 @@ public static Class[] getVarArgsClasses(Object[] args, Class... argTypes) Class[] classes = new Class[argsLength]; for(int i = 0; i < args.length; i++) { - if(i < typesLength) { - classes[i] = argTypes[i]; - } else { - classes[i] = argTypes[typesLength - 1]; - } + classes[i] = argTypes[Math.min(i, typesLength - 1)]; } return classes; @@ -97,12 +95,7 @@ public static T[] getVarArgsArray(Object[] args, int startIndex, Class varArgsClass = signatureClasses[lastIndex].getComponentType(); - if(ClassUtils.isAssignable(argumentsClasses[lastIndex], varArgsClass)) { + if(isAssignable(argumentsClasses[lastIndex], varArgsClass)) { signatureClasses[lastIndex] = varArgsClass; } } @@ -192,7 +185,7 @@ public static int getCompatibilityIndex(Method method, Object... args) { continue; } - if(!ClassUtils.isAssignable(argumentClass, signatureClass)) { + if(!isAssignable(argumentClass, signatureClass)) { return -1; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/AbstractServiceSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/AbstractServiceSettings.java index bbbe2d19..5a2ae7a8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/AbstractServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/AbstractServiceSettings.java @@ -37,10 +37,10 @@ public abstract class AbstractServiceSettings implements IServiceSettings, Seria protected long expectedTimeOfStarting = 2000; @Description("Waiting time before starting") - protected long waitingTimeBeforeStarting = 0; + protected long waitingTimeBeforeStarting; @Description("User comment") - protected String comment = null; + protected String comment; @Description("Network traffic will be recorded for this service's lifetime and for each test script run using it") private boolean performDump; @@ -67,7 +67,7 @@ public void setExpectedTimeOfStarting(long expectedTimeOfStarting) { @Override public String getComment() { - return this.comment; + return comment; } public void setComment(String comment) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHArrayList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHArrayList.java index 69cf7fb3..e3aae48f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHArrayList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHArrayList.java @@ -40,7 +40,7 @@ public CSHArrayList() { } public void addCheckPoint(CheckPoint checkPoint) { - putCheckPoint(checkPoint, super.size()); + putCheckPoint(checkPoint, size()); } protected void putCheckPoint(CheckPoint checkPoint, int index) { @@ -53,13 +53,8 @@ public int getIndex(CheckPoint checkPoint) { } public List subList(int fromIndex) { - int size = super.size(); - - if(fromIndex < size) { - return new ArrayList<>(super.subList(fromIndex, size)); - } - - return new ArrayList<>(); + int size = size(); + return fromIndex < size ? new ArrayList<>(subList(fromIndex, size)) : new ArrayList<>(); } public long getID() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHIterator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHIterator.java index 4806b465..2eb9bd43 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHIterator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CSHIterator.java @@ -24,9 +24,9 @@ public class CSHIterator implements ICSHIterator { private final CSHArrayList list; private final CheckPoint checkPoint; - private List cache; - private int offset; - private int index = 0; + private final List cache; + private final int offset; + private int index; public CSHIterator(CSHArrayList list, CheckPoint checkPoint) { this.list = list; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CollectorServiceHandler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CollectorServiceHandler.java index 9704b5d4..d5f3d970 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CollectorServiceHandler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CollectorServiceHandler.java @@ -145,7 +145,7 @@ public void cleanMessages(ServiceHandlerRoute... routes) { logger.debug("clean: {}", (Object) routes); for (ServiceHandlerRoute route : routes) { - this.routeToMessages.get(route).clear(); + routeToMessages.get(route).clear(); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CustomDialog.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CustomDialog.java index 26631b55..84113f3e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CustomDialog.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/CustomDialog.java @@ -45,7 +45,7 @@ public class CustomDialog extends JDialog implements ActionListener private final JButton cancelButton = new JButton("Cancel"); private final JButton stopButton = new JButton("Stop"); - public byte doIt = 0; + public byte doIt; public GridBagConstraints getRC(int gridx, int gridy) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DefaultServiceContext.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DefaultServiceContext.java index 41f83c30..3d795fbd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DefaultServiceContext.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DefaultServiceContext.java @@ -64,7 +64,7 @@ public DefaultServiceContext(IServiceContext prototype, IMessageStorage messageS */ @Override public IDictionaryManager getDictionaryManager() { - return this.dictionaryManager; + return dictionaryManager; } /* (non-Javadoc) @@ -72,7 +72,7 @@ public IDictionaryManager getDictionaryManager() { */ @Override public IMessageStorage getMessageStorage() { - return this.messageStorage; + return messageStorage; } @Override @@ -85,7 +85,7 @@ public ServiceInfo lookupService(ServiceName serviceName) { */ @Override public ILoggingConfigurator getLoggingConfigurator() { - return this.loggingConfigurator; + return loggingConfigurator; } /* (non-Javadoc) @@ -93,7 +93,7 @@ public ILoggingConfigurator getLoggingConfigurator() { */ @Override public ITaskExecutor getTaskExecutor() { - return this.taskExecutor; + return taskExecutor; } /* (non-Javadoc) @@ -101,7 +101,7 @@ public ITaskExecutor getTaskExecutor() { */ @Override public IDataManager getDataManager() { - return this.dataManager; + return dataManager; } /* (non-Javadoc) @@ -109,7 +109,7 @@ public IDataManager getDataManager() { */ @Override public IWorkspaceDispatcher getWorkspaceDispatcher() { - return this.workspaceDispatcher; + return workspaceDispatcher; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DisabledServiceSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DisabledServiceSettings.java index d76169fe..43950533 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DisabledServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/DisabledServiceSettings.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -97,7 +98,7 @@ public Map getSettings() { } public void setSettings(Map settings) { - this.entries.clear(); + entries.clear(); convertMapToElementList(settings); } @@ -107,7 +108,7 @@ public List getEntries() { } private void convertMapToElementList(Map settings) { - for (Map.Entry entry : settings.entrySet()) { + for(Entry entry : settings.entrySet()) { DOMElement domElement = new DOMElement(new QName(entry.getKey())); domElement.setText(entry.getValue()); entries.add(domElement); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FileSessionStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FileSessionStorage.java index 76e72354..ace17d6f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FileSessionStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FileSessionStorage.java @@ -16,16 +16,6 @@ package com.exactpro.sf.services; -import com.exactpro.sf.configuration.workspace.FolderType; -import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import org.apache.commons.lang3.ClassUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -33,17 +23,28 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; - import java.time.LocalDate; import java.time.ZoneOffset; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.function.Predicate; import java.util.stream.Collectors; +import org.apache.commons.lang3.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.exactpro.sf.configuration.workspace.FolderType; +import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; + public class FileSessionStorage { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private static final String STORAGE = "session_manager_storage.json"; private static final ObjectReader jsonReader = new ObjectMapper().reader(new MapTypeReference()); @@ -78,7 +79,7 @@ public FileSessionStorage(IWorkspaceDispatcher workspaceDispatcher, String proto } tmpMap = tmpMap.entrySet().stream().filter(entry -> lifetimePredicate.test(entry.getValue().getTimestamp())) - .collect(Collectors.toConcurrentMap(Map.Entry::getKey, Map.Entry::getValue)); + .collect(Collectors.toConcurrentMap(Entry::getKey, Entry::getValue)); metadataMap = tmpMap; } @@ -98,14 +99,8 @@ public void flush() throws Exception { } public T readSessionProperty(String key) { - TimestampedValue tval = (TimestampedValue) metadataMap.get(key); - - if ((tval != null) && lifetimePredicate.test(tval.getTimestamp())) { - return tval.value; - } else { - return null; - } + return (tval != null) && lifetimePredicate.test(tval.getTimestamp()) ? tval.value : null; } public void putSessionProperty(String key, T value) { @@ -118,7 +113,7 @@ public void putSessionProperty(String key, T value) { } private boolean checkType(Class clazz) { - return String.class == clazz || ClassUtils.isPrimitiveWrapper(clazz); + return clazz == String.class || ClassUtils.isPrimitiveWrapper(clazz); } private static class MapTypeReference extends TypeReference>> { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FilterServiceHandlerWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FilterServiceHandlerWrapper.java index 6aa6d0b7..5c01d72a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FilterServiceHandlerWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/FilterServiceHandlerWrapper.java @@ -38,7 +38,7 @@ public FilterServiceHandlerWrapper(IServiceHandler serviceHandler, Set p @Override public void putMessage(ISession session, ServiceHandlerRoute route, IMessage message) throws ServiceHandlerException { - if (this.processedMessageTypes.contains(message.getName())) { + if(processedMessageTypes.contains(message.getName())) { super.putMessage(session, route, message); } else { logger.trace("Message {} skipped by service settings. Route {}, Session {}", message.getName(), route, session); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/IService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/IService.java index 9b37367b..d462dd0c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/IService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/IService.java @@ -33,11 +33,11 @@ public interface IService * @param name * */ - void init(final IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName name); + void init(IServiceContext serviceContext, + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName name); void start(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/MessageHelper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/MessageHelper.java index 5414cf32..ecccf391 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/MessageHelper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/MessageHelper.java @@ -31,7 +31,6 @@ import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.messages.structures.IMessageStructure; import com.exactpro.sf.common.messages.structures.StructureUtils; -import com.exactpro.sf.configuration.IDictionaryManager; public abstract class MessageHelper { @@ -59,11 +58,8 @@ public IMessage prepareMessageToEncode(Map message, Map files) { FileInputStream fis = new FileInputStream(e.getValue()); zos.putNextEntry(new ZipEntry(e.getKey())); int len; - while ((len = fis.read(buf)) > 0) - zos.write(buf, 0, len); + while((len = fis.read(buf)) > 0) { + zos.write(buf, 0, len); + } fis.close(); zos.closeEntry(); } @@ -200,8 +201,8 @@ private EnvironmentDescription unmarshalFromZip(InputStream stream, List addRepeatedTask(Runnable task, long initialDelay, @Override public void dispose() { - if(!this.threadPool.isShutdown() || !this.scheduledThreadPool.isShutdown()) { + if(!threadPool.isShutdown() || !scheduledThreadPool.isShutdown()) { logger.info("TaskExecutor disposing started..."); try { - if (!this.threadPool.isShutdown()) { - this.threadPool.shutdownNow(); - if (!this.threadPool.awaitTermination(5000, TimeUnit.MILLISECONDS)) { + if(!threadPool.isShutdown()) { + threadPool.shutdownNow(); + if(!threadPool.awaitTermination(5000, TimeUnit.MILLISECONDS)) { logger.warn("Some Threads from cachedThreadPool remained alive"); } } @@ -92,9 +92,9 @@ public void dispose() } try { - if (!this.scheduledThreadPool.isShutdown()) { - this.scheduledThreadPool.shutdownNow(); - if (!this.scheduledThreadPool.awaitTermination(5000, TimeUnit.MILLISECONDS)) { + if(!scheduledThreadPool.isShutdown()) { + scheduledThreadPool.shutdownNow(); + if(!scheduledThreadPool.awaitTermination(5000, TimeUnit.MILLISECONDS)) { logger.warn("Some Threads from scheduledThreadPool remained alive"); } } @@ -149,22 +149,22 @@ public TaskRunnableWrapper(Runnable wrappedTask) { @Override public void run() { - long timeInQueue = System.currentTimeMillis() - this.createTime; - - String oldName = null; + long timeInQueue = System.currentTimeMillis() - createTime; + + String oldName = null; Thread currentThread = null; - - if (this.threadName != null) { + + if(threadName != null) { currentThread = Thread.currentThread(); oldName = currentThread.getName(); - - setThreadName(currentThread, this.threadName); + + setThreadName(currentThread, threadName); } try { executeTask(timeInQueue); } finally { - if (currentThread != null && this.threadName != null) { + if(currentThread != null && threadName != null) { setThreadName(currentThread, oldName); } } @@ -206,22 +206,22 @@ public TaskCallableWrapper(Callable wrappedTask) { @Override public T call() throws Exception { - long timeInQueue = System.currentTimeMillis() - this.createTime; - + long timeInQueue = System.currentTimeMillis() - createTime; + String oldName = null; Thread currentThread = null; - - if (this.threadName != null) { + + if(threadName != null) { currentThread = Thread.currentThread(); oldName = currentThread.getName(); - - setThreadName(currentThread, this.threadName); + + setThreadName(currentThread, threadName); } try { return executeTask(timeInQueue); } finally { - if (currentThread != null && this.threadName != null) { + if(currentThread != null && threadName != null) { setThreadName(currentThread, oldName); } } @@ -252,7 +252,7 @@ public TaskRepeatableWrapper(Runnable wrappedTask, long initialDelay, long delay @Override public void run() { super.run(); - this.createTime = System.currentTimeMillis() + this.delay; + this.createTime = System.currentTimeMillis() + delay; } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketAcceptor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketAcceptor.java index 00020456..0e21b4e1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketAcceptor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketAcceptor.java @@ -37,7 +37,7 @@ * @author nikita.smirnov */ public class WrapperNioSocketAcceptor { - private final static Logger logger = LoggerFactory.getLogger(WrapperNioSocketAcceptor.class); + private static final Logger logger = LoggerFactory.getLogger(WrapperNioSocketAcceptor.class); private final NioSocketAcceptor nioSocketAcceptor; private final IoProcessor ioProcessor; private final ITaskExecutor taskExecutor; @@ -55,30 +55,30 @@ public WrapperNioSocketAcceptor(ITaskExecutor taskExecutor) { } public void bind() throws IOException { - this.nioSocketAcceptor.bind(); + nioSocketAcceptor.bind(); } public void bind(Iterable localAddresses) throws IOException { - this.nioSocketAcceptor.bind(localAddresses); + nioSocketAcceptor.bind(localAddresses); } public void bind(SocketAddress localAddress) throws IOException { - this.nioSocketAcceptor.bind(localAddress); + nioSocketAcceptor.bind(localAddress); } public void unbind() { - this.nioSocketAcceptor.unbind(); + nioSocketAcceptor.unbind(); } public void unbind(SocketAddress localAddress) { - this.nioSocketAcceptor.unbind(localAddress); + nioSocketAcceptor.unbind(localAddress); } public Future dispose() { return dispose(false); } - - public Future dispose(final boolean awaitTermination) { + + public Future dispose(boolean awaitTermination) { if(taskExecutor != null){ return taskExecutor.addTask(new Runnable() { @Override @@ -101,27 +101,27 @@ public String toString() { } public void setCloseOnDeactivation(boolean disconnectClientsOnUnbind) { - this.nioSocketAcceptor.setCloseOnDeactivation(disconnectClientsOnUnbind); + nioSocketAcceptor.setCloseOnDeactivation(disconnectClientsOnUnbind); } public void setHandler(IoHandler handler) { - this.nioSocketAcceptor.setHandler(handler); + nioSocketAcceptor.setHandler(handler); } public void setReuseAddress(boolean reuseAddress) { - this.nioSocketAcceptor.setReuseAddress(reuseAddress); + nioSocketAcceptor.setReuseAddress(reuseAddress); } public void setDefaultLocalAddress(Iterable localAddress) { - this.nioSocketAcceptor.setDefaultLocalAddresses(localAddress); + nioSocketAcceptor.setDefaultLocalAddresses(localAddress); } public void setDefaultLocalAddress(SocketAddress localAddress) { - this.nioSocketAcceptor.setDefaultLocalAddress(localAddress); + nioSocketAcceptor.setDefaultLocalAddress(localAddress); } public IoSessionConfig getSessionConfig() { - return this.nioSocketAcceptor.getSessionConfig(); + return nioSocketAcceptor.getSessionConfig(); } public NioSocketAcceptor getNioSocketAcceptor() { @@ -129,15 +129,15 @@ public NioSocketAcceptor getNioSocketAcceptor() { } public DefaultIoFilterChainBuilder getFilterChain() { - return this.nioSocketAcceptor.getFilterChain(); + return nioSocketAcceptor.getFilterChain(); } public boolean isDisposed() { - return this.nioSocketAcceptor.isDisposed(); + return nioSocketAcceptor.isDisposed(); } public boolean isActive() { - return this.nioSocketAcceptor.isActive(); + return nioSocketAcceptor.isActive(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketConnector.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketConnector.java index b45975d0..9c505cc0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketConnector.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/WrapperNioSocketConnector.java @@ -38,7 +38,7 @@ * @author nikita.smirnov */ public class WrapperNioSocketConnector { - private final static Logger logger = LoggerFactory.getLogger(WrapperNioSocketConnector.class); + private static final Logger logger = LoggerFactory.getLogger(WrapperNioSocketConnector.class); private final NioSocketConnector nioSocketConnector; private final IoProcessor ioProcessor; private final ITaskExecutor taskExecutor; @@ -56,26 +56,26 @@ public WrapperNioSocketConnector(ITaskExecutor taskExecutor) { } public void setConnectTimeoutMillis(long connectTimeoutInMillis) { - this.nioSocketConnector.setConnectTimeoutMillis(connectTimeoutInMillis); + nioSocketConnector.setConnectTimeoutMillis(connectTimeoutInMillis); } public ConnectFuture connect() { - return this.nioSocketConnector.connect(); + return nioSocketConnector.connect(); } public ConnectFuture connect(SocketAddress remoteAddress) { - return this.nioSocketConnector.connect(remoteAddress); + return nioSocketConnector.connect(remoteAddress); } public ConnectFuture connect(IoSessionInitializer sessionInitializer) { - return this.nioSocketConnector.connect(sessionInitializer); + return nioSocketConnector.connect(sessionInitializer); } public Future dispose() { return dispose(false); } - - public Future dispose(final boolean awaitTermination) { + + public Future dispose(boolean awaitTermination) { if(taskExecutor != null){ return taskExecutor.addTask(new Runnable() { @Override @@ -98,15 +98,15 @@ public String toString() { } public void setHandler(IoHandler handler) { - this.nioSocketConnector.setHandler(handler); + nioSocketConnector.setHandler(handler); } public void setDefaultRemoteAddress(SocketAddress defaultRemoteAddress) { - this.nioSocketConnector.setDefaultRemoteAddress(defaultRemoteAddress); + nioSocketConnector.setDefaultRemoteAddress(defaultRemoteAddress); } public IoSessionConfig getSessionConfig() { - return this.nioSocketConnector.getSessionConfig(); + return nioSocketConnector.getSessionConfig(); } public NioSocketConnector getNioSocketConnector() { @@ -114,15 +114,15 @@ public NioSocketConnector getNioSocketConnector() { } public DefaultIoFilterChainBuilder getFilterChain() { - return this.nioSocketConnector.getFilterChain(); + return nioSocketConnector.getFilterChain(); } public boolean isDisposed() { - return this.nioSocketConnector.isDisposed(); + return nioSocketConnector.isDisposed(); } public boolean isActive() { - return this.nioSocketConnector.isActive(); + return nioSocketConnector.isActive(); } public IoProcessor getIoProcessor() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/CodecMessageFilter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/CodecMessageFilter.java index 7b7e4b93..b8e4a39a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/CodecMessageFilter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/CodecMessageFilter.java @@ -58,7 +58,7 @@ public CodecMessageFilter(String filterValuesString) { messageSpecialField = new HashMap<>(); filterValues = parseFilterValues(filterValuesString); - logger.info("Filter values: {}", this.filterValues); + logger.info("Filter values: {}", filterValues); } @@ -89,12 +89,12 @@ public enum SpecialAttribute { private final String attribut; - private SpecialAttribute(String attribut) { + SpecialAttribute(String attribut) { this.attribut = attribut; } public String getAttribut() { - return this.attribut; + return attribut; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/HackedProtocolCodecFilter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/HackedProtocolCodecFilter.java index c404e659..2a1b63d3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/HackedProtocolCodecFilter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/codecs/HackedProtocolCodecFilter.java @@ -91,7 +91,7 @@ public HackedProtocolCodecFilter(ProtocolCodecFactory factory) { * @param encoder The class responsible for encoding the message * @param decoder The class responsible for decoding the message */ - public HackedProtocolCodecFilter(final ProtocolEncoder encoder, final ProtocolDecoder decoder) { + public HackedProtocolCodecFilter(ProtocolEncoder encoder, ProtocolDecoder decoder) { if (encoder == null) { throw new IllegalArgumentException("encoder"); } @@ -122,8 +122,8 @@ public ProtocolDecoder getDecoder(IoSession session) { * @param encoder The class responsible for encoding the message * @param decoder The class responsible for decoding the message */ - public HackedProtocolCodecFilter(final Class encoderClass, - final Class decoderClass) { + public HackedProtocolCodecFilter(Class encoderClass, + Class decoderClass) { if (encoderClass == null) { throw new IllegalArgumentException("encoderClass"); } @@ -147,7 +147,7 @@ public HackedProtocolCodecFilter(final Class encoderC throw new IllegalArgumentException("decoderClass doesn't have a public default constructor."); } - final ProtocolEncoder encoder; + ProtocolEncoder encoder; try { encoder = encoderClass.newInstance(); @@ -155,7 +155,7 @@ public HackedProtocolCodecFilter(final Class encoderC throw new IllegalArgumentException("encoderClass cannot be initialized"); } - final ProtocolDecoder decoder; + ProtocolDecoder decoder; try { decoder = decoderClass.newInstance(); @@ -242,12 +242,7 @@ public void messageReceived(NextFilter nextFilter, IoSession session, Object mes // Finish decoding if no exception was thrown. decoderOut.flush(nextFilter, session); } catch (Throwable t) { - ProtocolDecoderException pde; - if (t instanceof ProtocolDecoderException) { - pde = (ProtocolDecoderException) t; - } else { - pde = new ProtocolDecoderException(t); - } + ProtocolDecoderException pde = t instanceof ProtocolDecoderException ? (ProtocolDecoderException)t : new ProtocolDecoderException(t); if (pde.getHexdump() == null) { // Generate a message hex dump @@ -315,18 +310,18 @@ public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest w encoder.encode(session, message, encoderOut); // Send it directly - Queue bufferQueue = ((AbstractProtocolEncoderOutput) encoderOut).getMessageQueue(); + Queue bufferQueue = ((AbstractProtocolEncoderOutput)encoderOut).getMessageQueue(); // Write all the encoded messages now - while (!bufferQueue.isEmpty()) { + while(!bufferQueue.isEmpty()) { Object encodedMessage = bufferQueue.poll(); - if (encodedMessage == null) { + if(encodedMessage == null) { break; } // Flush only when the buffer has remaining. - if (!(encodedMessage instanceof IoBuffer) || ((IoBuffer) encodedMessage).hasRemaining()) { + if(!(encodedMessage instanceof IoBuffer) || ((IoBuffer)encodedMessage).hasRemaining()) { SocketAddress destination = writeRequest.getDestination(); WriteRequest encodedWriteRequest = new EncodedWriteRequest(encodedMessage, null, destination); @@ -336,17 +331,11 @@ public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest w // Call the next filter nextFilter.filterWrite(session, new MessageWriteRequest(writeRequest)); + } catch(ProtocolEncoderException e) { + throw e; } catch (Throwable t) { - ProtocolEncoderException pee; - // Generate the correct exception - if (t instanceof ProtocolEncoderException) { - pee = (ProtocolEncoderException) t; - } else { - pee = new ProtocolEncoderException(t); - } - - throw pee; + throw new ProtocolEncoderException(t); } } @@ -358,14 +347,10 @@ public void sessionClosed(NextFilter nextFilter, IoSession session) throws Excep try { decoder.finishDecode(session, decoderOut); + } catch(ProtocolDecoderException e) { + throw e; } catch (Throwable t) { - ProtocolDecoderException pde; - if (t instanceof ProtocolDecoderException) { - pde = (ProtocolDecoderException) t; - } else { - pde = new ProtocolDecoderException(t); - } - throw pde; + throw new ProtocolDecoderException(t); } finally { // Dispose everything disposeCodec(session); @@ -456,7 +441,7 @@ public WriteFuture flush() { if (future == null) { // Creates an empty writeRequest containing the destination WriteRequest writeRequest = new DefaultWriteRequest(null, null, destination); - future = DefaultWriteFuture.newNotWrittenFuture(session, new NothingWrittenException(writeRequest)); + return DefaultWriteFuture.newNotWrittenFuture(session, new NothingWrittenException(writeRequest)); } return future; @@ -521,25 +506,25 @@ private void disposeDecoder(IoSession session) { private ProtocolDecoderOutput getDecoderOut(IoSession session, NextFilter nextFilter) { //ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT); - if (this.decOut == null) { + if(decOut == null) { // Create a new instance, and stores it into the session this.decOut = new ProtocolDecoderOutputImpl(); //session.setAttribute(DECODER_OUT, out); } - return this.decOut; + return decOut; } private ProtocolEncoderOutput getEncoderOut(IoSession session, NextFilter nextFilter, WriteRequest writeRequest) { //ProtocolEncoderOutput out = (ProtocolEncoderOutput) session.getAttribute(ENCODER_OUT); - if (this.encOut == null) { + if(encOut == null) { // Create a new instance, and stores it into the session this.encOut = new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest); //session.setAttribute(ENCODER_OUT, out); } - return this.encOut; + return encOut; } /** diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeClientService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeClientService.java index 65f78112..a3247d21 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeClientService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeClientService.java @@ -61,20 +61,20 @@ protected void disposeResources() { } public IMessageStorage getStorage() { - return this.storage; + return storage; } public ServiceInfo getServiceInfo() { - return this.serviceInfo; + return serviceInfo; } public IDictionaryStructure getDictionary() { - return this.dictionary; + return dictionary; } @Override public FakeSession getSession() { - return this.session; + return session; } public void removeFilters(IMessage message) @@ -85,7 +85,7 @@ public void removeFilters(IMessage message) Object field = message.getField(fldStruct.getName()); - if(null == field) + if(field == null) { continue; } @@ -112,12 +112,7 @@ public void messageReceived(IMessage message) throws Exception removeFilters(message); boolean admin = false; persistMessage(admin, message, serviceName.toString(), serviceName.toString()); - - if (admin) { - handler.putMessage(session, ServiceHandlerRoute.FROM_ADMIN, message); - } else { - handler.putMessage(session, ServiceHandlerRoute.FROM_APP, message); - } + handler.putMessage(session, admin ? ServiceHandlerRoute.FROM_ADMIN : ServiceHandlerRoute.FROM_APP, message); } public void messageSent(IMessage message) throws Exception @@ -126,14 +121,7 @@ public void messageSent(IMessage message) throws Exception persistMessage(admin, message, serviceName.toString(), serviceName.toString()); // Putting message into a service handler - if (admin) - { - handler.putMessage(session, ServiceHandlerRoute.TO_ADMIN, message); - } - else - { - handler.putMessage(session, ServiceHandlerRoute.TO_APP, message); - } + handler.putMessage(session, admin ? ServiceHandlerRoute.TO_ADMIN : ServiceHandlerRoute.TO_APP, message); } // Persists message to storage diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeSession.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeSession.java index 0910565f..818ef24e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeSession.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/fake/FakeSession.java @@ -25,11 +25,11 @@ import com.exactpro.sf.services.ISession; public class FakeSession implements ISession { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private final String name; private volatile boolean closed; - private volatile FakeClientService fakeService; + private final FakeClientService fakeService; public FakeSession(FakeClientService fakeService) { @@ -49,7 +49,7 @@ public IMessage send(Object message) { try { - this.fakeService.messageSent((IMessage)message); + fakeService.messageSent((IMessage)message); } catch (Exception e) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackService.java index 56f0e778..22d045dc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackService.java @@ -44,7 +44,7 @@ public class LoopbackService implements IInitiatorService { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private ServiceName serviceName; private IServiceHandler handler; @@ -55,16 +55,16 @@ public class LoopbackService implements IInitiatorService { private ILoggingConfigurator logConfigurator; private volatile ServiceStatus status = ServiceStatus.CREATED; - private volatile LoopbackSession session = null; + private volatile LoopbackSession session; @Override public void init( - final IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName name) { + IServiceContext serviceContext, + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName name) { this.serviceName = name; this.handler = Objects.requireNonNull(handler, "'Service handler' parameter"); @@ -79,7 +79,7 @@ public void init( @Override public void start() { - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); session = new LoopbackSession(); status = ServiceStatus.STARTED; } @@ -88,7 +88,7 @@ public void start() { public void dispose() { session = null; if (logConfigurator != null) { - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } status = ServiceStatus.DISPOSED; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackServiceSettings.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackServiceSettings.java index 8633adb0..5d35b7f0 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/loopback/LoopbackServiceSettings.java @@ -26,7 +26,7 @@ public class LoopbackServiceSettings extends AbstractServiceSettings{ private SailfishURI dictionaryName; @Override public SailfishURI getDictionaryName() { - return this.dictionaryName; + return dictionaryName; } @Override public void setDictionaryName(SailfishURI dictionaryName) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINASession.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINASession.java index 6d3bdd41..e353606b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINASession.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINASession.java @@ -53,7 +53,7 @@ public MINASession(ServiceName serviceName, IoSession session, ILoggingConfigura @Override public String getName() { - return this.serviceName.toString(); + return serviceName.toString(); } @Override @@ -88,11 +88,7 @@ public IMessage send(Object message, long timeout) throws InterruptedException { throw new SendMessageFailedException("Message send failed. Session: " + this, future.getException()); } - if(message instanceof IMessage) { - return (IMessage)message; - } - - return null; + return message instanceof IMessage ? (IMessage)message : null; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINAUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINAUtil.java index 4218db84..e0018a55 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINAUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/mina/MINAUtil.java @@ -44,19 +44,13 @@ public class MINAUtil { - public static String getHexdumpAdv(final IoBuffer in, int lengthLimit) { + public static String getHexdumpAdv(IoBuffer in, int lengthLimit) { if (lengthLimit == 0) { throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)"); } boolean truncate = in.remaining() > lengthLimit; - int size; - - if (truncate) { - size = lengthLimit; - } else { - size = in.remaining(); - } + int size = truncate ? lengthLimit : in.remaining(); if (size == 0) { return "empty"; @@ -84,9 +78,9 @@ public static SslFilter createSslFilter(boolean clientMode, String protocol, CertificateException, UnrecoverableKeyException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance(protocol); - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + TrustManager[] trustAllCerts = { new X509TrustManager() { @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { + public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @@ -130,7 +124,7 @@ private static KeyStore getKeyStore(String keyStoreType, String keyStore, char[] KeyStore ks = KeyStore.getInstance(keyStoreType); try (InputStream is = new FileInputStream(new File(keyStore))) { ks.load(is, keyStorePassword); + return ks; } - return ks; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyClientService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyClientService.java index 04c6b8c9..8f46b4ce 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyClientService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyClientService.java @@ -16,7 +16,7 @@ package com.exactpro.sf.services.netty; import java.util.LinkedHashMap; -import java.util.Map; +import java.util.Map.Entry; import java.util.Objects; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -62,7 +62,7 @@ public abstract class NettyClientService implements IInitiatorService { - protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + protected final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); protected final ChannelFutureListener SET_CHANNEL = future -> setChannel(future.channel()); @@ -80,13 +80,13 @@ public abstract class NettyClientService implements IInitiatorService { protected volatile ServiceStatus serviceStatus = ServiceStatus.CREATED; protected volatile NettySession nettySession; // FIXME volatile?? - protected volatile NioEventLoopGroup nioEventLoopGroup = null; + protected volatile NioEventLoopGroup nioEventLoopGroup; protected IMessageFactory msgFactory; - protected Future hbFuture = null; + protected Future hbFuture; private final ReadWriteLock channelLock = new ReentrantReadWriteLock(); - private Channel channel = null; + private Channel channel; // At least it should contains: // * YourCodec(s) @@ -108,7 +108,7 @@ public void run() { try { // FIXME: synchronize? serviceHandler.sessionIdle(nettySession, IdleStatus.WRITER_IDLE); - NettyClientService.this.sendHeartBeat(); + sendHeartBeat(); } catch (Exception e) { logger.error("OnIdle", e); } @@ -117,11 +117,11 @@ public void run() { @Override public void init( - final IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName name) { + IServiceContext serviceContext, + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName name) { try { changeStatus(ServiceStatus.INITIALIZING, "Service initializing", null); @@ -155,7 +155,7 @@ public void start() { try { changeStatus(ServiceStatus.STARTING, "Starting service " + serviceName, null); - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); nettySession = new NettySession(this, logConfigurator); @@ -175,9 +175,9 @@ public void start() { @Override public void connect() throws Exception { - this.initChannelHandlers(this.serviceContext); + initChannelHandlers(serviceContext); - final LinkedHashMap handlers = getChannelHandlers(); + LinkedHashMap handlers = getChannelHandlers(); Bootstrap cb = new Bootstrap(); // Fixme: use ITaskExecutor ? @@ -189,7 +189,7 @@ public void connect() throws Exception { cb.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { - for (Map.Entry entry : handlers.entrySet()) { + for(Entry entry : handlers.entrySet()) { ch.pipeline().addLast(entry.getKey(), entry.getValue()); } // add exception handler for inbound messages @@ -221,22 +221,22 @@ public void operationComplete(ChannelFuture future) throws Exception { @Override public void dispose() { - this.changeStatus(ServiceStatus.DISPOSING, "Service disposing", null); + changeStatus(ServiceStatus.DISPOSING, "Service disposing", null); try { - NettySession session = this.nettySession; + NettySession session = nettySession; if (session != null) { nettySession = null; session.close(); } } catch (RuntimeException e) { - this.changeStatus(ServiceStatus.ERROR, "Session '"+serviceName +"' has not been closed", e); + changeStatus(ServiceStatus.ERROR, "Session '" + serviceName + "' has not been closed", e); } finally { Channel localChannel = getChannel(); if (localChannel != null) { if (localChannel.isOpen()) { if (!localChannel.close().awaitUninterruptibly(5, TimeUnit.SECONDS)) { - this.changeStatus(ServiceStatus.ERROR, "Channel '" + serviceName + "' has not been closed for 5 secons", null); + changeStatus(ServiceStatus.ERROR, "Channel '" + serviceName + "' has not been closed for 5 secons", null); } } @@ -250,7 +250,7 @@ public void dispose() { if (nioEventLoopGroup != null) { if (!nioEventLoopGroup.isShutdown()) { if(!nioEventLoopGroup.shutdownGracefully().awaitUninterruptibly(5, TimeUnit.SECONDS)) { - this.changeStatus(ServiceStatus.ERROR, "Events executor '" + serviceName + "' has not been closed for 5 secons", null); + changeStatus(ServiceStatus.ERROR, "Events executor '" + serviceName + "' has not been closed for 5 secons", null); } } @@ -260,13 +260,13 @@ public void dispose() { } if(logConfigurator != null){ - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } } - if (this.serviceStatus == ServiceStatus.DISPOSING) { - this.changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); + if(serviceStatus == ServiceStatus.DISPOSING) { + changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); } } @@ -318,10 +318,10 @@ public IMessage receive(IActionContext actionContext, IMessage msg) throws Inter // Used in session public Channel getChannel() { try { - this.channelLock.readLock().lock(); + channelLock.readLock().lock(); return channel; } finally { - this.channelLock.readLock().unlock(); + channelLock.readLock().unlock(); } } @@ -360,10 +360,10 @@ protected void stopSendHeartBeats() { private void setChannel(Channel channel) { try { - this.channelLock.writeLock().lock(); + channelLock.writeLock().lock(); this.channel = channel; } finally { - this.channelLock.writeLock().unlock(); + channelLock.writeLock().unlock(); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyMulticastClientService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyMulticastClientService.java index 18169d94..52cd2a2f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyMulticastClientService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettyMulticastClientService.java @@ -19,7 +19,7 @@ import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.util.LinkedHashMap; -import java.util.Map; +import java.util.Map.Entry; import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.configuration.IDictionaryManager; @@ -60,12 +60,12 @@ public void start() { try { changeStatus(ServiceStatus.STARTING, "Starting service " + serviceName, null); - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); nettySession = new NettySession(this, logConfigurator); - this.initChannelHandlers(this.serviceContext); + initChannelHandlers(serviceContext); connect(); @@ -78,7 +78,7 @@ public void start() { @Override public void connect() throws Exception { - final LinkedHashMap handlers = getChannelHandlers(); + LinkedHashMap handlers = getChannelHandlers(); String localIP = getSettings().getLocalIP(); String bindIp = (getSettings().getBindIp() == null) ? getSettings().getMulticastIp() : getSettings().getBindIp(); @@ -106,7 +106,7 @@ public Channel newChannel() { cb.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { - for (Map.Entry entry : handlers.entrySet()) { + for(Entry entry : handlers.entrySet()) { ch.pipeline().addLast(entry.getKey(), entry.getValue()); } // add exception handler for inbound messages @@ -128,7 +128,7 @@ public void operationComplete(ChannelFuture bindFuture) throws Exception { // TODO: heartbeat loss detection ChannelFuture future; - String sourceIP = NettyMulticastClientService.this.getSettings().getSourceIp(); + String sourceIP = getSettings().getSourceIp(); if (sourceIP == null) { future = channel.joinGroup(multicastGroup, localNetworkInterface); } @@ -150,9 +150,9 @@ public void operationComplete(ChannelFuture bindFuture) throws Exception { @Override public void dispose() { - this.changeStatus(ServiceStatus.DISPOSING, "Service disposing", null); + changeStatus(ServiceStatus.DISPOSING, "Service disposing", null); - NettySession session = this.nettySession; + NettySession session = nettySession; if (session != null) { nettySession = null; session.close(); @@ -164,9 +164,9 @@ public void dispose() { localChannel.close().syncUninterruptibly(); } - this.changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); // FIXME: the same called from closeFuture.listen + changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); // FIXME: the same called from closeFuture.listen - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } @@ -202,13 +202,15 @@ public void operationComplete(ChannelFuture future) throws Exception { @Override protected void initService(IDictionaryManager dictionaryManager, IServiceSettings settings) { - if ( settings.getDictionaryName() == null ) + if(settings.getDictionaryName() == null) { throw new IllegalArgumentException("'dictionaryName' parameter incorrect"); + } this.dictionary = dictionaryManager.getDictionary(settings.getDictionaryName()); - if ( this.dictionary == null ) + if(dictionary == null) { throw new ServiceException("can't create dictionary"); + } } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettySession.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettySession.java index c9bf8f3a..45805bbf 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettySession.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/NettySession.java @@ -30,19 +30,18 @@ public class NettySession implements ISession { protected final Logger logger = LoggerFactory - .getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + .getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private final ILoggingConfigurator logConfigurator; private final NettyClientService client; - public NettySession(final NettyClientService client, ILoggingConfigurator logConfigurator) { - super(); - if (client == null) { + public NettySession(NettyClientService client, ILoggingConfigurator logConfigurator) { + if(client == null) { throw new NullPointerException(); } this.client = client; this.logConfigurator = logConfigurator; - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), client.getServiceName()); } @@ -82,12 +81,13 @@ public IMessage send(Object message) throws InterruptedException { logger.error("Send operation is not completed. Session: {}", this); isSendSuccess = false; } - if (future.cause() != null) - throw new EPSCommonException("Message sent failed. Session: " + this, future.cause()); + if(future.cause() != null) { + throw new EPSCommonException("Message sent failed. Session: " + this, future.cause()); + } if (!isSendSuccess) { throw new SendMessageFailedException( - "Message wasn't send during 1 second." + errorMsg.toString() + " Session: " + this); + "Message wasn't send during 1 second." + errorMsg + " Session: " + this); } return msg; @@ -106,16 +106,14 @@ public void onExceptionCaught(Throwable cause) { @Override public void close() { client.stop("Close session", null); - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), client.getServiceName()); } @Override public boolean isClosed() { - if (client.getChannel() == null) - return true; - return !(client.getChannel().isActive() || client.getChannel().isOpen()); - } + return client.getChannel() == null || !(client.getChannel().isActive() || client.getChannel().isOpen()); + } @Override public boolean isLoggedOn() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/ExceptionInboundHandler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/ExceptionInboundHandler.java index 346b1aab..d14f98be 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/ExceptionInboundHandler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/ExceptionInboundHandler.java @@ -25,8 +25,7 @@ public class ExceptionInboundHandler extends ChannelInboundHandlerAdapter { private final NettySession session; public ExceptionInboundHandler(NettySession session) { - super(); - this.session = session; + this.session = session; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/MessagePersisterHandler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/MessagePersisterHandler.java index 73732f35..c6ce9e23 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/MessagePersisterHandler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/MessagePersisterHandler.java @@ -50,7 +50,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) ctx.write(msg, promise); } - protected void persistRecievedMessage(final IMessage message) { + protected void persistRecievedMessage(IMessage message) { message.getMetaData().setServiceInfo(serviceInfo); storage.storeMessage(message); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/NettyServiceHandler.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/NettyServiceHandler.java index b0ff031b..c012beb4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/NettyServiceHandler.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/netty/handlers/NettyServiceHandler.java @@ -29,13 +29,12 @@ public class NettyServiceHandler extends ChannelDuplexHandler { // FIXME: IServiceHandler throws exceptions! - private IServiceHandler serviceHandler; + private final IServiceHandler serviceHandler; - private ISession session; + private final ISession session; public NettyServiceHandler(IServiceHandler serviceHandler, ISession session) { - super(); - this.serviceHandler = serviceHandler; + this.serviceHandler = serviceHandler; this.session = session; } @@ -44,12 +43,7 @@ public NettyServiceHandler(IServiceHandler serviceHandler, ISession session) { public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof IMessage) { IMessage imsg = (IMessage) msg; - if (imsg.getMetaData().isAdmin()) { - serviceHandler.putMessage(session, ServiceHandlerRoute.TO_ADMIN, imsg); - } - else { - serviceHandler.putMessage(session, ServiceHandlerRoute.TO_APP, imsg); - } + serviceHandler.putMessage(session, imsg.getMetaData().isAdmin() ? ServiceHandlerRoute.TO_ADMIN : ServiceHandlerRoute.TO_APP, imsg); } ctx.write(msg, promise); } @@ -74,12 +68,7 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof IMessage) { IMessage imsg = (IMessage) msg; - if (imsg.getMetaData().isAdmin()) { - serviceHandler.putMessage(session, ServiceHandlerRoute.FROM_ADMIN, imsg); - } - else { - serviceHandler.putMessage(session, ServiceHandlerRoute.FROM_APP, imsg); - } + serviceHandler.putMessage(session, imsg.getMetaData().isAdmin() ? ServiceHandlerRoute.FROM_ADMIN : ServiceHandlerRoute.FROM_APP, imsg); } ctx.fireChannelRead(msg); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/RulesProcessor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/RulesProcessor.java index 2349e62c..04b3d79f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/RulesProcessor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/RulesProcessor.java @@ -40,11 +40,10 @@ public class RulesProcessor { private final Map> mapStorage = new HashMap<>(); public RulesProcessor(Rules rules) { - super(); - this.rules = rules; + this.rules = rules; } - public boolean processMessage(final IMessage message) { + public boolean processMessage(IMessage message) { boolean notSend = false; for (RuleDescription rule : rules.getRuleDescription()) { @@ -73,7 +72,7 @@ public boolean processMessage(final IMessage message) { msg.addField(changeField.getName(), changeField.getValue()); } } - } // if CHANGE + } if (rule.getRemove() != null) { for (FieldName removeField : rule.getRemove().getField()) { @@ -82,7 +81,7 @@ public boolean processMessage(final IMessage message) { msg.removeField(removeField.getName()); } } - } // if REMOVE + } if (rule.getSave() != null) { for (FieldPosition saveField : rule.getSave().getField()) { @@ -91,8 +90,8 @@ public boolean processMessage(final IMessage message) { fieldStorage.put(mappingAlias, lookupField(message, fieldName)); } - } // if SAVE - if (null != rule.getLoad()) { + } + if(rule.getLoad() != null) { for (FieldPosition loadField : rule.getLoad().getField()) { String fieldName = loadField.getName(); String mappingAlias = loadField.getValue(); @@ -104,9 +103,9 @@ public boolean processMessage(final IMessage message) { logger.debug("Can't load: path not found in message"); } } - } // if LOAD + } - if (null != rule.getSaveMapping()) { + if(rule.getSaveMapping() != null) { for (FieldMapping saveMappingField : rule.getSaveMapping().getField()) { key = saveMappingField.getKeyField(); value = saveMappingField.getValueField(); @@ -119,8 +118,8 @@ public boolean processMessage(final IMessage message) { map.put(String.valueOf(lookupField(message, key)), lookupField(message, value)); } - } // if SAVE MAPPING - if (null != rule.getLoadMapping()) { + } + if(rule.getLoadMapping() != null) { for (FieldMapping loadMappingField : rule.getLoadMapping().getField()) { key = loadMappingField.getKeyField(); value = loadMappingField.getValueField(); @@ -136,7 +135,7 @@ public boolean processMessage(final IMessage message) { msg.addField(value, map.get(lookupField(msg, key))); } } - } // if LOAD MAPPING + } } } return notSend; @@ -169,18 +168,11 @@ private IMessage lookupParentToFieldMessage(IMessage message, String name) { // FIXME: collections? Object nested = message.getField(group); - - if (nested instanceof IMessage) { - return lookupParentToFieldMessage((IMessage) nested, restName); - } - return null; - } + return nested instanceof IMessage ? lookupParentToFieldMessage((IMessage)nested, restName) : null; + } - private static String getLastFiled(final String path) { - if (path.indexOf('.') < 0) { - return path; - } - return path.substring(path.lastIndexOf('.')); - } + private static String getLastFiled(String path) { + return path.indexOf('.') < 0 ? path : path.substring(path.lastIndexOf('.')); + } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/ServiceUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/ServiceUtil.java index c1d6e684..033f7bdf 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/ServiceUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/services/util/ServiceUtil.java @@ -15,6 +15,11 @@ ******************************************************************************/ package com.exactpro.sf.services.util; +import static com.exactpro.sf.services.ServiceEvent.Level.ERROR; +import static com.exactpro.sf.services.ServiceEvent.Level.INFO; +import static com.exactpro.sf.services.ServiceEvent.Type.convert; +import static com.exactpro.sf.services.ServiceEventFactory.createStatusUpdateEvent; + import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; @@ -49,7 +54,7 @@ import com.exactpro.sf.services.IServiceSettings; import com.exactpro.sf.services.ServiceDescription; import com.exactpro.sf.services.ServiceEvent; -import com.exactpro.sf.services.ServiceEventFactory; +import com.exactpro.sf.services.ServiceEvent.Level; import com.exactpro.sf.services.ServiceStatus; import com.google.common.primitives.Longs; import com.google.common.primitives.UnsignedLong; @@ -75,14 +80,10 @@ private ServiceUtil() { } public static void changeStatus(IService service, IServiceMonitor monitor, ServiceStatus status, String message, Throwable e) { - - ServiceEvent event; - - if (status != ServiceStatus.ERROR) { - event = ServiceEventFactory.createStatusUpdateEvent(service.getServiceName(), ServiceEvent.Level.INFO, ServiceEvent.Type.convert(status), message, "", null); - } else { - event = ServiceEventFactory.createStatusUpdateEvent(service.getServiceName(), ServiceEvent.Level.ERROR, ServiceEvent.Type.convert(status), message, "", e); - } + boolean error = status == ServiceStatus.ERROR; + Level level = error ? ERROR : INFO; + Throwable throwable = error ? e : null; + ServiceEvent event = createStatusUpdateEvent(service.getServiceName(), level, convert(status), message, "", throwable); if (monitor != null) { monitor.onEvent(event); @@ -131,8 +132,9 @@ public static double divide(long dividend, long divider) { } public static byte[] normalisate(byte[] array, int size) { - if (array == null) - throw new EPSCommonException("Array is null"); + if(array == null) { + throw new EPSCommonException("Array is null"); + } if (size < 0) { throw new EPSCommonException("Size cannot be negative"); } @@ -141,7 +143,7 @@ public static byte[] normalisate(byte[] array, int size) { int from = array.length - size; for (int i = from - 1; i > -1; i--) { - if (BYTE_ZERO != array[i]) { + if(array[i] != BYTE_ZERO) { throw new EPSCommonException("Massive compression does not execute without data loss"); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/AbstractStaticTest.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/AbstractStaticTest.java index 9af456dc..efc67557 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/AbstractStaticTest.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/AbstractStaticTest.java @@ -23,6 +23,7 @@ import java.util.Set; import org.apache.commons.configuration.HierarchicalConfiguration; +import org.apache.commons.configuration.HierarchicalConfiguration.Node; import org.apache.commons.lang3.StringUtils; import com.exactpro.sf.center.ISFContext; @@ -34,7 +35,7 @@ public abstract class AbstractStaticTest { protected static ISFContext initContext(List workspaceLayers) throws Exception { HierarchicalConfiguration config = new HierarchicalConfiguration(); - config.setRootNode(new HierarchicalConfiguration.Node("configuration")); + config.setRootNode(new Node("configuration")); config.addProperty("Environment.GeneralSettings.StorageType", "file"); config.addProperty("Environment.GeneralSettings.FileStoragePath", "storage"); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/StaticMatrixTest.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/StaticMatrixTest.java index 0babf1ce..c5edf759 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/StaticMatrixTest.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/statictesting/StaticMatrixTest.java @@ -85,14 +85,14 @@ @RunWith(Parameterized.class) public class StaticMatrixTest extends AbstractStaticTest { - private static ObjectReader VARIABLE_SET_READER = new ObjectMapper(new YAMLFactory()).readerFor(new TypeReference>>() {}); + private static final ObjectReader VARIABLE_SET_READER = new ObjectMapper(new YAMLFactory()).readerFor(new TypeReference>>() {}); private static List testData = Collections.emptyList(); - private ISFContext context; - private File matrix; - private File services; - private boolean skipOptional; + private final ISFContext context; + private final File matrix; + private final File services; + private final boolean skipOptional; public StaticMatrixTest(ISFContext context, File matrix, File services, boolean skipOptional) { this.context = context; @@ -154,7 +154,7 @@ public static void main(String[] args) throws Exception { File matricesPath = (File) commandLine.getParsedOptionValue("matrices"); - Set servicesPaths = Arrays.stream(commandLine.getOptionValues("services")) + Set servicesPaths = stream(commandLine.getOptionValues("services")) .map(File::new) .collect(Collectors.toSet()); @@ -412,7 +412,7 @@ private static List getFiles(File path, Predicate filter) throws IOE .filter(Files::isRegularFile) .map(Path::toFile) .filter(filter) - .collect(Collectors.toList()); + .collect(toList()); } private static void compileMatrix(ISFContext context, File matrix, boolean skipOptional) throws Exception { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/DefaultMatrix.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/DefaultMatrix.java index 5d34fdd4..a02b5c72 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/DefaultMatrix.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/DefaultMatrix.java @@ -67,29 +67,11 @@ public DefaultMatrix(Long id, String name, String description, String creator, S this.id = id; this.name = name; this.date = date; - if (creator != null) { - this.creator = creator; - } else { - this.creator = "Unknown creator"; - } - if (description != null) { - this.description = description; - } else { - this.description = ""; - } - if (link != null) { - this.link = link; - } else { - this.link = ""; - } - + this.creator = creator != null ? creator : "Unknown creator"; + this.description = description != null ? description : ""; + this.link = link != null ? link : ""; this.providerURI = providerURI; - - if (languageURI != null) { - this.languageURI = languageURI; - } else { - this.languageURI = AutoLanguageFactory.URI; - } + this.languageURI = languageURI != null ? languageURI : AutoLanguageFactory.URI; this.filePath = filePath; } @@ -126,7 +108,7 @@ public void setName(String name) { @Override public InputStream readStream(IWorkspaceDispatcher workspaceDispatcher) { try { - File target = workspaceDispatcher.getFile(FolderType.MATRIX, this.filePath); + File target = workspaceDispatcher.getFile(FolderType.MATRIX, filePath); return new FileInputStream(target); } catch (Exception e) { throw new StorageException("Can't open stored matrix", e); @@ -204,7 +186,7 @@ public void setLink(String link) { @JsonIgnore @Override public boolean getReloadEnabled() { - return link != null && !link.equals(""); + return link != null && !"".equals(link); } @Override @@ -219,12 +201,18 @@ public void setProviderURI(SailfishURI providerURI) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(this == o) { + return true; + } + if(o == null || getClass() != o.getClass()) { + return false; + } DefaultMatrix that = (DefaultMatrix) o; - if (!id.equals(that.id)) return false; + if(!id.equals(that.id)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/FileBackedList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/FileBackedList.java index d1475957..cfc17921 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/FileBackedList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/FileBackedList.java @@ -39,7 +39,7 @@ public class FileBackedList extends AbstractList implements RandomAccess { protected final File path; protected final ISerializer serializer; - protected int size = 0; + protected int size; public FileBackedList(File path, ISerializer serializer) { this.path = Objects.requireNonNull(path, "path cannot be null"); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IAuthStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IAuthStorage.java index d0f140b6..255e42dc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IAuthStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IAuthStorage.java @@ -20,18 +20,18 @@ import com.exactpro.sf.storage.auth.User; public interface IAuthStorage { - public static final String ADMIN = "admin"; - public static final String USER = "user"; + String ADMIN = "admin"; + String USER = "user"; - public boolean userExists(String name); - public User getUser(String name); - public void addUser(User user); - public void updateUser(User user); - public void removeUser(String name); - public Set getUsers(); + boolean userExists(String name); + User getUser(String name); + void addUser(User user); + void updateUser(User user); + void removeUser(String name); + Set getUsers(); - public boolean roleExists(String name); - public void addRole(String name); - public void removeRole(String name); - public Set getRoles(); + boolean roleExists(String name); + void addRole(String name); + void removeRole(String name); + Set getRoles(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IMessageStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IMessageStorage.java index e9337be1..4f6e643d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IMessageStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IMessageStorage.java @@ -21,7 +21,7 @@ import com.exactpro.sf.common.messages.IMessage; public interface IMessageStorage extends IDisposable { - public static final int BUFFER_SIZE = 50; + int BUFFER_SIZE = 50; @Deprecated // move to proper class default ScriptRun openScriptRun(String name, String description) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IObjectFlusher.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IObjectFlusher.java index 67c03ff4..927ca199 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IObjectFlusher.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/IObjectFlusher.java @@ -18,12 +18,12 @@ import java.util.List; public interface IObjectFlusher { - public void start(); - public void stop(); - public void add(T object); - public void flush(); + void start(); + void stop(); + void add(T object); + void flush(); - public interface IFlushProvider { - public void flush(List objects) throws Exception; + interface IFlushProvider { + void flush(List objects) throws Exception; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ISerializer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ISerializer.java index 091523ce..fd92fbbb 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ISerializer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ISerializer.java @@ -20,8 +20,8 @@ import java.io.OutputStream; public interface ISerializer { - public T deserialize(File input) throws Exception; - public T deserialize(InputStream input) throws Exception; - public void serialize(T object, File output) throws Exception; - public void serialize(T object, OutputStream output) throws Exception; + T deserialize(File input) throws Exception; + T deserialize(InputStream input) throws Exception; + void serialize(T object, File output) throws Exception; + void serialize(T object, OutputStream output) throws Exception; } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageList.java index 56a8de14..8534b01f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageList.java @@ -62,7 +62,7 @@ public void serialize(FileMessage object, OutputStream output) throws Exception @Override public void serialize(FileMessage object, File output) throws Exception { - this.fileSerializer.serialize(object, output); + fileSerializer.serialize(object, output); output.setLastModified(object.getTimestamp().getTime()); } @@ -73,7 +73,7 @@ public FileMessage deserialize(InputStream input) throws Exception { @Override public FileMessage deserialize(File input) throws Exception { - return new FileMessage(this.fileSerializer, input); + return new FileMessage(fileSerializer, input); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageLoader.java index 898236e4..8ff32aae 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/MessageLoader.java @@ -21,9 +21,9 @@ import java.util.Iterator; public class MessageLoader implements Iterator { - private ScrollableResults results; - private Session session; - private int numberOfRecords; + private final ScrollableResults results; + private final Session session; + private final int numberOfRecords; public MessageLoader(ScrollableResults results, Session session) { this.results = results; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ServiceEventList.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ServiceEventList.java index 94d8d585..76724fcb 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ServiceEventList.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/ServiceEventList.java @@ -62,7 +62,7 @@ public void serialize(FileServiceEvent object, OutputStream output) throws Excep @Override public void serialize(FileServiceEvent object, File output) throws Exception { - this.fileSerializer.serialize(object, output); + fileSerializer.serialize(object, output); output.setLastModified(object.getOccurred().getTime()); } @@ -73,7 +73,7 @@ public FileServiceEvent deserialize(InputStream input) throws Exception { @Override public FileServiceEvent deserialize(File input) throws Exception { - return new FileServiceEvent(this.fileSerializer, input); + return new FileServiceEvent(fileSerializer, input); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/StorageFilter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/StorageFilter.java index c5873947..7e72fdcc 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/StorageFilter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/StorageFilter.java @@ -31,7 +31,7 @@ public StorageFilter() public void addCriterion(FilterCriterion criterion) { - this.criteria.add(criterion); + criteria.add(criterion); } public List getCriteria() { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToLong.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToLong.java index 57a976a8..bb386af8 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToLong.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToLong.java @@ -20,6 +20,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; +import java.sql.Types; import java.util.Date; import org.hibernate.HibernateException; @@ -41,7 +42,9 @@ public Object assemble(Serializable cached, Object obj) throws HibernateExceptio @Override public Object deepCopy(Object obj) throws HibernateException { - if (obj == null) return null; + if(obj == null) { + return null; + } Date orig = (Date) obj; return new Timestamp(orig.getTime()); } @@ -75,12 +78,8 @@ public Object nullSafeGet(ResultSet ps, String[] names, SessionImplementor s, Ob @Override public void nullSafeSet(PreparedStatement ps, Object value, int index, SessionImplementor s) - throws HibernateException, SQLException { - if (value == null) - LongType.INSTANCE.set(ps, 0L, index, s); - else - LongType.INSTANCE.set(ps, ((Date) value).getTime(), index, s); - + throws HibernateException, SQLException { + LongType.INSTANCE.set(ps, value == null ? 0L : ((Date)value).getTime(), index, s); } @Override @@ -95,7 +94,7 @@ public Class returnedClass() { @Override public int[] sqlTypes() { - return new int[] { java.sql.Types.BIGINT }; + return new int[] { Types.BIGINT }; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToString.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToString.java index df47e85a..a1f4c9da 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToString.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TimestampToString.java @@ -20,7 +20,9 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; +import java.sql.Types; import java.text.ParseException; +import java.time.Instant; import java.util.Date; import org.hibernate.HibernateException; @@ -29,7 +31,6 @@ import org.hibernate.usertype.UserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; public class TimestampToString implements UserType, Serializable{ @@ -47,7 +48,9 @@ public Object assemble(Serializable cached, Object obj) throws HibernateExceptio @Override public Object deepCopy(Object obj) throws HibernateException { - if (obj == null) return null; + if(obj == null) { + return null; + } Date orig = (Date) obj; return new Timestamp(orig.getTime()); } @@ -82,20 +85,13 @@ public Object nullSafeGet(ResultSet ps, String[] names, SessionImplementor s, Ob } catch (ParseException e) { logger.error(e.getMessage(), e); } - if (time != null) - return new Timestamp(time.getTime()); - else - return null; + return time != null ? new Timestamp(time.getTime()) : null; } @Override public void nullSafeSet(PreparedStatement ps, Object value, int index, SessionImplementor s) throws HibernateException, SQLException { - if (value == null) - StringType.INSTANCE.set(ps, "", index, s); - else - StringType.INSTANCE.set(ps, dateToString((Date)value), index, s); - + StringType.INSTANCE.set(ps, value == null ? "" : dateToString((Date)value), index, s); } public static String dateToString(Date value) { @@ -118,7 +114,7 @@ public Class returnedClass() { @Override public int[] sqlTypes() { - return new int[] { java.sql.Types.VARCHAR }; + return new int[] { Types.VARCHAR }; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TruncatedString.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TruncatedString.java index e66f616b..5255f33c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TruncatedString.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/TruncatedString.java @@ -19,6 +19,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Types; import java.util.Properties; import org.hibernate.HibernateException; @@ -49,7 +50,7 @@ public void setParameterValues(Properties parameters) { @Override public int[] sqlTypes() { - return new int[] { java.sql.Types.VARCHAR }; + return new int[] { Types.VARCHAR }; } @Override @@ -60,7 +61,7 @@ public Class returnedClass() { @Override public boolean equals(Object x, Object y) throws HibernateException { - return (x == y) || (x != null && y != null && (x.equals(y))); + return (x == y) || (x != null && y != null && x.equals(y)); } @Override @@ -76,7 +77,7 @@ public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessi @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { String val = (String) value; - if (val != null && val.length() > this.maxLength) { + if(val != null && val.length() > maxLength) { val = val.substring(0, maxLength); } st.setString(index, val); @@ -84,10 +85,7 @@ public void nullSafeSet(PreparedStatement st, Object value, int index, SessionIm @Override public Object deepCopy(Object value) throws HibernateException { - if (value == null) { - return null; - } - return new String(((String) value)); + return value; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/PasswordHasher.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/PasswordHasher.java index a1d547d9..f9df8d85 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/PasswordHasher.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/PasswordHasher.java @@ -16,6 +16,7 @@ package com.exactpro.sf.storage.auth; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -37,26 +38,22 @@ public static String getHash(String toHash) { try { messageDigest = MessageDigest.getInstance("MD5"); - messageDigest.update((toHash + SALT).getBytes("UTF-8")); + messageDigest.update((toHash + SALT).getBytes(StandardCharsets.UTF_8)); } catch (NoSuchAlgorithmException e) { logger.error("Could not get hash!", e); return null; - } catch (UnsupportedEncodingException e) { - - logger.error("Could not get hash!", e); - return null; } - return encodeHex(messageDigest.digest()); + return encodeHex(messageDigest.digest()); } - protected static String encodeHex(final byte[] data) { + protected static String encodeHex(byte[] data) { - final int l = data.length; - final char[] out = new char[l << 1]; + int l = data.length; + char[] out = new char[l << 1]; // two characters form the hex value. diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/User.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/User.java index 0425cf54..af21aac7 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/User.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/auth/User.java @@ -29,7 +29,7 @@ public class User { private String email; private Date registered; private Set roles = new HashSet<>(); - private boolean guest = false; + private boolean guest; public String getName() { return name; @@ -80,7 +80,7 @@ public void setRegistered(Date registered) { } public Set getRoles() { - return this.roles; + return roles; } public void setRoles(Set roles) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/AppUser.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/AppUser.java index d236891e..1c008c3d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/AppUser.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/AppUser.java @@ -41,7 +41,7 @@ public class AppUser implements Serializable { private Set roles = new HashSet(); @Transient - private boolean transientUser = false; + private boolean transientUser; public AppUser() { } @@ -124,7 +124,7 @@ public void setUserName(String userName) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((userName == null) ? 0 : userName.hashCode()); return result; @@ -132,13 +132,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } AppUser other = (AppUser) obj; if (userName == null) { - if (other.userName != null) return false; - } else if (!userName.equals(other.userName)) return false; + if(other.userName != null) { + return false; + } + } else if(!userName.equals(other.userName)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/Role.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/Role.java index 985007b7..046b799e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/Role.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/Role.java @@ -44,7 +44,7 @@ public void setUsers(Set users) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((roleName == null) ? 0 : roleName.hashCode()); return result; @@ -52,13 +52,23 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } Role other = (Role) obj; if (roleName == null) { - if (other.roleName != null) return false; - } else if (!roleName.equals(other.roleName)) return false; + if(other.roleName != null) { + return false; + } + } else if(!roleName.equals(other.roleName)) { + return false; + } return true; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredEnvironment.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredEnvironment.java index df26617d..afad453d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredEnvironment.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredEnvironment.java @@ -61,7 +61,7 @@ public void setServices(Set services) { @Override public int hashCode() { - final int prime = 31; + int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; @@ -69,20 +69,30 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } StoredEnvironment other = (StoredEnvironment) obj; if (id == null) { - if (other.id != null) return false; - } else if (!id.equals(other.id)) return false; + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } return true; } @Override public StoredEnvironment clone() { StoredEnvironment env = new StoredEnvironment(); - env.setName(this.name); + env.setName(name); env.setVariableSet(variableSet); return env; } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMatrix.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMatrix.java index 877999f3..cbcaf27f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMatrix.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMatrix.java @@ -55,7 +55,7 @@ public class StoredMatrix { private List scriptRuns; - private SimpleDateFormat dateFormat; + private final SimpleDateFormat dateFormat; private String link; @@ -111,7 +111,7 @@ public void setName(String name) { public InputStream readStream(IWorkspaceDispatcher workspaceDispatcher) { try { - File target = workspaceDispatcher.getFile(FolderType.MATRIX, this.filePath); + File target = workspaceDispatcher.getFile(FolderType.MATRIX, filePath); return new FileInputStream(target); } catch (Exception e) { throw new StorageException("Can't open stored matrix", e); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMessage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMessage.java index 32699234..d0f290b1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMessage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredMessage.java @@ -18,10 +18,11 @@ import java.sql.Timestamp; import java.util.Set; +import org.apache.commons.lang3.builder.ToStringBuilder; + import com.exactpro.sf.storage.IMeasurable; import com.exactpro.sf.storage.util.StorageMeasureUtils; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.apache.commons.lang3.builder.ToStringBuilder; public class StoredMessage implements IMeasurable { @@ -59,10 +60,7 @@ public void setSubMessage(boolean subMessage) { this.subMessage = subMessage; } - public StoredMessage() { - } - - public String getFrom() { + public String getFrom() { return from; } @@ -167,7 +165,7 @@ public String toString() { } public String getServiceId() { - return this.serviceId; + return serviceId; } public void setServiceId(String serviceId) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredService.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredService.java index 5d3be661..dcd89e39 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredService.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/entities/StoredService.java @@ -89,7 +89,7 @@ public String toString() { append("handler", serviceHandlerClassName). append("settings", parameters). append("variables", variables). - append("environment", (null != environment) ? environment.getName() : ""). + append("environment", (environment != null) ? environment.getName() : ""). toString(); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractMessageStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractMessageStorage.java index 6ae2cde8..a1b096fa 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractMessageStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractMessageStorage.java @@ -53,11 +53,11 @@ public void storeMessage(IMessage message) { SailfishURI dictionaryURI = message.getMetaData().getDictionaryURI(); if (dictionaryURI != null) { - dictionary = this.dictionaryManager.getDictionary(dictionaryURI); + dictionary = dictionaryManager.getDictionary(dictionaryURI); if (dictionary != null) { messageStructure = dictionary.getMessages().get(message.getName()); } - messageFactory = this.dictionaryManager.getMessageFactory(dictionaryURI); + messageFactory = dictionaryManager.getMessageFactory(dictionaryURI); } IHumanMessage humanMessage = MessageUtil.convertToIHumanMessage(messageFactory, messageStructure, message); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractPersistentObject.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractPersistentObject.java index 95bb0cb1..6ea3a7d2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractPersistentObject.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/AbstractPersistentObject.java @@ -39,8 +39,9 @@ public void setVersion(Integer version) { @Override public boolean equals(Object o) { - if (this == o) - return true; + if(this == o) { + return true; + } if (o == null || !(o instanceof PersistentObject)) { return false; @@ -48,25 +49,17 @@ public boolean equals(Object o) { PersistentObject other = (PersistentObject) o; - // if the id is missing, return false - if (id == null) - return false; - - // equivalence by id - return id.equals(other.getId()); - } + return id != null && id.equals(other.getId()); + } @Override public int hashCode() { - if (id != null) { - return id.hashCode(); - } - return super.hashCode(); - } + return id != null ? id.hashCode() : super.hashCode(); + } @Override public String toString() { - return this.getClass().getName() + "[id=" + id + "]"; + return getClass().getName() + "[id=" + id + "]"; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseAuthStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseAuthStorage.java index 827f2c7c..b045ceb4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseAuthStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseAuthStorage.java @@ -42,12 +42,7 @@ public boolean userExists(String name) { @Override public User getUser(String name) { AppUser appUser = storage.getEntityByField(AppUser.class, "userName", name); - - if(appUser == null) { - return null; - } - - return convertAppUser(appUser); + return appUser == null ? null : convertAppUser(appUser); } private User convertAppUser(AppUser appUser) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMatrixStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMatrixStorage.java index 2bd7bd70..8b1729cf 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMatrixStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMatrixStorage.java @@ -21,18 +21,12 @@ import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.Date; -import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; -import com.exactpro.sf.aml.Hash; -import com.exactpro.sf.aml.iomatrix.MatrixFileTypes; -import com.exactpro.sf.configuration.workspace.FolderType; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -41,8 +35,10 @@ import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; +import com.exactpro.sf.aml.iomatrix.MatrixFileTypes; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.configuration.suri.SailfishURIException; +import com.exactpro.sf.configuration.workspace.FolderType; import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; import com.exactpro.sf.storage.DefaultMatrix; import com.exactpro.sf.storage.IMatrix; @@ -216,14 +212,8 @@ public IMatrix getMatrixById(long matrixId) { } } - IMatrix result = null; - - if ( !list.isEmpty() ) { - result = convertFromStoredMatrix(list.get(0)); - } - - return result; - } + return !list.isEmpty() ? convertFromStoredMatrix(list.get(0)) : null; + } @Override protected void updateReloadedMatrix(IMatrix matrix) { @@ -297,7 +287,9 @@ public List getMatrixList() { return (fileType == MatrixFileTypes.CSV) || (fileType == MatrixFileTypes.XLS) || (fileType == MatrixFileTypes.XLSX); }).collect(Collectors.toSet()); - list.forEach(storedMatrix -> matrices.remove(storedMatrix.getFilePath())); + for(StoredMatrix storedMatrix : list) { + matrices.remove(storedMatrix.getFilePath()); + } Transaction tx = null; @@ -351,18 +343,8 @@ public List getMatrixList() { } private StoredMatrix convertToStoredMatrix(IMatrix matrix, Session session) { - - StoredMatrix storedMatrix = null; - - if (matrix.getId() == null) { - storedMatrix = new StoredMatrix(); - } else { - storedMatrix = (StoredMatrix) session.load(StoredMatrix.class, matrix.getId()); - } - - return storedMatrix; - - } + return matrix.getId() == null ? new StoredMatrix() : (StoredMatrix)session.load(StoredMatrix.class, matrix.getId()); + } private IMatrix convertFromStoredMatrix(StoredMatrix storedMatrix) { try { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMessageStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMessageStorage.java index 66885e71..8194e1b3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMessageStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseMessageStorage.java @@ -17,6 +17,7 @@ import java.io.FileNotFoundException; import java.sql.Timestamp; +import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; @@ -24,7 +25,6 @@ import java.util.Queue; import java.util.Set; -import com.exactpro.sf.storage.DBStorageSettings; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ObjectUtils; import org.hibernate.Criteria; @@ -35,7 +35,6 @@ import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; -import java.time.Instant; import com.exactpro.sf.common.messages.IHumanMessage; import com.exactpro.sf.common.messages.IMessage; @@ -43,9 +42,8 @@ import com.exactpro.sf.common.messages.MsgMetaData; import com.exactpro.sf.common.services.ServiceInfo; import com.exactpro.sf.common.util.HexDumper; -import com.exactpro.sf.configuration.DictionaryManager; -import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; import com.exactpro.sf.configuration.workspace.WorkspaceStructureException; +import com.exactpro.sf.storage.DBStorageSettings; import com.exactpro.sf.storage.IObjectFlusher; import com.exactpro.sf.storage.MessageFilter; import com.exactpro.sf.storage.MessageRow; @@ -58,7 +56,7 @@ import com.exactpro.sf.util.Interner; public class DatabaseMessageStorage extends AbstractMessageStorage { - private final static int REMOVE_BATCH_SIZE = 5000; + private static final int REMOVE_BATCH_SIZE = 5000; private final SessionFactory sessionFactory; private final Interner interner; @@ -75,10 +73,10 @@ public DatabaseMessageStorage(DBStorageSettings dbStorageSettings) throws Worksp * We must create this run to make sure that messagestorage could store * messages during Service initialisation phase */ - this.openScriptRun("Initialisation", "Initialisation of services"); + openScriptRun("Initialisation", "Initialisation of services"); - this.flusher = new ObjectFlusher(new HibernateFlushProvider(this.sessionFactory), BUFFER_SIZE, dbStorageSettings.getEnvironmentSettings().getMaxStorageQueueSize()); - this.flusher.start(); + this.flusher = new ObjectFlusher(new HibernateFlushProvider(sessionFactory), BUFFER_SIZE, dbStorageSettings.getEnvironmentSettings().getMaxStorageQueueSize()); + flusher.start(); } @@ -126,21 +124,23 @@ public synchronized ScriptRun openScriptRun(String name, String description) { try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); session.save(storedScriptRun); tx.commit(); } catch (RuntimeException e) { - if (tx != null) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } logger.error("Could not create script run", e); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } scriptRun.setId(storedScriptRun.getId()); @@ -156,7 +156,7 @@ public void closeScriptRun(ScriptRun scriptRun) { try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); StoredScriptRun storedScriptRun = new StoredScriptRun(); @@ -174,22 +174,24 @@ public void closeScriptRun(ScriptRun scriptRun) { } catch (RuntimeException e) { - if (tx != null) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } logger.error("Could not close script run", e); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @Override public void dispose() { - this.flusher.stop(); + flusher.stop(); - this.sessionFactory.close(); + sessionFactory.close(); } // FIXME: it does not work properly in case of multiple scripts running(it @@ -213,12 +215,13 @@ public List getMessages(int offset, int count, String where) { return new ArrayList<>(); } - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); String strQuery = "from StoredMessage msg "; - if (!where.isEmpty()) - strQuery += " where " + where; + if(!where.isEmpty()) { + strQuery += " where " + where; + } strQuery += " order by msg.id desc, msg.arrived desc "; Query query = session.createQuery(strQuery); @@ -227,8 +230,9 @@ public List getMessages(int offset, int count, String where) { query.setFirstResult(offset); - if (count != -1) - query.setMaxResults(count); + if(count != -1) { + query.setMaxResults(count); + } List result = new ArrayList<>(); @@ -268,7 +272,7 @@ public static MessageRow convert(StoredMessage message, Interner interne row.setJson(interner.intern(message.getJsonMessage())); row.setContent(interner.intern(message.getHumanMessage())); row.setMetaDataID(interner.intern(String.valueOf(message.getStoredId()))); - row.setRejectReason(interner.intern((message.getRejectReason()))); + row.setRejectReason(interner.intern(message.getRejectReason())); if(message.getRawMessage() != null) { if(hex) { @@ -287,16 +291,19 @@ public static MessageRow convert(StoredMessage message, Interner interne @Override public void removeMessages(Instant olderThan) { + //noinspection ControlFlowStatementWithoutBraces while(removeMessages(olderThan, null, REMOVE_BATCH_SIZE)); } @Override public void removeMessages(String serviceID) { + //noinspection ControlFlowStatementWithoutBraces while(removeMessages(null, serviceID, REMOVE_BATCH_SIZE)); } @Override public void clear() { + //noinspection ControlFlowStatementWithoutBraces while(removeMessages(null, null, REMOVE_BATCH_SIZE)); } @@ -332,6 +339,7 @@ private boolean removeMessages(Instant olderThan, String serviceID, int limit) { successful = query.executeUpdate() > 0; tx.commit(); + return successful; } catch(HibernateException e) { if(tx != null) { tx.rollback(); @@ -344,7 +352,6 @@ private boolean removeMessages(Instant olderThan, String serviceID, int limit) { } } - return successful; } private long getFirstMessageID(Session session, String serviceID) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseOptionsStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseOptionsStorage.java index 5415d7da..ab2b8619 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseOptionsStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseOptionsStorage.java @@ -24,8 +24,8 @@ import com.exactpro.sf.storage.entities.StoredOption; public class DatabaseOptionsStorage implements IOptionsStorage { - - private IStorage hbStorage; + + private final IStorage hbStorage; public DatabaseOptionsStorage(IStorage hbStorage) { @@ -35,40 +35,33 @@ public DatabaseOptionsStorage(IStorage hbStorage) { @Override public void setOption(String key, String value) { - - StoredOption stored = this.hbStorage.getEntityByField(StoredOption.class, "optionName", key); + + StoredOption stored = hbStorage.getEntityByField(StoredOption.class, "optionName", key); if(stored == null) { stored = new StoredOption(key, value); - this.hbStorage.add(stored); + hbStorage.add(stored); } else { stored.setOptionValue(value); - this.hbStorage.update(stored); + hbStorage.update(stored); } } @Override - public String getOption(String key) { - - StoredOption stored = this.hbStorage.getEntityByField(StoredOption.class, "optionName", key); - - if(stored != null) { - return stored.getOptionValue(); - } - - return null; - - } + public String getOption(String key) { + StoredOption stored = hbStorage.getEntityByField(StoredOption.class, "optionName", key); + return stored != null ? stored.getOptionValue() : null; + } @Override public Map getAllOptions() { - - return optionsToMap(this.hbStorage.getAllEntities(StoredOption.class)); + + return optionsToMap(hbStorage.getAllEntities(StoredOption.class)); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseServiceStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseServiceStorage.java index 231aa919..d37ea247 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseServiceStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DatabaseServiceStorage.java @@ -50,6 +50,8 @@ import com.exactpro.sf.services.IServiceSettings; import com.exactpro.sf.services.ServiceDescription; import com.exactpro.sf.services.ServiceEvent; +import com.exactpro.sf.services.ServiceEvent.Level; +import com.exactpro.sf.services.ServiceEvent.Type; import com.exactpro.sf.storage.FilterCriterion; import com.exactpro.sf.storage.FilterCriterion.Operation; import com.exactpro.sf.storage.IMessageStorage; @@ -78,11 +80,11 @@ public class DatabaseServiceStorage implements IServiceStorage { private final IDictionaryManager dictionaryManager; - private ConvertUtilsBean converter = new ConvertUtilsBean(); + private final ConvertUtilsBean converter = new ConvertUtilsBean(); - private IObjectFlusher flusher; + private final IObjectFlusher flusher; - private IMessageStorage messageStorage; + private final IMessageStorage messageStorage; /** * Operations with this collections should be synchronized @@ -95,7 +97,7 @@ public class DatabaseServiceStorage implements IServiceStorage { * @param cfgFolderPath * @param factory */ - public DatabaseServiceStorage(final SessionFactory sessionFactory, final IStaticServiceManager staticServiceManager, final IDictionaryManager dictionaryManager, final IMessageStorage messageStorage) { + public DatabaseServiceStorage(SessionFactory sessionFactory, IStaticServiceManager staticServiceManager, IDictionaryManager dictionaryManager, IMessageStorage messageStorage) { this.sessionFactory = Objects.requireNonNull(sessionFactory, "sessionFactory cannot be null"); this.staticServiceManager = Objects.requireNonNull(staticServiceManager, "staticServiceManager cannot be null"); @@ -103,7 +105,7 @@ public DatabaseServiceStorage(final SessionFactory sessionFactory, final IStatic this.messageStorage = Objects.requireNonNull(messageStorage, "messageStorage cannot be null"); this.flusher = new ObjectFlusher<>(new HibernateFlushProvider(this.sessionFactory), BUFFER_SIZE); - this.flusher.start(); + flusher.start(); loadServiceDescriptions(); } @@ -111,10 +113,9 @@ public DatabaseServiceStorage(final SessionFactory sessionFactory, final IStatic @Override public ServiceInfo lookupService(ServiceName serviceName) { Session session = null; - ServiceInfo result = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(StoredService.class); criteria.add(Restrictions.eq("name", serviceName.getServiceName())); @@ -131,18 +132,16 @@ public ServiceInfo lookupService(ServiceName serviceName) { storedService = (StoredService) criteria.uniqueResult(); } - if(storedService != null) { - result = new ServiceInfo(storedService.getId(), serviceName); - } + return storedService != null ? new ServiceInfo(storedService.getId(), serviceName) : null; } catch (RuntimeException e) { logger.error("Could not retrieve a service for name: {}", serviceName, e); throw new StorageException("Could not retrieve a service for name: " + serviceName, e); } finally { - if (session != null) + if(session != null) { session.close(); + } } - return result; } @Override @@ -154,7 +153,7 @@ public synchronized void addServiceDescription(ServiceDescription description) { Transaction tx = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); session.setFlushMode(FlushMode.COMMIT); // do not delete this line // cause default mode is not declared and equal FlushMode.AUTO @@ -168,24 +167,27 @@ public synchronized void addServiceDescription(ServiceDescription description) { } catch (ConstraintViolationException e) { - if ( tx != null ) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } String message = "Service with name " + description.getEnvironment() + ":" + description.getName() + " already exists"; logger.error(message, e); throw new StorageException(message, e); } catch ( RuntimeException e ){ - if ( tx != null ) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } String message = "Could not store a service description " + description.getEnvironment() + ":" + description.getName(); logger.error(message, e); throw new StorageException(message, e); } finally{ - if ( session != null ) - session.close(); + if(session != null) { + session.close(); + } } } @@ -200,7 +202,7 @@ public void removeServiceDescription(ServiceDescription description) { try { synchronized (description) { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); session.setFlushMode(FlushMode.COMMIT); // do not delete this line // cause default mode is not declared and equal FlushMode.AUTO @@ -220,8 +222,9 @@ public void removeServiceDescription(ServiceDescription description) { } catch ( RuntimeException e ) { - if ( tx != null ) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } String message = "Could not delete a service description " + description.getEnvironment() + ":" + description.getName(); logger.error(message, e); @@ -251,7 +254,7 @@ public void updateServiceDescription(ServiceDescription description) { try { synchronized (descriptionMap) { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); session.update(stored); tx.commit(); @@ -261,8 +264,9 @@ public void updateServiceDescription(ServiceDescription description) { } catch (ConstraintViolationException e) { - if ( tx != null ) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } String message = "Service with name " + description.getEnvironment() + ":" + description.getName() + " already exists"; logger.error(message, e); @@ -270,16 +274,18 @@ public void updateServiceDescription(ServiceDescription description) { } catch ( RuntimeException e ) { - if ( tx != null ) - tx.rollback(); + if(tx != null) { + tx.rollback(); + } String message = "Could not update service description " + description.getEnvironment() + ":" + description.getName(); logger.error(message, e); throw new StorageException(message, e); } finally { - if ( session != null ) - session.close(); + if(session != null) { + session.close(); + } } } @@ -301,10 +307,9 @@ public void addServiceEvent(ServiceDescription description, ServiceEvent event) public long getEventsCount(ServiceDescription description, StorageFilter filter) { flusher.flush(); Session session = null; - long result = 0; - try { - session = this.sessionFactory.openSession(); + try { + session = sessionFactory.openSession(); StoredService storedDescription = null; @@ -312,28 +317,29 @@ public long getEventsCount(ServiceDescription description, StorageFilter filter) storedDescription = getStoredService(description); } - if ( storedDescription == null ) - throw new StorageException("Could not find stored description for [" + description.getName() + "] service"); + if(storedDescription == null) { + throw new StorageException("Could not find stored description for [" + description.getName() + "] service"); + } - filter.addCriterion(new FilterCriterion("serviceId", storedDescription.getId(), FilterCriterion.Operation.EQUALS)); + filter.addCriterion(new FilterCriterion("serviceId", storedDescription.getId(), Operation.EQUALS)); String countQueryStr = "select count(msg) from StoredServiceEvent msg where "; Query countQuery = convertFilterToQuery(session, StoredServiceEvent.class, countQueryStr, filter, null); - result = (Long)countQuery.uniqueResult(); + return (Long)countQuery.uniqueResult(); } catch (RuntimeException e) { String message = "Could not retrive events count for service " + description.getEnvironment() + ":" + description.getName(); logger.error(message, e); throw new StorageException(message, e); } finally { - if ( session != null ) - session.close(); + if(session != null) { + session.close(); + } } - return result; - } + } @SuppressWarnings("unchecked") @Override @@ -341,16 +347,16 @@ public StorageResult getServiceEvents(ServiceDescription descripti flusher.flush(); Session session = null; - StorageResult totalResult = null; - - try { - session = this.sessionFactory.openSession(); + try { + session = sessionFactory.openSession(); - if(sorting == null) - sorting = new ArrayList<>(); + if(sorting == null) { + sorting = new ArrayList<>(); + } - if(sorting.size() == 0) - sorting.add(new SortCriterion("occured", false)); + if(sorting.isEmpty()) { + sorting.add(new SortCriterion("occured", false)); + } String strQuery = "from StoredServiceEvent msg where "; @@ -360,10 +366,11 @@ public StorageResult getServiceEvents(ServiceDescription descripti storedDescription = getStoredService(description); } - if ( storedDescription == null ) - throw new StorageException("Could not find stored description for [" + description.getName() + "] service"); + if(storedDescription == null) { + throw new StorageException("Could not find stored description for [" + description.getName() + "] service"); + } - filter.addCriterion(new FilterCriterion("serviceId", storedDescription.getId(), FilterCriterion.Operation.EQUALS)); + filter.addCriterion(new FilterCriterion("serviceId", storedDescription.getId(), Operation.EQUALS)); String countQueryStr = "select count(msg) from StoredServiceEvent msg where "; @@ -387,20 +394,19 @@ public StorageResult getServiceEvents(ServiceDescription descripti result.add(serviceEvent); } - totalResult = new StorageResult<>(result, recordCount); + return new StorageResult<>(result, recordCount); } catch (RuntimeException e) { String message = "Could not retrive service events for " + description.getEnvironment() + ":" + description.getName(); logger.error(message, e); throw new StorageException(message, e); } finally { - if ( session != null ) - session.close(); - } - - return totalResult; + if(session != null) { + session.close(); + } + } - } + } @Override public void removeServiceEvents(ServiceDescription description) { @@ -414,16 +420,19 @@ public void removeServiceEvents(ServiceDescription description) { throw new StorageException("Could not find stored description for [" + description.getName() + "] service"); } + //noinspection ControlFlowStatementWithoutBraces while(removeServiceEvents(null, storedDescription.getId(), REMOVE_BATCH_SIZE)); } @Override public void removeServiceEvents(Instant olderThan) { + //noinspection ControlFlowStatementWithoutBraces while(removeServiceEvents(olderThan, null, REMOVE_BATCH_SIZE)); } @Override public void clearServiceEvents() { + //noinspection ControlFlowStatementWithoutBraces while(removeServiceEvents(null, null, REMOVE_BATCH_SIZE)); } @@ -459,7 +468,8 @@ private boolean removeServiceEvents(Instant olderThan, String serviceID, int lim successful = query.executeUpdate() > 0; tx.commit(); - } catch (HibernateException e) { + return successful; + } catch(HibernateException e) { if (tx != null) { tx.rollback(); } @@ -471,8 +481,7 @@ private boolean removeServiceEvents(Instant olderThan, String serviceID, int lim } } - return successful; - } + } private long getFirstServiceEventID(Session session, String serviceID) { String hql = "select event.id from StoredServiceEvent event"; @@ -492,7 +501,7 @@ private long getFirstServiceEventID(Session session, String serviceID) { @Override public void dispose() { - this.flusher.stop(); + flusher.stop(); if(sessionFactory != null) { sessionFactory.close(); } @@ -511,7 +520,7 @@ private StoredService convertServiceDescription(ServiceDescription description) try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(StoredEnvironment.class); criteria.add(Restrictions.eq("name", description.getEnvironment())); @@ -524,8 +533,9 @@ private StoredService convertServiceDescription(ServiceDescription description) stored.setEnvironment(se); } finally{ - if ( session != null ) - session.close(); + if(session != null) { + session.close(); + } } } } @@ -540,15 +550,14 @@ private StoredService convertServiceDescription(ServiceDescription description) return stored; } - - private ServiceDescription convertStoredServiceDescription(final StoredService storedDescription) throws SailfishURIException { + private ServiceDescription convertStoredServiceDescription(StoredService storedDescription) throws SailfishURIException { ServiceDescription description = null; synchronized (descriptionMap) { String environment = storedDescription.getEnvironment() == null ? null : storedDescription.getEnvironment().getName(); ServiceName serviceName = new ServiceName(environment, storedDescription.getName()); - description = this.descriptionMap.get(serviceName); + description = descriptionMap.get(serviceName); if ( description == null ) { SailfishURI serviceURI = SailfishURI.parse(storedDescription.getType()); @@ -556,14 +565,15 @@ private ServiceDescription convertStoredServiceDescription(final StoredService s IServiceSettings serviceSettings = staticServiceManager.createServiceSettings(serviceURI); description.setSettings(serviceSettings); - this.descriptionMap.put(serviceName, description); + descriptionMap.put(serviceName, description); } } description.setName(storedDescription.getName()); - if (null != storedDescription.getEnvironment()) - description.setEnvironment(storedDescription.getEnvironment().getName()); + if(storedDescription.getEnvironment() != null) { + description.setEnvironment(storedDescription.getEnvironment().getName()); + } description.setServiceHandlerClassName(storedDescription.getServiceHandlerClassName()); description.setVariables(new HashMap<>(storedDescription.getVariables())); @@ -581,8 +591,9 @@ private StoredServiceEvent convertServiceEvent(ServiceDescription descr, Service stored = getStoredService(descr); } - if ( stored == null ) - throw new EPSCommonException("Could not find stored description for ServiceDescription [" + descr + "]"); + if(stored == null) { + throw new EPSCommonException("Could not find stored description for ServiceDescription [" + descr + "]"); + } StoredServiceEvent stEvent = new StoredServiceEvent(); @@ -607,16 +618,18 @@ private Query convertFilterToQuery(Session session, Class beanClass, String q Map> beanMap = new HashMap<>(); StringBuilder queryBld = new StringBuilder(queryStr); - for ( PropertyDescriptor descr : properties ) - beanMap.put(descr.getName(), descr.getPropertyType()); + for(PropertyDescriptor descr : properties) { + beanMap.put(descr.getName(), descr.getPropertyType()); + } List params = new ArrayList<>(list.size()); for ( int i = 0; i < list.size(); ++i ) { FilterCriterion crit = list.get(i); - if ( i != 0 ) + if(i != 0) { queryBld.append(" and "); + } queryBld.append("msg.").append(crit.getName()).append(" ").append(convertOp(crit.getOper())).append(" :param").append(i).append(" "); @@ -627,23 +640,20 @@ private Query convertFilterToQuery(Session session, Class beanClass, String q } } - if ( sorting != null && sorting.size() != 0 ) { + if(sorting != null && !sorting.isEmpty()) { queryBld.append(" order by "); for ( int i = 0; i < sorting.size(); ++i ) { - if ( i != 0 && i != (sorting.size() - 1) ) + if(i != 0 && i != (sorting.size() - 1)) { queryBld.append(" , "); + } SortCriterion entry = sorting.get(i); queryBld.append("msg." + entry.getName()); - - if ( entry.isSortAscending() ) - queryBld.append(" asc "); - else - queryBld.append(" desc "); + queryBld.append(entry.isSortAscending() ? " asc " : " desc "); } } @@ -659,8 +669,7 @@ private Query convertFilterToQuery(Session session, Class beanClass, String q return query; } - - private String convertOp(FilterCriterion.Operation op) { + private String convertOp(Operation op) { switch (op) { case EQUALS: @@ -690,7 +699,7 @@ private ServiceEvent convertStoredServiceEvent(StoredServiceEvent storedServiceE //FIXME //Need to change mapping to return StoredService - ServiceEvent serviceEvent = new ServiceEvent(null, ServiceEvent.Level.valueOf(level), ServiceEvent.Type.valueOf(type), date, message, details); + ServiceEvent serviceEvent = new ServiceEvent(null, Level.valueOf(level), Type.valueOf(type), date, message, details); return serviceEvent; } @@ -701,7 +710,7 @@ private StoredService getStoredService(ServiceDescription description) { try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); String strQuery = "select service from StoredService service left join service.environment as environment where service.name = :serviceName"; @@ -732,8 +741,9 @@ private StoredService getStoredService(ServiceDescription description) { throw new StorageException("Could not retrieve StoredService", e); } finally { - if ( session != null ) - session.close(); + if(session != null) { + session.close(); + } } } @@ -743,7 +753,7 @@ private void loadServiceDescriptions() { try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); String strQuery = "from StoredService"; @@ -763,8 +773,9 @@ private void loadServiceDescriptions() { throw new StorageException("Could not retrieve service descriptions", e); } finally { - if ( session != null ) - session.close(); + if(session != null) { + session.close(); + } } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DefaultTestScriptStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DefaultTestScriptStorage.java index ed24e2b0..accc4060 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DefaultTestScriptStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/DefaultTestScriptStorage.java @@ -15,17 +15,25 @@ ******************************************************************************/ package com.exactpro.sf.storage.impl; -import java.io.*; -import java.util.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportProperties; -import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportRoot; -import com.exactpro.sf.storage.entities.XmlReportProperties; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -41,21 +49,25 @@ import com.exactpro.sf.scriptrunner.IScriptRunListener; import com.exactpro.sf.scriptrunner.ScriptContext; import com.exactpro.sf.scriptrunner.ScriptProgress; +import com.exactpro.sf.scriptrunner.ScriptProgress.IScriptRunProgressListener; import com.exactpro.sf.scriptrunner.TestScriptDescription; +import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptState; +import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptStatus; import com.exactpro.sf.scriptrunner.ZipReport; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportProperties; +import com.exactpro.sf.scriptrunner.impl.jsonreport.beans.ReportRoot; import com.exactpro.sf.storage.ITestScriptStorage; +import com.exactpro.sf.storage.entities.XmlReportProperties; import com.exactpro.sf.util.DirectoryFilter; import com.exactpro.sf.util.ReportFilter; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class DefaultTestScriptStorage implements ITestScriptStorage { private static final Logger logger = LoggerFactory.getLogger(DefaultTestScriptStorage.class); - public final static String REPORT_DATA_DIR = "reportData"; + public static final String REPORT_DATA_DIR = "reportData"; public static final String ROOT_JSON_REPORT_FILE = REPORT_DATA_DIR + "/report.json"; @Deprecated @@ -200,9 +212,9 @@ protected TestScriptDescription convertToTestScriptDescription(String workFolder testScriptDescription.setContext(scriptContext); testScriptDescription.setState( - TestScriptDescription.ScriptState.valueOf(properties.getState())); + ScriptState.valueOf(properties.getState())); testScriptDescription.setStatus( - TestScriptDescription.ScriptStatus.valueOf(properties.getStatus())); + ScriptStatus.valueOf(properties.getStatus())); testScriptDescription.setStartedTime(properties.getStartTime()); testScriptDescription.setFinishedTime(properties.getFinishTime()); testScriptDescription.setCause(SerializeUtil.deserializeBase64Obj(properties.getCause(), Throwable.class)); @@ -251,7 +263,7 @@ private TestScriptDescription getReport(String reportRootPath) { } } - private class ScriptRunProgressListenerStub implements ScriptProgress.IScriptRunProgressListener{ + private class ScriptRunProgressListenerStub implements IScriptRunProgressListener{ @Override public void onProgressChanged(long id) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMatrixStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMatrixStorage.java index f249d450..388b0311 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMatrixStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMatrixStorage.java @@ -43,14 +43,8 @@ public class FileMatrixStorage extends AbstractMatrixStorage { public FileMatrixStorage(String path, IWorkspaceDispatcher dispatcher) { super(dispatcher); Objects.requireNonNull(path, "path cannot be null"); - this.matrices = new FileBackedList<>(FilenameUtils.concat(path, MATRICES_DIR), JSONSerializer.of(DefaultMatrix.class), dispatcher); - - if(matrices.isEmpty()) { - matrixId = new AtomicLong(); - } else { - matrixId = new AtomicLong(matrices.get(matrices.size() - 1).getId()); - } + this.matrixId = matrices.isEmpty() ? new AtomicLong() : new AtomicLong(matrices.get(matrices.size() - 1).getId()); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageLoader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageLoader.java index c7622f9f..049f67d1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageLoader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageLoader.java @@ -35,7 +35,7 @@ public class FileMessageLoader extends MessageRowLoaderBase { private final long startTime; private final long finishTime; - private int nextIndex = 0; + private int nextIndex; public FileMessageLoader(List source, MessageFilter filter, int count, int bufferSize) { super(filter, count, bufferSize); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageStorage.java index f47cc082..f11a0014 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileMessageStorage.java @@ -16,6 +16,7 @@ package com.exactpro.sf.storage.impl; import java.sql.Timestamp; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; @@ -23,10 +24,7 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; -import com.exactpro.sf.scriptrunner.EnvironmentSettings; -import com.exactpro.sf.storage.BaseStorageSettings; import org.apache.commons.io.FilenameUtils; -import java.time.Instant; import com.exactpro.sf.common.messages.IHumanMessage; import com.exactpro.sf.common.messages.IMessage; @@ -34,8 +32,8 @@ import com.exactpro.sf.common.messages.MsgMetaData; import com.exactpro.sf.common.services.ServiceInfo; import com.exactpro.sf.common.util.HexDumper; -import com.exactpro.sf.configuration.DictionaryManager; -import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; +import com.exactpro.sf.scriptrunner.EnvironmentSettings; +import com.exactpro.sf.storage.BaseStorageSettings; import com.exactpro.sf.storage.IObjectFlusher; import com.exactpro.sf.storage.MessageFilter; import com.exactpro.sf.storage.MessageList; @@ -71,7 +69,7 @@ public FileMessageStorage(BaseStorageSettings settings) { this.interner = new CHMInterner<>(); this.messageID = new AtomicLong(messages.size()); - this.flusher.start(); + flusher.start(); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileServiceStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileServiceStorage.java index cdb45359..0e57b8bd 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileServiceStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FileServiceStorage.java @@ -112,13 +112,13 @@ public FileServiceStorage(String path, IWorkspaceDispatcher dispatcher, IStaticS @Override public ServiceInfo lookupService(ServiceName serviceName) { try { - this.descriptionLock.readLock().lock(); + descriptionLock.readLock().lock(); if(descriptionMap.containsKey(serviceName)) { return new ServiceInfo(serviceName.toString(), serviceName); } } finally { - this.descriptionLock.readLock().unlock(); + descriptionLock.readLock().unlock(); } return null; @@ -216,10 +216,10 @@ public void updateServiceDescription(ServiceDescription description) { @Override public List getServiceDescriptions() { try { - this.descriptionLock.readLock().lock(); + descriptionLock.readLock().lock(); return ImmutableList.copyOf(descriptionMap.values()); } finally { - this.descriptionLock.readLock().unlock(); + descriptionLock.readLock().unlock(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FilterMessageStorageWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FilterMessageStorageWrapper.java index 1b844acd..1c59f46f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FilterMessageStorageWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/FilterMessageStorageWrapper.java @@ -39,7 +39,7 @@ public FilterMessageStorageWrapper(IMessageStorage messageStorage, Set p @Override public void storeMessage(IMessage message) { - if (this.processedMessageTypes.contains(message.getName())) { + if(processedMessageTypes.contains(message.getName())) { super.storeMessage(message); } else { logger.trace("Message {} skipped by service settings.", message.getName()); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateFactory.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateFactory.java index 7020ee08..b14c7b14 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateFactory.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateFactory.java @@ -40,7 +40,7 @@ public class HibernateFactory { private static final Object lock = new Object(); - private Map sessionFactories; + private final Map sessionFactories; private HibernateFactory () { this.sessionFactories = new HashMap<>(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateStorage.java index 2474e326..bc908297 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/HibernateStorage.java @@ -15,9 +15,16 @@ ******************************************************************************/ package com.exactpro.sf.storage.impl; -import com.exactpro.sf.storage.IStorage; -import com.exactpro.sf.storage.StorageException; -import org.hibernate.*; +import java.util.Iterator; +import java.util.List; +import java.util.function.BiConsumer; + +import org.hibernate.Criteria; +import org.hibernate.HibernateException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; @@ -27,15 +34,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Iterator; -import java.util.List; -import java.util.function.BiConsumer; +import com.exactpro.sf.storage.IStorage; +import com.exactpro.sf.storage.StorageException; public class HibernateStorage implements IStorage { private static final Logger logger = LoggerFactory.getLogger(HibernateStorage.class); - - private SessionFactory sessionFactory; + + private final SessionFactory sessionFactory; private static final int BATCH_SIZE = 50; @@ -52,7 +58,7 @@ public void add(Object entity) throws StorageException { Transaction tx = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); session.save(entity); @@ -87,8 +93,9 @@ public void add(Object entity) throws StorageException { throw new StorageException("Unknown exception", e); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @@ -109,7 +116,7 @@ public void update(Object entity) throws StorageException { Transaction tx = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); session.update(entity); @@ -159,7 +166,7 @@ public void delete(Object entity) throws StorageException { Transaction tx = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); session.delete(entity); @@ -207,7 +214,7 @@ public Object getEntityById(Class entityClass, Long id) { Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); return session.get(entityClass, id); @@ -226,7 +233,7 @@ public T getEntityById(Class entityClass, String id) { Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); return (T) session.get(entityClass, id); @@ -245,20 +252,17 @@ public T getEntityByField(Class entityClass, String fieldName, Object val Session session = null; try { - - session = this.sessionFactory.openSession(); + + session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(entityClass); criteria.add(Restrictions.eq(fieldName, value)); List list = criteria.list(); - - if (null == list || list.isEmpty()) return null; - - return (T) list.get(0); - - } finally { + + return list == null || list.isEmpty() ? null : (T)list.get(0); + } finally { if (session != null) { session.close(); } @@ -273,7 +277,7 @@ public List getAllEntities(Class entityClass) { Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(entityClass); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); @@ -281,8 +285,9 @@ public List getAllEntities(Class entityClass) { return criteria.list(); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @@ -294,13 +299,14 @@ public List getAllEntities(String className) { Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); return session.createQuery(String.format("from %s", className)).list(); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @@ -312,7 +318,7 @@ public List getAllEntities(Class entityClass, List criterio Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(entityClass); @@ -323,8 +329,9 @@ public List getAllEntities(Class entityClass, List criterio return criteria.list(); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @@ -336,27 +343,23 @@ public List getAllEntities(Class entityClass, List criterio Session session = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(entityClass); for (Criterion criterion : criterions) { criteria.add(criterion); } - - if(orderAsc) { - criteria.addOrder(Order.asc(orderField)); - } else { - criteria.addOrder(Order.desc(orderField)); - } - - criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + + criteria.addOrder(orderAsc ? Order.asc(orderField) : Order.desc(orderField)); + criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @@ -368,7 +371,7 @@ public void clear(String[] entities) { Transaction tx = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); Query query; @@ -387,22 +390,23 @@ public void clear(String[] entities) { } finally { - if (session != null) - session.close(); + if(session != null) { + session.close(); + } } } @Override public SessionFactory getSessionFactory() { - return this.sessionFactory; + return sessionFactory; } private void batchOperation(List entities, BiConsumer sessionOperation) { Session session = null; Transaction tx = null; try { - session = this.sessionFactory.openSession(); + session = sessionFactory.openSession(); tx = session.beginTransaction(); Iterator iterator = entities.iterator(); int count = 0; @@ -436,8 +440,9 @@ private void batchOperation(List entities, BiConsumer s } throw new StorageException("Unknown exception", e); } finally { - if (session != null) + if(session != null) { session.close(); + } } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/IDGenerator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/IDGenerator.java index a3ebb72a..e9694a42 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/IDGenerator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/IDGenerator.java @@ -20,7 +20,7 @@ public class IDGenerator { public static String createId() { - UUID uuid = java.util.UUID.randomUUID(); + UUID uuid = UUID.randomUUID(); return uuid.toString(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MemoryServiceStorage.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MemoryServiceStorage.java index 52b4eda8..45562c4f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MemoryServiceStorage.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MemoryServiceStorage.java @@ -15,6 +15,7 @@ ******************************************************************************/ package com.exactpro.sf.storage.impl; +import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; @@ -26,7 +27,6 @@ import org.apache.commons.lang3.NotImplementedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; import com.exactpro.sf.common.services.ServiceInfo; import com.exactpro.sf.common.services.ServiceName; @@ -62,13 +62,13 @@ public MemoryServiceStorage() { @Override public ServiceInfo lookupService(ServiceName serviceName) { try { - this.descriptionLock.readLock().lock(); + descriptionLock.readLock().lock(); - if(this.descriptionMap.containsKey(serviceName)) { + if(descriptionMap.containsKey(serviceName)) { return new ServiceInfo(serviceName.toString(), serviceName); } } finally { - this.descriptionLock.readLock().unlock(); + descriptionLock.readLock().unlock(); } return null; @@ -78,24 +78,24 @@ public ServiceInfo lookupService(ServiceName serviceName) { public void addServiceDescription(ServiceDescription description) { ServiceName serviceName = new ServiceName(description.getEnvironment(), description.getName()); try { - this.descriptionLock.writeLock().lock(); - if (!this.descriptionMap.containsKey(serviceName)) { + descriptionLock.writeLock().lock(); + if(!descriptionMap.containsKey(serviceName)) { try { - this.eventLock.writeLock().lock(); - if (!this.eventMap.containsKey(serviceName)) { - this.descriptionMap.put(serviceName, description); - this.eventMap.put(serviceName, new LinkedList()); + eventLock.writeLock().lock(); + if(!eventMap.containsKey(serviceName)) { + descriptionMap.put(serviceName, description); + eventMap.put(serviceName, new LinkedList()); } else { throw new StorageException("Service '" + serviceName + "' with the same name already exists"); } } finally { - this.eventLock.writeLock().unlock(); + eventLock.writeLock().unlock(); } } else { throw new StorageException("Service '" + serviceName + "' with the same name already exists"); } } finally { - this.descriptionLock.writeLock().unlock(); + descriptionLock.writeLock().unlock(); } } @@ -103,16 +103,16 @@ public void addServiceDescription(ServiceDescription description) { public void removeServiceDescription(ServiceDescription description) { ServiceName serviceName = new ServiceName(description.getEnvironment(), description.getName()); try { - this.descriptionLock.writeLock().lock(); + descriptionLock.writeLock().lock(); try { - this.eventLock.writeLock().lock(); - this.descriptionMap.remove(serviceName); - this.eventMap.remove(serviceName); + eventLock.writeLock().lock(); + descriptionMap.remove(serviceName); + eventMap.remove(serviceName); } finally { - this.eventLock.writeLock().unlock(); + eventLock.writeLock().unlock(); } } finally { - this.descriptionLock.writeLock().unlock(); + descriptionLock.writeLock().unlock(); } } @@ -120,10 +120,10 @@ public void removeServiceDescription(ServiceDescription description) { public void updateServiceDescription(ServiceDescription description) { ServiceName serviceName = new ServiceName(description.getEnvironment(), description.getName()); try { - this.descriptionLock.writeLock().lock(); - this.descriptionMap.put(serviceName, description); + descriptionLock.writeLock().lock(); + descriptionMap.put(serviceName, description); } finally { - this.descriptionLock.writeLock().unlock(); + descriptionLock.writeLock().unlock(); } } @@ -131,11 +131,11 @@ public void updateServiceDescription(ServiceDescription description) { @Override public List getServiceDescriptions() { try { - this.descriptionLock.readLock().lock(); - List result = new ArrayList<>(this.descriptionMap.values()); + descriptionLock.readLock().lock(); + List result = new ArrayList<>(descriptionMap.values()); return result; } finally { - this.descriptionLock.readLock().unlock(); + descriptionLock.readLock().unlock(); } } @@ -143,10 +143,10 @@ public List getServiceDescriptions() { public void addServiceEvent(ServiceDescription description, ServiceEvent event) { ServiceName serviceName = new ServiceName(description.getEnvironment(), description.getName()); try { - this.eventLock.writeLock().lock(); - LinkedList list = this.eventMap.get(serviceName); + eventLock.writeLock().lock(); + LinkedList list = eventMap.get(serviceName); if (list != null) { - while (list.size() > this.eventLimit) { + while(list.size() > eventLimit) { list.removeLast(); } list.addFirst(event); @@ -154,7 +154,7 @@ public void addServiceEvent(ServiceDescription description, ServiceEvent event) logger.warn("Storage does not contain service {}", serviceName); } } finally { - this.eventLock.writeLock().unlock(); + eventLock.writeLock().unlock(); } } @@ -162,11 +162,11 @@ public void addServiceEvent(ServiceDescription description, ServiceEvent event) public long getEventsCount(ServiceDescription description, StorageFilter filter) { ServiceName serviceName = new ServiceName(description.getEnvironment(), description.getName()); try { - this.eventLock.readLock().lock(); - List list = this.eventMap.get(serviceName); + eventLock.readLock().lock(); + List list = eventMap.get(serviceName); return list != null ? list.size() : 0; } finally { - this.eventLock.readLock().unlock(); + eventLock.readLock().unlock(); } } @@ -180,23 +180,23 @@ public StorageResult getServiceEvents(ServiceDescription descripti public void removeServiceEvents(ServiceDescription description) { ServiceName serviceName = new ServiceName(description.getEnvironment(), description.getName()); try { - this.eventLock.writeLock().lock(); - List list = this.eventMap.get(serviceName); + eventLock.writeLock().lock(); + List list = eventMap.get(serviceName); if (list != null) { list.clear(); } } finally { - this.eventLock.writeLock().unlock(); + eventLock.writeLock().unlock(); } } @Override public void removeServiceEvents(Instant olderThan) { try { - this.eventLock.writeLock().lock(); + eventLock.writeLock().lock(); long epochMillis = olderThan.toEpochMilli(); - for (List list : this.eventMap.values()) { + for(List list : eventMap.values()) { if(olderThan == null) { list.clear(); continue; @@ -218,7 +218,7 @@ public void removeServiceEvents(Instant olderThan) { list.subList(0, toIndex + 1).clear(); } } finally { - this.eventLock.writeLock().unlock(); + eventLock.writeLock().unlock(); } } @@ -230,16 +230,16 @@ public void clearServiceEvents() { @Override public void dispose() { try { - this.descriptionLock.writeLock().lock(); + descriptionLock.writeLock().lock(); try { - this.eventLock.writeLock().lock(); - this.descriptionMap.clear(); - this.eventMap.clear(); + eventLock.writeLock().lock(); + descriptionMap.clear(); + eventMap.clear(); } finally { - this.eventLock.writeLock().unlock(); + eventLock.writeLock().unlock(); } } finally { - this.descriptionLock.writeLock().unlock(); + descriptionLock.writeLock().unlock(); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageRowLoaderBase.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageRowLoaderBase.java index bd553a78..c7f0dad2 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageRowLoaderBase.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageRowLoaderBase.java @@ -44,11 +44,7 @@ public MessageRowLoaderBase(MessageFilter filter, int count, int bufferSize) { this.filter = filter; this.count = count; this.bufferSize = bufferSize; - if (filter.getRawMessage() != null) { - this.isHex = "hex".equals(filter.getRawMessage()); - } else { - this.isHex = true; - } + this.isHex = filter.getRawMessage() == null || "hex".equals(filter.getRawMessage()); this.buffer = new ArrayDeque<>(this.bufferSize); } @@ -67,14 +63,14 @@ public Iterator iterator() { return new Iterator() { - int counter = 0; + int counter; private long lastID; private final Interner interner = new CHMInterner<>(); { - lastID = (Boolean.FALSE.equals(filter.getSortOrder())) + lastID = Boolean.FALSE.equals(filter.getSortOrder()) ? Long.MAX_VALUE : 0; - retrieveMessages(MessageRowLoaderBase.this.buffer, MessageRowLoaderBase.this.bufferSize, this.lastID); + retrieveMessages(buffer, bufferSize, lastID); } @Override @@ -87,14 +83,14 @@ public MessageRow next() { this.counter++; T tmp = buffer.remove(); this.lastID = getID(tmp); - if (MessageRowLoaderBase.this.buffer.isEmpty() && needMessages()) { - retrieveMessages(MessageRowLoaderBase.this.buffer, MessageRowLoaderBase.this.bufferSize, this.lastID); + if(buffer.isEmpty() && needMessages()) { + retrieveMessages(buffer, bufferSize, lastID); } - return convert(tmp, this.interner); + return convert(tmp, interner); } private boolean needMessages() { - return (this.counter < MessageRowLoaderBase.this.count || MessageRowLoaderBase.this.count < 0); + return counter < count || count < 0; } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageStorageWrapper.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageStorageWrapper.java index ab30fa4e..b2ffce9c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageStorageWrapper.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/MessageStorageWrapper.java @@ -30,27 +30,27 @@ public MessageStorageWrapper(IMessageStorage messageStorage) { @Override public void dispose() { - this.messageStorage.dispose(); + messageStorage.dispose(); } @Override public void storeMessage(IMessage message) { - this.messageStorage.storeMessage(message); + messageStorage.storeMessage(message); } @Override public Iterable getMessages(int count, MessageFilter filter) { - return this.messageStorage.getMessages(count, filter); + return messageStorage.getMessages(count, filter); } @Override public Iterable getMessages(int offset, int count, String where) { - return this.messageStorage.getMessages(offset, count, where); + return messageStorage.getMessages(offset, count, where); } @Override public void clear() { - this.messageStorage.clear(); + messageStorage.clear(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java index 399527b2..79780a62 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/ObjectFlusher.java @@ -15,24 +15,29 @@ ******************************************************************************/ package com.exactpro.sf.storage.impl; -import com.exactpro.sf.common.util.EPSCommonException; -import com.exactpro.sf.storage.IObjectFlusher; -import com.exactpro.sf.storage.IMeasurable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.*; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.exactpro.sf.common.util.EPSCommonException; +import com.exactpro.sf.storage.IMeasurable; +import com.exactpro.sf.storage.IObjectFlusher; public class ObjectFlusher implements IObjectFlusher { private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); - private final static Logger USER_EVENTS_LOG = LoggerFactory.getLogger("USER_EVENTS_LOG"); + private static final Logger USER_EVENTS_LOG = LoggerFactory.getLogger("USER_EVENTS_LOG"); private static final long JOIN_TIMEOUT = 2000; @@ -44,18 +49,18 @@ public class ObjectFlusher implements IObjectFlusher { private final long maxStorageQueueSize; - private long storageProviderQueueSize = 0; - private long lastThrottleNotification = 0; + private long storageProviderQueueSize; + private long lastThrottleNotification; private static final long NOTIFY_COOLDOWN = 1000*30; private static final String STORE_OBJECT_LIMIT_EXCEEDED = "Can't store object, limit exceeded"; - private static final long DEFAULT_STORAGE_QUEUE = (1024L * 1024L * 32L); + private static final long DEFAULT_STORAGE_QUEUE = 1024L * 1024L * 32L; private List objects; private FlushTask flushTask; private Thread flushThread; - static int a = 0; + static int a; static Lock lock = new ReentrantLock(true); static CyclicBarrier b = new CyclicBarrier(2); @@ -71,7 +76,7 @@ public void run() { for (int i = 0; i < 500; i++) { try { lock.lock(); - System.out.println(Thread.currentThread().getId() + " " + String.valueOf(a++)); + System.out.println(Thread.currentThread().getId() + " " + a++); } finally { lock.unlock(); } @@ -107,7 +112,7 @@ public ObjectFlusher(IFlushProvider provider, int bufferSize, long maxStorage @Override public void start() { try { - this.sourceMonitor.writeLock().lock(); + sourceMonitor.writeLock().lock(); if(flushTask != null) { throw new EPSCommonException("Cannot start flusher. Flusher is already started"); } @@ -117,7 +122,7 @@ public void start() { flushThread.setDaemon(true); flushThread.start(); } finally { - this.sourceMonitor.writeLock().unlock(); + sourceMonitor.writeLock().unlock(); } } @@ -126,7 +131,7 @@ public void stop() { flush(); try { - this.sourceMonitor.writeLock().lock(); + sourceMonitor.writeLock().lock(); if(flushTask == null) { throw new EPSCommonException("Cannot stop flusher. Flusher is not started"); @@ -146,7 +151,7 @@ public void stop() { flushThread = null; } } finally { - this.sourceMonitor.writeLock().unlock(); + sourceMonitor.writeLock().unlock(); } } @@ -154,7 +159,7 @@ public void stop() { public void add(T object) { try { logger.debug("Try lock sourceMonitor read"); - this.sourceMonitor.readLock().lock(); + sourceMonitor.readLock().lock(); logger.debug("sourceMonitor locked"); if(flushTask == null) { throw new EPSCommonException("Cannot add object. Flusher is not started"); @@ -182,7 +187,7 @@ public void add(T object) { logger.debug("monitor unlocked"); } } finally { - this.sourceMonitor.readLock().unlock(); + sourceMonitor.readLock().unlock(); logger.debug("sourceMonitor read unlocked"); } } @@ -191,7 +196,7 @@ public void add(T object) { public void flush() { try { logger.debug("Try lock sourceMonitor read"); - this.sourceMonitor.readLock().lock(); + sourceMonitor.readLock().lock(); logger.debug("sourceMonitor read locked"); if(flushTask == null) { throw new EPSCommonException("Cannot request flush. Flusher is not started"); @@ -218,7 +223,7 @@ public void flush() { } } } finally { - this.sourceMonitor.readLock().unlock(); + sourceMonitor.readLock().unlock(); logger.debug("sourceMonitor read unlocked"); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/PersistentObject.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/PersistentObject.java index a4033172..3488b950 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/PersistentObject.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/impl/PersistentObject.java @@ -17,12 +17,12 @@ public interface PersistentObject { - public String getId(); + String getId(); - public void setId(String id); + void setId(String id); - public Integer getVersion(); + Integer getVersion(); - public void setVersion(Integer version); + void setVersion(Integer version); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonHumanDecoder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonHumanDecoder.java index 7bfc24e9..0535c9d3 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonHumanDecoder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonHumanDecoder.java @@ -45,7 +45,7 @@ public IHumanMessage parse(JsonParser parser, String protocol, SailfishURI dicti @Override protected IHumanMessage createMessage(String messageName) { - return this.messageFactory.createHumanMessage(messageName); + return messageFactory.createHumanMessage(messageName); } @Override diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonIMessageDecoder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonIMessageDecoder.java index d0a69c4e..bf451af1 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonIMessageDecoder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonIMessageDecoder.java @@ -47,7 +47,7 @@ public IMessage parse(JsonParser parser, String protocol, SailfishURI dictionary @Override protected IMessage createMessage(String messageName) { - return this.messageFactory.createMessage(messageName); + return messageFactory.createMessage(messageName); } @Override @@ -65,7 +65,7 @@ public JSONMessageFactory(String protocol) { @Override public String getProtocol() { - return this.protocol; + return protocol; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageConverter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageConverter.java index bbe53b2b..a9a3f26b 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageConverter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageConverter.java @@ -277,30 +277,26 @@ private static Set getFieldNamesRetain(IMessage message, IFieldStructure } private static String getValueClass(Object value, IFieldStructure structure) { - String clazz = null; - if(value instanceof List) { value = Iterables.get((Iterable)value, 0, null); if(value != null || structure != null) { - clazz = List.class.getSimpleName() + "<" + getValueClass(value, structure) + ">"; + return List.class.getSimpleName() + "<" + getValueClass(value, structure) + ">"; } else { - clazz = List.class.getSimpleName() + ""; + return List.class.getSimpleName() + ""; } } else if(value instanceof IMessage) { - clazz = IMessage.class.getSimpleName(); + return IMessage.class.getSimpleName(); } else { if(structure != null) { if(structure.isComplex()) { - clazz = IMessage.class.getSimpleName(); + return IMessage.class.getSimpleName(); } else { - clazz = StringUtils.substringAfterLast(structure.getJavaType().value(), "."); + return StringUtils.substringAfterLast(structure.getJavaType().value(), "."); } } else { - clazz = ClassUtils.getSimpleName(value, null); + return ClassUtils.getSimpleName(value, null); } } - - return clazz; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageDecoder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageDecoder.java index f8725947..b889c91c 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageDecoder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/JsonMessageDecoder.java @@ -37,7 +37,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; @@ -130,11 +129,7 @@ public T parse(JsonParser parser, String protocol, SailfishURI dictionaryURI, St ? dictionaryManager.getDictionary(dictionaryURI) : null; IFieldStructure fieldStructure = dictionaryStructure != null ? dictionaryStructure.getMessages().get(name) : null; - if (compact) { - return getMessageCompact(parser, fieldStructure, name, dirty); - } else { - return getMessageFull(parser, fieldStructure, name, dirty); - } + return compact ? getMessageCompact(parser, fieldStructure, name, dirty) : getMessageFull(parser, fieldStructure, name, dirty); } protected abstract T createMessage(String messageName); @@ -145,7 +140,7 @@ private T getMessageCompact(JsonParser parser, IFieldStructure fieldStructure, S try { checkToken(parser, JsonToken.START_OBJECT, parser.getCurrentToken()); T message = createMessage(messageName); - while (JsonToken.END_OBJECT != parser.nextToken()) { + while(parser.nextToken() != JsonToken.END_OBJECT) { String fieldName = parser.getCurrentName(); IFieldStructure subFieldStructure = fieldStructure != null ? fieldStructure.getFields().get(fieldName) : null; parser.nextToken(); @@ -163,7 +158,7 @@ private T getMessageFull(JsonParser parser, IFieldStructure fieldStructure, Stri try { checkToken(parser, JsonToken.START_OBJECT, parser.getCurrentToken()); T message = createMessage(messageName); - while (JsonToken.FIELD_NAME == parser.nextToken()) { + while(parser.nextToken() == JsonToken.FIELD_NAME) { String fieldName = parser.getCurrentName(); IFieldStructure subFieldStructure = fieldStructure != null ? fieldStructure.getFields().get(fieldName) : null; parser.nextToken(); @@ -188,14 +183,14 @@ private FieldInfo getValueCompact(JsonParser parser, IFieldStructure fieldStruct parser.getCurrentName(); isMessage = parser.getCurrentToken() == JsonToken.START_OBJECT; List list = new ArrayList<>(); - while (JsonToken.END_ARRAY != currentToken) { + while(currentToken != JsonToken.END_ARRAY) { list.add(getValueCompact(parser, fieldStructure, dirty).getValue()); currentToken = parser.nextToken(); currentName = parser.getCurrentName(); } Type type = isMessage ? Type.IMESSAGE : - !dirty && (fieldStructure != null && !fieldStructure.isComplex()) ? Type.parse(fieldStructure.getJavaType()) : Type.STRING; + !dirty && fieldStructure != null && !fieldStructure.isComplex() ? Type.parse(fieldStructure.getJavaType()) : Type.STRING; return new FieldInfo(list, type, isColection, null, fieldStructure); } else { @@ -230,7 +225,7 @@ private FieldInfo getValueFull(JsonParser parser, IFieldStructure fieldStructure JsonToken currentToken = parser.nextToken(); currentFieldName = parser.getCurrentName(); List list = new ArrayList<>(); - while (JsonToken.END_ARRAY != currentToken) { + while(currentToken != JsonToken.END_ARRAY) { list.add(getValueFull(parser, fieldStructure, dirty).getValue()); currentToken = parser.nextToken(); parser.getCurrentName(); @@ -240,7 +235,7 @@ private FieldInfo getValueFull(JsonParser parser, IFieldStructure fieldStructure } else { Object value = getValue(parser, fieldStructure, "value", type, dirty); Map properties = new HashMap<>(); - while (JsonToken.END_OBJECT != parser.nextToken()) { + while(parser.nextToken() != JsonToken.END_OBJECT) { checkFieldName(parser, JsonToken.FIELD_NAME, null); parser.nextToken(); currentFieldName = parser.getCurrentName(); @@ -271,60 +266,44 @@ protected V getValue(JsonParser parser, IFieldStructure fieldStructure, Stri } protected Object parseValueFull(JsonParser parser, IFieldStructure fieldStructure, String name, Type type, boolean dirty) throws IOException { - Object result = null; switch (type) { case BOOLEAN: - result = Boolean.valueOf(parser.getBooleanValue()); - break; - case SHORT: - result = Short.valueOf(parser.getShortValue()); - break; - case INTEGER: - result = Integer.valueOf(parser.getIntValue()); - break; - case LONG: - result = Long.valueOf(parser.getLongValue()); - break; - case BYTE: - result = Byte.valueOf(parser.getByteValue()); - break; - case FLOAT: - result = Float.valueOf(parser.getFloatValue()); - break; - case DOUBLE: - result = Double.valueOf(parser.getDoubleValue()); - break; - case NOTNULLFILTER: + return Boolean.valueOf(parser.getBooleanValue()); + case SHORT: + return Short.valueOf(parser.getShortValue()); + case INTEGER: + return Integer.valueOf(parser.getIntValue()); + case LONG: + return Long.valueOf(parser.getLongValue()); + case BYTE: + return Byte.valueOf(parser.getByteValue()); + case FLOAT: + return Float.valueOf(parser.getFloatValue()); + case DOUBLE: + return Double.valueOf(parser.getDoubleValue()); + case NOTNULLFILTER: case NULLFILTER: case MVELFILTER: case REGEXMVELFILTER: case SIMPLEMVELFILTER: case KNOWNBUGFILTER: case STRING: - result = parser.getValueAsString(); - break; - case LOCALDATETIME: - result = LocalDateTime.parse(parser.getValueAsString(), DateTimeFormatter.ISO_DATE_TIME); - break; - case LOCALDATE: - result = LocalDate.parse(parser.getValueAsString(), DateTimeFormatter.ISO_DATE); - break; - case LOCALTIME: - result = LocalTime.parse(parser.getValueAsString(), DateTimeFormatter.ISO_TIME); - break; - case CHARACTER: - result = Character.valueOf(parser.getValueAsString().charAt(0)); - break; - case BIGDECIMAL: - result = new BigDecimal(parser.getValueAsString()); - break; - case IMESSAGE: - result = getMessageFull(parser, fieldStructure, name, dirty); - break; - default: + return parser.getValueAsString(); + case LOCALDATETIME: + return LocalDateTime.parse(parser.getValueAsString(), DateTimeFormatter.ISO_DATE_TIME); + case LOCALDATE: + return LocalDate.parse(parser.getValueAsString(), DateTimeFormatter.ISO_DATE); + case LOCALTIME: + return LocalTime.parse(parser.getValueAsString(), DateTimeFormatter.ISO_TIME); + case CHARACTER: + return Character.valueOf(parser.getValueAsString().charAt(0)); + case BIGDECIMAL: + return new BigDecimal(parser.getValueAsString()); + case IMESSAGE: + return getMessageFull(parser, fieldStructure, name, dirty); + default: throw new JsonParseException("Unsupported type " + type, parser.getCurrentLocation()); } - return result; } protected Object parseValueCompact(JsonParser parser, IFieldStructure fieldStructure, JavaType javaType, boolean dirty) throws IOException { @@ -337,7 +316,7 @@ protected static void skipValue(JsonParser parser) throws JsonParseException, IO } protected static void checkFieldName(JsonParser parser, JsonToken jsonToken, String name) throws IOException, JsonParseException { - if (JsonToken.FIELD_NAME != jsonToken || (name != null && !name.equals(parser.getCurrentName()))) { + if(jsonToken != JsonToken.FIELD_NAME || (name != null && !name.equals(parser.getCurrentName()))) { throw new JsonParseException("Missing expected '" + name + "' field", parser.getCurrentLocation()); } } @@ -358,7 +337,6 @@ protected static class FieldInfo { private final IFieldStructure fieldStructure; public FieldInfo(Object value, Type type, boolean isCollection, Map properties, IFieldStructure fieldStructure) { - super(); this.value = value; this.type = type; this.isCollection = isCollection; @@ -387,7 +365,7 @@ public IFieldStructure getFieldStructure() { } } - protected static enum Type { + protected enum Type { IMESSAGE(null, "IMessage"), BOOLEAN(JavaType.JAVA_LANG_BOOLEAN, "Boolean"), SHORT(JavaType.JAVA_LANG_SHORT, "Short"), @@ -451,7 +429,7 @@ static Type parse(String value) { static Type parse(JavaType javaType) { for (Type type : Type.values()) { - if (Objects.equals(type.javaType, javaType)) { + if(type.javaType == javaType) { return type; } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/PropertiesSettingsReaderSerializer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/PropertiesSettingsReaderSerializer.java index 662298c9..20821e1e 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/PropertiesSettingsReaderSerializer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/PropertiesSettingsReaderSerializer.java @@ -23,6 +23,7 @@ import java.io.Writer; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import org.apache.commons.lang3.ArrayUtils; @@ -35,8 +36,8 @@ import com.exactpro.sf.storage.IMappableSettingsSerializer; public class PropertiesSettingsReaderSerializer implements IMappableSettingsSerializer { - private final static Logger logger = LoggerFactory.getLogger(PropertiesSettingsReaderSerializer.class); - private final static String SETTINGS_EXTENSION = ".properties"; + private static final Logger logger = LoggerFactory.getLogger(PropertiesSettingsReaderSerializer.class); + private static final String SETTINGS_EXTENSION = ".properties"; public void readMappableSettings(IMapableSettings settings, IWorkspaceDispatcher wd, FolderType folderType, String... relativePath) throws Exception { String fileName = settings.settingsName() + SETTINGS_EXTENSION; @@ -47,7 +48,7 @@ public void readMappableSettings(IMapableSettings settings, IWorkspaceDispatcher properties.load(in); } Map settingsMap = new HashMap<>(); - for (Map.Entry entry : properties.entrySet()) { + for (Entry entry : properties.entrySet()) { settingsMap.put(entry.getKey().toString(), entry.getValue().toString()); } settings.fillFromMap(settingsMap); @@ -58,7 +59,7 @@ public void writeMappableSettings(IMapableSettings settings, IWorkspaceDispatche String fileName = settings.settingsName() + SETTINGS_EXTENSION; File settingsFile = wd.createFile(folderType, true, ArrayUtils.addAll(relativePath, fileName)); Properties properties = new Properties(); - for (Map.Entry entry : settings.toMap().entrySet()) { + for (Entry entry : settings.toMap().entrySet()) { if (entry.getValue() != null) { properties.put(entry.getKey(), entry.getValue()); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/StorageMeasureUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/StorageMeasureUtils.java index 4d929c20..337282e4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/StorageMeasureUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/util/StorageMeasureUtils.java @@ -19,7 +19,7 @@ public class StorageMeasureUtils { public static long getSize(String src) { int no_chars = (src == null) ? 0 : src.length(); - return (8L * ((((no_chars) << 1) + 45) / 8)); //45bytes is representation of internal string fields + return 8L * (((no_chars << 1) + 45) / 8); //45bytes is representation of internal string fields } public static long getSize(String... src) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageReaderVisitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageReaderVisitor.java index f2d304ed..a7e9183d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageReaderVisitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageReaderVisitor.java @@ -31,9 +31,9 @@ class DataMessageReaderVisitor implements IMessageStructureVisitor { - private DataMessage dataMessage; - private IMessage mapMessage; - private static MessageStructureWriter wtraverser = new MessageStructureWriter(); + private final DataMessage dataMessage; + private final IMessage mapMessage; + private static final MessageStructureWriter wtraverser = new MessageStructureWriter(); public DataMessageReaderVisitor(DataMessage dataMessage, IMessage mapMessage) { this.dataMessage = dataMessage; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageWriterVisitor.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageWriterVisitor.java index 2558e5c5..ea4ee8e5 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageWriterVisitor.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/DataMessageWriterVisitor.java @@ -30,9 +30,9 @@ public class DataMessageWriterVisitor implements IMessageStructureVisitor { - private DataMessage dataMessage; + private final DataMessage dataMessage; - private static MessageStructureReader rtraverser = new MessageStructureReader(); + private static final MessageStructureReader rtraverser = new MessageStructureReader(); public DataMessageWriterVisitor(DataMessage dataMessage){ this.dataMessage = dataMessage; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/TypeConverter.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/TypeConverter.java index f4ebde33..439ca817 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/TypeConverter.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/TypeConverter.java @@ -15,21 +15,20 @@ ******************************************************************************/ package com.exactpro.sf.storage.xml; +import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.ParseException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; - -import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.ParseException; import java.util.Date; public class TypeConverter { public static boolean getBoolean(String value){ - return value.equals("true")?true:false; + return "true".equals(value) ? true : false; } public static String getString(boolean value){ diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/db/DBPersister.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/db/DBPersister.java index 7e152e45..78803184 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/db/DBPersister.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/storage/xml/db/DBPersister.java @@ -31,6 +31,7 @@ import com.exactpro.sf.common.impl.messages.xml.XMLTransmitter; import com.exactpro.sf.storage.FilterCriterion; +import com.exactpro.sf.storage.FilterCriterion.Operation; import com.exactpro.sf.storage.SortCriterion; import com.exactpro.sf.storage.StorageException; import com.exactpro.sf.storage.xml.DataMessage; @@ -40,19 +41,13 @@ @SuppressWarnings("deprecation") public class DBPersister implements DataMessagePersister { - private static SessionFactory factory; + private static final SessionFactory factory = new Configuration() + .configure("/com/exactpro/sf/configuration/hibernate.cfg.xml") + .buildSessionFactory(); - private static XMLTransmitter transmitter; + private static final XMLTransmitter transmitter = XMLTransmitter.getTransmitter(); - static { - factory = new Configuration() - .configure( - "/com/exactpro/sf/configuration/hibernate.cfg.xml") - .buildSessionFactory(); - transmitter = XMLTransmitter.getTransmitter(); - } - - @Override + @Override public DataMessage getDataMessage(List filterCriterions, List sortCriterions) throws StorageException { return deserialize(retriveUnique(filterCriterions, sortCriterions)); @@ -124,7 +119,7 @@ private Criteria createCriteria(List filterCriterions, Criteria criteria = session.createCriteria(XmlDataMessage.class); if (filterCriterions != null) { for (FilterCriterion criterion : filterCriterions) { - if (criterion.getOper() != FilterCriterion.Operation.LIKE) { + if (criterion.getOper() != Operation.LIKE) { continue; } criteria.add(Restrictions.like(XmlDataMessage.RAW_DATA, @@ -133,11 +128,7 @@ private Criteria createCriteria(List filterCriterions, } if (sortCriterions != null) { for (SortCriterion criterion : sortCriterions) { - if (criterion.isSortAscending()) { - criteria.addOrder(Order.asc(criterion.getName())); - } else { - criteria.addOrder(Order.desc(criterion.getName())); - } + criteria.addOrder(criterion.isSortAscending() ? Order.asc(criterion.getName()) : Order.desc(criterion.getName())); } } return criteria; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/AbstractBugsChecker.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/AbstractBugsChecker.java index b966e4b7..681debb4 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/AbstractBugsChecker.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/AbstractBugsChecker.java @@ -20,6 +20,7 @@ import com.exactpro.sf.aml.scriptutil.StaticUtil; import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; import com.exactpro.sf.aml.scriptutil.StaticUtil.IKnownBug; +import com.exactpro.sf.aml.scriptutil.StaticUtil.KnownBugFilter; import com.exactpro.sf.comparison.Convention; public abstract class AbstractBugsChecker implements IKnownBug { @@ -30,6 +31,6 @@ public IKnownBug BugEmpty(String subject, String... categories) { } public IFilter toFilter() { - return new StaticUtil.KnownBugFilter(0, StringUtils.EMPTY, this); + return new KnownBugFilter(0, StringUtils.EMPTY, this); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugDescription.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugDescription.java index e0098105..7bcbbe8a 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugDescription.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugDescription.java @@ -19,14 +19,14 @@ import java.util.Comparator; import java.util.List; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import com.exactpro.sf.common.util.EPSCommonException; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; @@ -52,11 +52,11 @@ public BugDescription(String subject, String... categories) { } public String getSubject() { - return this.subject; + return subject; } public Category getCategories() { - return this.category; + return category; } @Override @@ -67,8 +67,8 @@ public int compareTo(BugDescription o) { CompareToBuilder builder = new CompareToBuilder(); - builder.append(this.category, o.category); - builder.append(this.subject, o.subject); + builder.append(category, o.category); + builder.append(subject, o.subject); return builder.toComparison(); } @@ -86,8 +86,8 @@ public boolean equals(Object o) { BugDescription that = (BugDescription)o; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.category, that.category); - builder.append(this.subject, that.subject); + builder.append(category, that.category); + builder.append(subject, that.subject); return builder.isEquals(); } @@ -96,20 +96,20 @@ public boolean equals(Object o) { public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); - builder.append(this.category); - builder.append(this.subject); + builder.append(category); + builder.append(subject); return builder.toHashCode(); } public String toString() { StringBuilder builder = new StringBuilder(); - - for (String category : this.category.categories) { + + for(String category : category.categories) { builder.append(category).append('('); } - builder.append(this.subject); - for (int i = 0; i < this.category.categories.size(); i++) { + builder.append(subject); + for(int i = 0; i < category.categories.size(); i++) { builder.append(')'); } return builder.toString(); @@ -147,7 +147,7 @@ public int compareTo(Category o) { Comparator categoriesComparator = new BugCategoriesComparator(); - return categoriesComparator.compare(Iterables.toArray(this.categories, String.class), + return categoriesComparator.compare(Iterables.toArray(categories, String.class), Iterables.toArray(o.categories, String.class)); } @@ -164,7 +164,7 @@ public boolean equals(Object o) { Category that = (Category)o; EqualsBuilder builder = new EqualsBuilder(); - builder.append(this.categories, that.categories); + builder.append(categories, that.categories); return builder.isEquals(); } @@ -173,23 +173,23 @@ public boolean equals(Object o) { public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); - builder.append(this.categories); + builder.append(categories); return builder.toHashCode(); } public String toString() { - if (this.categories.isEmpty()) { + if(categories.isEmpty()) { return ""; } - - StringBuilder builder = new StringBuilder(this.categories.get(0)); - - for (int i = 1; i < this.categories.size(); i++) { - builder.append('(').append(this.categories.get(i)); + + StringBuilder builder = new StringBuilder(categories.get(0)); + + for(int i = 1; i < categories.size(); i++) { + builder.append('(').append(categories.get(i)); } - - for (int i = 0; i < this.categories.size() - 1; i++) { + + for(int i = 0; i < categories.size() - 1; i++) { builder.append(')'); } return builder.toString(); diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsCheckerBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsCheckerBuilder.java index a039ede3..8ffabf27 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsCheckerBuilder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsCheckerBuilder.java @@ -23,12 +23,9 @@ import java.util.function.Function; import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; import com.exactpro.sf.aml.scriptutil.ExpressionResult; -import com.exactpro.sf.aml.scriptutil.StaticUtil; import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; -import com.exactpro.sf.aml.scriptutil.StaticUtil.IKnownBug; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.comparison.Convention; import com.exactpro.sf.comparison.conversion.MultiConverter; @@ -49,8 +46,8 @@ public class BugsCheckerBuilder extends AbstractBugsChecker { private final SetMultimap alternativeValues = LinkedHashMultimap.create(); private Object actualValue = BugsCheckerBuilder.class; //default value, because real actual value may be null private final Function defaultActualMapFunction = value -> - this.actualValue != BugsCheckerBuilder.class - ? this.actualValue + actualValue != BugsCheckerBuilder.class + ? actualValue : ObjectUtils.defaultIfNull(value, Convention.CONV_MISSED_OBJECT); private Function actualMapFumction = defaultActualMapFunction; @@ -69,7 +66,7 @@ public BugsCheckerBuilder Bug(String subject, Object alternativeValue, String... "Alternative value " + alternativeValue + " with description " + bugDescription + " are equal to origin value " + originValue); } try { - this.alternativeValues.put(alternativeValue, bugDescription); + alternativeValues.put(alternativeValue, bugDescription); } catch (IllegalArgumentException e) { throw new EPSCommonException("Alternative values map already contains " + alternativeValue, e); } @@ -78,8 +75,8 @@ public BugsCheckerBuilder Bug(String subject, Object alternativeValue, String... @Override public BugsCheckerBuilder BugAny(String subject, String... categories) { - if (this.originValue != Convention.CONV_MISSED_OBJECT) { - throw new EPSCommonException("Expected value '" + this.originValue + "' is not empty"); + if(originValue != Convention.CONV_MISSED_OBJECT) { + throw new EPSCommonException("Expected value '" + originValue + "' is not empty"); } return Bug(subject, Convention.CONV_PRESENT_OBJECT, categories); } @@ -103,7 +100,7 @@ public BugsCheckerBuilder Actual(Object obj) { public ExpressionResult validate(Object actualValue) throws KnownBugException { actualValue = actualMapFumction.apply(actualValue); - if (this.originValue == Convention.CONV_PRESENT_OBJECT && actualValue != Convention.CONV_MISSED_OBJECT) { + if(originValue == Convention.CONV_PRESENT_OBJECT && actualValue != Convention.CONV_MISSED_OBJECT) { return new ExpressionResult(false, ORIGIN_VALUE_MESSAGE, null, null, getDescriptions()); } @@ -160,7 +157,7 @@ public ExpressionResult validate(Object actualValue) throws KnownBugException { @Override public String getCondition() { StringBuilder stringBuilder = new StringBuilder() - .append("Expected: ").append(formatValue(this.originValue)).append(", Bugs: ["); + .append("Expected: ").append(formatValue(originValue)).append(", Bugs: ["); for (Object alternativeValue : alternativeValues.keySet()) { stringBuilder .append("'").append(alternativeValues.get(alternativeValue)).append("'") @@ -180,7 +177,7 @@ private String formatValue(Object value) { } private Set getDescriptions() { - return Collections.unmodifiableSet(new HashSet<>(this.alternativeValues.values())); + return Collections.unmodifiableSet(new HashSet<>(alternativeValues.values())); } private static ExpressionResult createExpressionResult(BugsCheckerBuilder bugsCheckerBuilder, Set descriptions) { @@ -188,10 +185,10 @@ private static ExpressionResult createExpressionResult(BugsCheckerBuilder bugsCh } private boolean isActualEmpty() { - if (this.actualMapFumction != defaultActualMapFunction) { + if(actualMapFumction != defaultActualMapFunction) { throw new EPSCommonException("Actual map fumction already set"); - } else if (this.actualValue != BugsCheckerBuilder.class) { - throw new EPSCommonException("Actual already set '" + this.actualValue + "'"); + } else if(actualValue != BugsCheckerBuilder.class) { + throw new EPSCommonException("Actual already set '" + actualValue + "'"); } return true; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsListCheckerBuilder.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsListCheckerBuilder.java index 01438746..9f062690 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsListCheckerBuilder.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/BugsListCheckerBuilder.java @@ -54,7 +54,7 @@ public BugsListCheckerBuilder Bug(String subject, Object alternativeValue, Strin throw new EPSCommonException( "Alternative " + alternativeList + " with description " + bugDescription + " are equal to origin " + originList); } - if (this.alternativeSizes.put(alternativeList.size, alternativeList) != null) { + if(alternativeSizes.put(alternativeList.size, alternativeList) != null) { throw new EPSCommonException("Alternative sizes map already contains " + alternativeList); } return this; @@ -62,8 +62,8 @@ public BugsListCheckerBuilder Bug(String subject, Object alternativeValue, Strin @Override public BugsListCheckerBuilder BugAny(String subject, String... categories) { - if (this.originList.size != MISSED_LIST_SIZE.key) { - throw new EPSCommonException("Expected size '" + this.originList + "' is not empty"); + if(originList.size != MISSED_LIST_SIZE.key) { + throw new EPSCommonException("Expected size '" + originList + "' is not empty"); } return Bug(subject, Convention.CONV_PRESENT_OBJECT, categories); } @@ -80,8 +80,8 @@ public BugsListCheckerBuilder Actual(Object obj) { public ExpressionResult validate(Object actualValue) throws KnownBugException { int actualSize = this.actualSize != DEFAULT_LIST.key ? this.actualSize : size(actualValue); - if (this.originList.size == PRESENT_LIST_SIZE.key && actualSize != MISSED_LIST_SIZE.key) { - return new ExpressionResult(false, this.originList.list, ORIGIN_SIZE_MESSAGE, null, null, getDescriptions()); + if(originList.size == PRESENT_LIST_SIZE.key && actualSize != MISSED_LIST_SIZE.key) { + return new ExpressionResult(false, originList.list, ORIGIN_SIZE_MESSAGE, null, null, getDescriptions()); } if (originList.size != actualSize) { @@ -98,13 +98,13 @@ public ExpressionResult validate(Object actualValue) throws KnownBugException { Throwable exception = new EPSCommonException("Expected " + originList + " value is not equal actual " + formatSize(actualSize) + " value"); return new ExpressionResult(false, exception.getMessage(), exception, null, getDescriptions()); } - return new ExpressionResult(false, this.originList.list, ORIGIN_SIZE_MESSAGE, null, null, getDescriptions()); + return new ExpressionResult(false, originList.list, ORIGIN_SIZE_MESSAGE, null, null, getDescriptions()); } @Override public String getCondition() { StringBuilder stringBuilder = new StringBuilder() - .append("Expected: ").append(this.originList).append(", Bugs: ["); + .append("Expected: ").append(originList).append(", Bugs: ["); for (Integer alternativeSize : alternativeSizes.keySet()) { stringBuilder .append("'").append(alternativeSizes.get(alternativeSize).description).append("'") @@ -129,7 +129,7 @@ private static String formatSize(int size) { } private Set getDescriptions() { - return this.alternativeSizes.values().stream() + return alternativeSizes.values().stream() .map(ListWrapper::getDescription) .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); } @@ -140,8 +140,8 @@ private static ExpressionResult createExpressionResult(BugsListCheckerBuilder bu } private boolean isActualEmpty() { - if (this.actualSize != DEFAULT_LIST.key) { - throw new EPSCommonException("Actual already set '" + formatSize(this.actualSize) + "'"); + if(actualSize != DEFAULT_LIST.key) { + throw new EPSCommonException("Actual already set '" + formatSize(actualSize) + "'"); } return true; @@ -238,20 +238,20 @@ public boolean equals(Object o) { ListWrapper that = (ListWrapper) o; return new EqualsBuilder() - .append(this.size, that.size) + .append(size, that.size) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() - .append(this.size) + .append(size) .toHashCode(); } @Override public String toString() { - return formatSize(this.size); + return formatSize(size); } } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/CompareUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/CompareUtil.java index 15321b0e..650efa09 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/CompareUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/CompareUtil.java @@ -29,7 +29,7 @@ * */ @MatrixUtils -@ResourceAliases({ "CompareUtil" }) +@ResourceAliases("CompareUtil") public class CompareUtil extends AbstractCaller { @Description("Tests if a number is in the neighbourhood of base +/- delta (inclusive / non-strict) Usage: #{inRangeBased(actual, base, delta)}") diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/DictionaryValidator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/DictionaryValidator.java index 316e0468..fd996254 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/DictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/DictionaryValidator.java @@ -66,7 +66,7 @@ public static void main(String[] args) { System.out.println("Validating " + dictionary.getName()); IDictionaryStructure structure = dictionaryLoader.load(dictionaryStream); errors = validator.validate(structure, true, null); - if (errors.size() != 0) { + if (!errors.isEmpty()) { hasErrors = true; System.err.println("Errors detected in " + dictionary.getName()); for (Object o:errors) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/EnumReplacer.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/EnumReplacer.java index cf9528fb..3c7f13c6 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/EnumReplacer.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/EnumReplacer.java @@ -258,7 +258,7 @@ public void visit(String fieldName, IMessage value, IFieldStructure complexField EnumReplacingVisitor visitor = new EnumReplacingVisitor(value); messageStructureReader.traverse(visitor, complexField.getFields(), value, MessageStructureReaderHandlerImpl.instance()); - this.message.addField(fieldName, visitor.getMessage()); + message.addField(fieldName, visitor.getMessage()); } @Override @@ -282,7 +282,7 @@ public void visitMessageCollection(String fieldName, List values, IFie list.add(visitor.getMessage()); } - this.message.addField(fieldName, list); + message.addField(fieldName, list); } private void visit(String fieldName, List values, IFieldStructure fldStruct) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/ExecUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/ExecUtil.java index 25c0a72c..a9c1034f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/ExecUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/ExecUtil.java @@ -39,7 +39,7 @@ public static void main (String[] args) private void run(String[] args) { - if (args.length < 2 || args[1].equals("-h") || args[1].equals("--help")) { + if(args.length < 2 || "-h".equals(args[1]) || "--help".equals(args[1])) { usage(); return; } @@ -84,7 +84,7 @@ private void run(String[] args) } } - if (methods.size() == 0) { + if (methods.isEmpty()) { System.out.println("No methods found."); } else { String s = methods.size() == 1 ? "" : "s"; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/FieldKnownBugException.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/FieldKnownBugException.java index 98431650..4155037d 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/FieldKnownBugException.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/FieldKnownBugException.java @@ -73,10 +73,10 @@ public FieldKnownBugException(Set actualDescriptions, Throwable } public Set getActualDescriptions() { - return this.actualDescriptions; + return actualDescriptions; } public boolean isKnownBug() { - return !this.actualDescriptions.isEmpty(); + return !actualDescriptions.isEmpty(); } } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/HelpUtil.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/HelpUtil.java index 3e431c4f..ed98ccab 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/HelpUtil.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/HelpUtil.java @@ -19,6 +19,7 @@ import java.util.Collection; import java.util.Iterator; import java.util.Map; +import java.util.Map.Entry; import com.exactpro.sf.common.messages.structures.IAttributeStructure; import com.exactpro.sf.common.messages.structures.IFieldStructure; @@ -122,14 +123,14 @@ private static int getHashCode(IFieldStructure fieldStructure, StringBuilder has hashCode.append(fieldStructure.getJavaType().value()); } - for (Map.Entry entry : fieldStructure.getAttributes().entrySet()) { + for (Entry entry : fieldStructure.getAttributes().entrySet()) { hashCode.append(entry.getKey()); hashCode.append(entry.getValue().getValue()); } if(!hasChildren){ - for(Map.Entry entry : fieldStructure.getValues().entrySet()){ + for(Entry entry : fieldStructure.getValues().entrySet()){ hashCode.append(entry.getKey()); hashCode.append(entry.getValue().getValue()); } @@ -155,7 +156,7 @@ private static boolean isMapEquals(Map firstMap, Ma return false; } - for(Map.Entry firstEntry : firstMap.entrySet()){ + for(Entry firstEntry : firstMap.entrySet()){ IAttributeStructure secondVal = secondMap.get(firstEntry.getKey()); if(secondVal == null || !firstEntry.getValue().getValue().equals(secondVal.getValue())){ return false; diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/Interner.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/Interner.java index 55df4ad9..4ffa1c70 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/Interner.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/Interner.java @@ -17,6 +17,6 @@ public interface Interner { - public T intern(T object); + T intern(T object); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/JdbcUtils.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/JdbcUtils.java index 4496b5cf..5b052552 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/JdbcUtils.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/JdbcUtils.java @@ -50,23 +50,11 @@ public static void executeTestQuery(String driverClass, String url, String user, } } } - - public static String buildConnectionUrl(String protocol, String subProtocol, String host, String port, String database, String query) { - + + public static String buildConnectionUrl(String protocol, String subProtocol, String host, String port, String database, String query) { String hostFormat = StringUtils.isEmpty(port) ? "%s" : "%s:%s"; - - String format; - - if(StringUtils.isNotEmpty(query)) { - - format = "%s:%s://" + hostFormat + "/%s?%s"; - - } else { - - format = "%s:%s://" + hostFormat + "/%s"; - - } - + String format = "%s:%s://" + hostFormat + (StringUtils.isNotEmpty(query) ? "/%s?%s" : "/%s"); + if (StringUtils.isNotEmpty(port)) { return String.format(format, protocol, subProtocol, host, port, database, query); } else { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/KnownBugPostValidation.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/KnownBugPostValidation.java index df2b2fc7..a0f25166 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/KnownBugPostValidation.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/KnownBugPostValidation.java @@ -24,14 +24,14 @@ import java.util.Map.Entry; import java.util.Set; -import com.exactpro.sf.aml.scriptutil.ExpressionResult; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.exactpro.sf.aml.scriptutil.ExpressionResult; +import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.util.EPSCommonException; -import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; import com.exactpro.sf.comparison.ComparatorSettings; import com.exactpro.sf.comparison.ComparisonResult; import com.exactpro.sf.comparison.ComparisonUtil; @@ -44,7 +44,7 @@ */ public class KnownBugPostValidation extends AbstractPostValidation { - private static Logger logger = LoggerFactory.getLogger(KnownBugPostValidation.class); + private static final Logger logger = LoggerFactory.getLogger(KnownBugPostValidation.class); public KnownBugPostValidation(IPostValidation parentValidator, IMessage filter) { super(parentValidator); @@ -157,11 +157,7 @@ private static String attachOriginReason(ComparisonResult comparisonResult, Expr StringBuilder reasonBuilder = new StringBuilder(mainReason); if (!expressionResult.hasKnownBugsInfo()) { reasonBuilder.append(System.lineSeparator()).append(comparisonResult.getStatus()).append(": "); - if (expressionResult.getCause() != null) { - reasonBuilder.append(expressionResult.getCause().getMessage()); - } else { - reasonBuilder.append(expressionResult.getDescription()); - } + reasonBuilder.append(expressionResult.getCause() != null ? expressionResult.getCause().getMessage() : expressionResult.getDescription()); } return reasonBuilder.toString(); } @@ -171,7 +167,7 @@ private static void setStatus(ComparisonResult comparisonResult, StatusType stat comparisonResult.setException(message != null ? new KnownBugException(message) : null); } - private static enum Status { + private enum Status { PASSED(StatusType.PASSED, 0), CONDITIONALLY_PASSED(StatusType.CONDITIONALLY_PASSED, 1), FAILED(StatusType.FAILED, 2); @@ -179,16 +175,13 @@ private static enum Status { private final StatusType statusType; private final int priority; - private Status(StatusType statusType, int priority) { + Status(StatusType statusType, int priority) { this.statusType = statusType; this.priority = priority; } public Status compareAndGetMax(Status status) { - if (this.priority < status.priority) { - return status; - } - return this; + return priority < status.priority ? status : this; } } @@ -231,7 +224,7 @@ public void calculate(ComparisonResult comparisonResult) { Set descriptions = expressionResult.getActualDescriptions(); comparisonResult.setException(new FieldKnownBugException("It's part of bug(s): " + descriptions, descriptions)); for (BugDescription description : descriptions) { - this.map.get(description).increment(); + map.get(description).increment(); } } else { Throwable cause = expressionResult.getCause(); @@ -245,7 +238,7 @@ public void calculate(ComparisonResult comparisonResult) { } public Set> getIntersections() { - return this.intersections; + return intersections; } public Set getDescriptions() { @@ -262,7 +255,7 @@ public Set searchReproducedBugs() { } Set result = new HashSet<>(); - for (Entry entry : this.map.entrySet()) { + for(Entry entry : map.entrySet()) { if (entry.getValue().getStatus() != KnownBugStatus.NOT_REPRODUCE) { result.add(entry.getKey()); } @@ -272,23 +265,23 @@ public Set searchReproducedBugs() { } public KnownBugInfo get(BugDescription description) { - return this.map.get(description); + return map.get(description); } public boolean isEmpty() { - return this.map.isEmpty(); + return map.isEmpty(); } private void add(ComparisonResult comparisonResult, ExpressionResult expressionResult) { Set descriptions = expressionResult.getPotentialDescriptions(); if (descriptions.size() > 1) { - this.intersections.add(descriptions); + intersections.add(descriptions); } for (BugDescription description : descriptions) { - KnownBugInfo knownBugInfo = this.map.get(description); + KnownBugInfo knownBugInfo = map.get(description); if (knownBugInfo == null) { knownBugInfo = new KnownBugInfo(description); - this.map.put(description, knownBugInfo); + map.put(description, knownBugInfo); } knownBugInfo.add(comparisonResult, expressionResult); } @@ -296,12 +289,12 @@ private void add(ComparisonResult comparisonResult, ExpressionResult expressionR @Override public String toString() { - if (!this.map.isEmpty()) { + if(!map.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(); - if (!this.intersections.isEmpty()) { - stringBuilder.append("intersections: ").append(this.intersections).append(' '); + if(!intersections.isEmpty()) { + stringBuilder.append("intersections: ").append(intersections).append(' '); } - stringBuilder.append("bugs: ").append(this.map.values()); + stringBuilder.append("bugs: ").append(map.values()); return stringBuilder.toString(); } @@ -312,14 +305,14 @@ public String toString() { private static class KnownBugInfo { private final Map comparisonResults = new IdentityHashMap<>() ; private final BugDescription description; - private int count = 0; + private int count; public KnownBugInfo(BugDescription description) { this.description = description; } public void add(ComparisonResult comparisonResult, ExpressionResult expressionResult) { - this.comparisonResults.put(comparisonResult, expressionResult); + comparisonResults.put(comparisonResult, expressionResult); } public void increment() { @@ -327,14 +320,14 @@ public void increment() { } public KnownBugStatus getStatus() { - if (this.count == 0) { + if(count == 0) { return KnownBugStatus.NOT_REPRODUCE; - } else if (this.count < this.comparisonResults.size()) { + } else if(count < comparisonResults.size()) { return KnownBugStatus.PART_REPRODUCE; - } else if (this.count == this.comparisonResults.size()) { + } else if(count == comparisonResults.size()) { return KnownBugStatus.FULL_REPRODUCE; } - throw new EPSCommonException("Internal error, description for bug description " + this.description); + throw new EPSCommonException("Internal error, description for bug description " + description); } public BugDescription getDescription() { @@ -347,14 +340,14 @@ public Set> getComparisonResults() { @Override public String toString() { - return new StringBuilder("'").append(this.description).append("'-(").append(this.count).append('/').append(this.comparisonResults.size()) + return new StringBuilder("'").append(description).append("'-(").append(count).append('/').append(comparisonResults.size()) .append(')').toString(); } } - private static enum KnownBugStatus { + private enum KnownBugStatus { NOT_REPRODUCE, PART_REPRODUCE, - FULL_REPRODUCE; + FULL_REPRODUCE } } \ No newline at end of file diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/LRUMap.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/LRUMap.java index 230a90ed..40036977 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/LRUMap.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/LRUMap.java @@ -24,9 +24,8 @@ public class LRUMap extends LinkedHashMap { private final int maxSize; - public LRUMap(final int maxSize) { - super(); - this.maxSize = maxSize; + public LRUMap(int maxSize) { + this.maxSize = maxSize; } public LRUMap(int maxSize, int initialCapacity, float loadFactor, boolean accessOrder) { diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/MatrixActionsGenerator.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/MatrixActionsGenerator.java index 075d8984..556f0c0f 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/MatrixActionsGenerator.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/MatrixActionsGenerator.java @@ -40,7 +40,7 @@ public static void generate( String genDir, String actionPackage, String messagesPackageName, - final IDictionaryStructure dictionary, + IDictionaryStructure dictionary, String uncheckedFields) throws IOException { @@ -85,8 +85,9 @@ private static void writeFile(String contents, String fileName) { throw new EPSCommonException(e); } finally { try { - if (writer != null) - writer.close(); + if(writer != null) { + writer.close(); + } } catch (IOException e) { throw new EPSCommonException(e); } diff --git a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/UnicodeReader.java b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/UnicodeReader.java index 35243b57..4626df05 100644 --- a/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/UnicodeReader.java +++ b/BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/util/UnicodeReader.java @@ -33,7 +33,7 @@ public class UnicodeReader extends Reader { * @throws IOException If an I/O error occurs. */ public UnicodeReader(InputStream in, String defaultEncoding) throws IOException { - byte bom[] = new byte[BOM_SIZE]; + byte[] bom = new byte[BOM_SIZE]; String encoding; int unread; PushbackInputStream pushbackStream = new PushbackInputStream(in, BOM_SIZE); @@ -62,17 +62,13 @@ public UnicodeReader(InputStream in, String defaultEncoding) throws IOException // Unread bytes if necessary and skip BOM marks. if (unread > 0) { - pushbackStream.unread(bom, (n - unread), unread); + pushbackStream.unread(bom, n - unread, unread); } else if (unread < -1) { pushbackStream.unread(bom, 0, 0); } // Use given encoding. - if (encoding == null) { - reader = new InputStreamReader(pushbackStream); - } else { - reader = new InputStreamReader(pushbackStream, encoding); - } + reader = encoding == null ? new InputStreamReader(pushbackStream) : new InputStreamReader(pushbackStream, encoding); } public String getEncoding() { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestObjectFlusher.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestObjectFlusher.java index 5c5a023b..77644a99 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestObjectFlusher.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestObjectFlusher.java @@ -26,12 +26,12 @@ public class TestObjectFlusher { - private static long timeToRun = 1000 * 10; + private static final long timeToRun = 1000 * 10; @Test public void testOOM() throws Exception { - ObjectFlusher objectFlusher = new ObjectFlusher<>((o) -> { + ObjectFlusher objectFlusher = new ObjectFlusher<>(o -> { System.out.println("try to flush objects " + o.size()); Assert.assertEquals(32, o.size());//check that limit is not exceeded System.out.println("objects flushed"); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestUnsigned.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestUnsigned.java index 87788c98..362873d2 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestUnsigned.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/TestUnsigned.java @@ -156,7 +156,7 @@ public void testUnsignedConvert() { @Test public void testNormalization() { - byte[] array = new byte[] { 0, 1, 2, 3, 4 }; + byte[] array = { 0, 1, 2, 3, 4 }; Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4 }, ServiceUtil.normalisate(array, 4)); Assert.assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, ServiceUtil.normalisate(array, 5)); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestCommonActions.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestCommonActions.java index 00a98315..8f41f5aa 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestCommonActions.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestCommonActions.java @@ -41,9 +41,8 @@ public void init(){ @Test public void testBD() { - Object o = null; - long l = 5l; - o = l; + long l = 5l; + Object o = l; System.out.println(o.getClass().isPrimitive()); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java index d62c6e96..b5e44f87 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestDateUtil.java @@ -20,17 +20,29 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.time.DateTimeException; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.Month; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.TimeZone; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.time.*; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; import com.exactpro.sf.actions.data.DateComponent; import com.exactpro.sf.util.DateTimeUtility; @@ -220,8 +232,8 @@ public void getDateTimeByZoneId() { ":m=" + (30 - minutsDiff)) .minusSeconds(defaultOffsetSeconds); LocalDateTime dateTimeByZoneId = dateUtil.getDateTimeByZoneId("Y=2018:M=3:D=7:h=12:m=30:s=10:ns=123456789", signedOffset); - - Assert.assertEquals("Diff hours = " + hoursDiff + ", minuts = " + minutsDiff, dateTime, dateTimeByZoneId); + + assertEquals("Diff hours = " + hoursDiff + ", minuts = " + minutsDiff, dateTime, dateTimeByZoneId); } } @@ -309,7 +321,7 @@ public void testGetDate() { public void testModifyWithTimezone() { //no DST adjusting TimeZone withoutDst = Arrays.stream(TimeZone.getAvailableIDs()).map(TimeZone::getTimeZone) - .filter((z) -> !z.useDaylightTime() && z.getRawOffset() != 0) + .filter(z -> !z.useDaylightTime() && z.getRawOffset() != 0) .findFirst().orElseThrow(() -> new IllegalArgumentException("no time zone without dst support was found")); LocalDateTime base = LocalDate.now().atTime(12, 0); @@ -321,7 +333,7 @@ public void testModifyWithTimezone() { //with DST adjusting TimeZone withDst = Arrays.stream(TimeZone.getAvailableIDs()).map(TimeZone::getTimeZone) - .filter((z) -> z.useDaylightTime() && z.getRawOffset() != 0) + .filter(z -> z.useDaylightTime() && z.getRawOffset() != 0) .findFirst().orElseThrow(() -> new IllegalArgumentException("no time zone with dst support was found")); compareTo = dateUtil.modifyDateTimeByZoneId(base, "M=1", withDst.getID()).toLocalTime(); @@ -401,64 +413,64 @@ public void testCreateAndModifyAndFormat() { // getLocalDate LocalDate date = dateUtil.getDate("Y=2025:M=2:D=13:h=8:m=24:s=5:ns=111222333"); String dateString = dateUtil.formatDate(date, "yyyyMMdd"); - Assert.assertEquals("20250213", dateString); + assertEquals("20250213", dateString); // getLocalTime LocalTime time = dateUtil.getTime("Y=2025:M=2:D=13:h=8:m=24:s=5:ns=111222333"); dateString = dateUtil.formatTime(time, "HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("08:24:05.111222333", dateString); + assertEquals("08:24:05.111222333", dateString); // toLocalDate with modification date = dateUtil.toDate(dateTime, "Y+1:M-1:D+3:h-1:m=30:s=11:ms=777:mc=666:ns+222"); dateString = dateUtil.formatDate(date, "yyyyMMdd"); - Assert.assertEquals("20260116", dateString); + assertEquals("20260116", dateString); // toLocalDate without modification date = dateUtil.toDate(dateTime); dateString = dateUtil.formatDate(date, "yyyyMMdd"); - Assert.assertEquals("20250213", dateString); + assertEquals("20250213", dateString); // toLocalTime with modification time = dateUtil.toTime(dateTime, "Y+1:M-1:D+3:h-1:m=30:s=11:ns=777666555"); dateString = dateUtil.formatTime(time, "HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("07:30:11.777666555", dateString); + assertEquals("07:30:11.777666555", dateString); // toLocalTime without modification time = dateUtil.toTime(dateTime); dateString = dateUtil.formatTime(time, "HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("08:24:05.111222333", dateString); + assertEquals("08:24:05.111222333", dateString); // toLocalDateTime by merging a LocalDate and LocalTime (with modification) LocalDateTime modifiedDateTime = dateUtil.mergeDateTime(date, time, "Y+1:M-1:D+3:h-1:m=30:s=11:ns=777666555"); dateString = dateUtil.formatDateTime(modifiedDateTime, "yyyyMMdd-HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("20260116-07:30:11.777666555", dateString); + assertEquals("20260116-07:30:11.777666555", dateString); // toLocalDateTime by merging a LocalDate and LocalTime (without modification) modifiedDateTime = dateUtil.mergeDateTime(date, time); dateString = dateUtil.formatDateTime(modifiedDateTime, "yyyyMMdd-HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("20250213-08:24:05.111222333", dateString); + assertEquals("20250213-08:24:05.111222333", dateString); // toLocalDateTime from LocalDate with modification modifiedDateTime = dateUtil.toDateTime(date, "Y+1:M-1:D+3:h+1:m=30:s=11:ns=777666555"); dateString = dateUtil.formatDateTime(modifiedDateTime, "yyyyMMdd-HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("20260116-01:30:11.777666555", dateString); + assertEquals("20260116-01:30:11.777666555", dateString); // toLocalDateTime from LocalDate without modification modifiedDateTime = dateUtil.toDateTime(date); dateString = dateUtil.formatDateTime(modifiedDateTime, "yyyyMMdd-HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("20250213-00:00:00.000000000", dateString); + assertEquals("20250213-00:00:00.000000000", dateString); // toLocalDateTime from LocalTime with modification modifiedDateTime = dateUtil.toDateTime(time, "Y+1:M+1:D+3:h+1:m=30:s=11:ns=777666555"); dateString = dateUtil.formatDateTime(modifiedDateTime, "yyyyMMdd-HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("19710204-09:30:11.777666555", dateString); + assertEquals("19710204-09:30:11.777666555", dateString); // toLocalDateTime from LocalTime without modification modifiedDateTime = dateUtil.toDateTime(time); dateString = dateUtil.formatDateTime(modifiedDateTime, "yyyyMMdd-HH:mm:ss.SSSSSSSSS"); - Assert.assertEquals("19700101-08:24:05.111222333", dateString); + assertEquals("19700101-08:24:05.111222333", dateString); } @Test @@ -466,24 +478,24 @@ public void testDifferenceBetweenTwoDates() { LocalDateTime dateTime = dateUtil.getDateTime("Y=2025:M=2:D=13:h=8:m=24:s=5:ns=111222333"); LocalDateTime modifiedDateTime = dateUtil.modifyDateTime(dateTime, "D+3" ); - Assert.assertEquals(3, dateUtil.diffDateTime(modifiedDateTime, dateTime, "D")); + assertEquals(3, dateUtil.diffDateTime(modifiedDateTime, dateTime, "D")); modifiedDateTime = dateUtil.modifyDateTime(dateTime, "h+3" ); - Assert.assertEquals(3, dateUtil.diffDateTime(modifiedDateTime, dateTime, "h")); + assertEquals(3, dateUtil.diffDateTime(modifiedDateTime, dateTime, "h")); modifiedDateTime = dateUtil.modifyDateTime(dateTime, "h+1:m+1" ); - Assert.assertEquals(61, dateUtil.diffDateTime(modifiedDateTime, dateTime, "m")); + assertEquals(61, dateUtil.diffDateTime(modifiedDateTime, dateTime, "m")); modifiedDateTime = dateUtil.modifyDateTime(dateTime, "m+1:s+1" ); - Assert.assertEquals(61, dateUtil.diffDateTime(modifiedDateTime, dateTime, "s")); + assertEquals(61, dateUtil.diffDateTime(modifiedDateTime, dateTime, "s")); modifiedDateTime = dateUtil.modifyDateTime(dateTime, "s+1:ms+1" ); - Assert.assertEquals(1001, dateUtil.diffDateTime(modifiedDateTime, dateTime, "ms")); + assertEquals(1001, dateUtil.diffDateTime(modifiedDateTime, dateTime, "ms")); } @Test public void testDifferenceBetweenTwoZonedDates() { - String[] dates = new String[] { + String[] dates = { "2011-12-03T10:15:30.123456789+01:00[Europe/Paris]", "2011-12-03T11:15:30.123456789+02:00", "2011-12-03T11:45:30.123456789+02:30", @@ -494,14 +506,14 @@ public void testDifferenceBetweenTwoZonedDates() { for (String subtrahend : dates) { if ( minuend != subtrahend) { for (DateComponent dateComponent : DateComponent.values()) { - Assert.assertEquals("Minuend = " + minuend + " subtrahend = " + subtrahend + " date component = " + dateComponent, + assertEquals("Minuend = " + minuend + " subtrahend = " + subtrahend + " date component = " + dateComponent, 0, dateUtil.diffDateTimeISO(minuend, subtrahend, dateComponent.toString())); } } } } - Assert.assertEquals(1001, dateUtil.diffDateTimeISO("2011-12-03T11:45:30.123456789+02:30", "2011-12-03T10:15:30.122455789+01:00[Europe/Paris]", "mc")); + assertEquals(1001, dateUtil.diffDateTimeISO("2011-12-03T11:45:30.123456789+02:30", "2011-12-03T10:15:30.122455789+01:00[Europe/Paris]", "mc")); } @Test @@ -518,19 +530,19 @@ public void testMergeDateTimes() { // LocalDateTime + LocalDate LocalDateTime modifiedDateTime = dateUtil.mergeDateTime(dateTime, time); - Assert.assertEquals(expectedFromDateTime, modifiedDateTime); + assertEquals(expectedFromDateTime, modifiedDateTime); // LocalDateTime + LocalDateTime modifiedDateTime = dateUtil.mergeDateTime(dateTime, dateUtil.toDateTime(time)); - Assert.assertEquals(expectedFromDateTime, modifiedDateTime); + assertEquals(expectedFromDateTime, modifiedDateTime); // LocalDate + LocalTime modifiedDateTime = dateUtil.mergeDateTime(date, time); - Assert.assertEquals(expectedFromDate, modifiedDateTime); + assertEquals(expectedFromDate, modifiedDateTime); // LocalDate + LocalDateTime modifiedDateTime = dateUtil.mergeDateTime(date, dateUtil.toDateTime(time)); - Assert.assertEquals(expectedFromDate, modifiedDateTime); + assertEquals(expectedFromDate, modifiedDateTime); } @Test @@ -593,7 +605,7 @@ public void testToDateWithoutDelimiters() throws ParseException { @Test public void testNullPointerException() { thrown.expect(NullPointerException.class); - thrown.expectMessage(("Date argument is null")); + thrown.expectMessage("Date argument is null"); dateUtil.toDateTime((String)null); } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestEncodingUtility.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestEncodingUtility.java index 96000feb..4fcaffcf 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestEncodingUtility.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestEncodingUtility.java @@ -19,7 +19,7 @@ import org.junit.Test; public class TestEncodingUtility { - private EncodingUtility encodingUtility= new EncodingUtility(); + private final EncodingUtility encodingUtility= new EncodingUtility(); @Test public void testConvertBase64() throws Exception { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMathUtil.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMathUtil.java index c13532bd..dc3952e1 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMathUtil.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMathUtil.java @@ -25,7 +25,7 @@ public class TestMathUtil { - private MathUtil mathUtil = new MathUtil(); + private final MathUtil mathUtil = new MathUtil(); @Test public void TestMin() throws UtilityCallException, UtilityNotFoundException, InterruptedException { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMessageUtil.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMessageUtil.java index 11949520..950f16e6 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMessageUtil.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMessageUtil.java @@ -26,7 +26,7 @@ import com.exactpro.sf.common.util.EPSCommonException; public class TestMessageUtil { - private MessageUtil messageUtil = new MessageUtil(); + private final MessageUtil messageUtil = new MessageUtil(); @Test public void testFindGroup() { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMiscUtils.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMiscUtils.java index 54cbac67..8e8749c5 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMiscUtils.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/actions/TestMiscUtils.java @@ -26,10 +26,10 @@ import org.junit.Before; import org.junit.Test; -import com.exactpro.sf.common.impl.messages.DefaultMessageFactory; -import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.aml.scriptutil.StaticUtil; import com.exactpro.sf.center.impl.SFLocalContext; +import com.exactpro.sf.common.impl.messages.DefaultMessageFactory; +import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.util.AbstractTest; import com.exactpro.sf.util.FieldKnownBugException; @@ -37,7 +37,7 @@ public class TestMiscUtils extends AbstractTest { private final String intFiled = "int"; private final String stringFiled = "str"; - private MiscUtils miscUtils = null; + private MiscUtils miscUtils; @Before public void before() { @@ -48,14 +48,14 @@ public void before() { public void testIntCheckCount() throws Exception { Collection intCollection = Arrays.asList(4, 1, 2, 3, 4); - Assert.assertTrue(this.miscUtils.checkCount(intCollection, 5, 0)); - Assert.assertFalse(this.miscUtils.checkCount(intCollection, 5, 1)); + Assert.assertTrue(miscUtils.checkCount(intCollection, 5, 0)); + Assert.assertFalse(miscUtils.checkCount(intCollection, 5, 1)); - Assert.assertTrue(this.miscUtils.checkCount(intCollection, 2, 1)); - Assert.assertFalse(this.miscUtils.checkCount(intCollection, 2, 2)); + Assert.assertTrue(miscUtils.checkCount(intCollection, 2, 1)); + Assert.assertFalse(miscUtils.checkCount(intCollection, 2, 2)); - Assert.assertTrue(this.miscUtils.checkCount(intCollection, 4, 2)); - Assert.assertFalse(this.miscUtils.checkCount(intCollection, 4, 0)); + Assert.assertTrue(miscUtils.checkCount(intCollection, 4, 2)); + Assert.assertFalse(miscUtils.checkCount(intCollection, 4, 0)); } @Test @@ -69,12 +69,12 @@ public void testIMessageCheckCount() throws Exception { int count = 2; Collection msgCollection = Collections.nCopies(count, fullItem); - Assert.assertTrue(this.miscUtils.checkCount(msgCollection, fullItem, count)); - Assert.assertTrue(this.miscUtils.checkCount(msgCollection, partItem, count)); - Assert.assertTrue(this.miscUtils.checkCount(msgCollection, empty, 0)); - Assert.assertFalse(this.miscUtils.checkCount(msgCollection, fullItem, 0)); - Assert.assertFalse(this.miscUtils.checkCount(msgCollection, partItem, 0)); - Assert.assertFalse(this.miscUtils.checkCount(msgCollection, empty, count)); + Assert.assertTrue(miscUtils.checkCount(msgCollection, fullItem, count)); + Assert.assertTrue(miscUtils.checkCount(msgCollection, partItem, count)); + Assert.assertTrue(miscUtils.checkCount(msgCollection, empty, 0)); + Assert.assertFalse(miscUtils.checkCount(msgCollection, fullItem, 0)); + Assert.assertFalse(miscUtils.checkCount(msgCollection, partItem, 0)); + Assert.assertFalse(miscUtils.checkCount(msgCollection, empty, count)); IMessage knownBugItem = empty.cloneMessage(); knownBugItem.addField(intFiled, @@ -84,7 +84,7 @@ public void testIMessageCheckCount() throws Exception { FieldKnownBugException fieldKnownBugException = null; try { - this.miscUtils.checkCount(msgCollection, knownBugItem, count); + miscUtils.checkCount(msgCollection, knownBugItem, count); } catch (FieldKnownBugException e) { fieldKnownBugException = e; } @@ -98,7 +98,7 @@ public void testIMessageCheckCount() throws Exception { "um.call(SailfishURI.parse(\"BugsUtils.Expected\"), \"str2\").Bug(\"string bug\", \"str\" )", "um", SFLocalContext.getDefault().getUtilityManager())); try { - this.miscUtils.checkCount(msgCollection, knownBugItem, count); + miscUtils.checkCount(msgCollection, knownBugItem, count); } catch (FieldKnownBugException e) { fieldKnownBugException = e; } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/adapting/impl/TestDefaultAdapterManager.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/adapting/impl/TestDefaultAdapterManager.java index 99f9fe54..dcdb864a 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/adapting/impl/TestDefaultAdapterManager.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/adapting/impl/TestDefaultAdapterManager.java @@ -34,12 +34,13 @@ public interface ILabelProvider public class FileLabelProvider implements ILabelProvider { - private File file; + private final File file; public FileLabelProvider(File file) { - if ( file == null ) - throw new NullPointerException("file"); + if(file == null) { + throw new NullPointerException("file"); + } this.file = file; } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLBlockProcessorTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLBlockProcessorTest.java index 2064b38d..705fc77e 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLBlockProcessorTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLBlockProcessorTest.java @@ -15,6 +15,15 @@ ******************************************************************************/ package com.exactpro.sf.aml; +import java.io.File; +import java.util.Collection; +import java.util.List; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; + import com.exactpro.sf.aml.generator.Alert; import com.exactpro.sf.aml.generator.AlertType; import com.exactpro.sf.aml.iomatrix.AdvancedMatrixReader; @@ -26,20 +35,12 @@ import com.exactpro.sf.scriptrunner.actionmanager.ActionRequirements; import com.exactpro.sf.util.AbstractTest; import com.google.common.collect.ListMultimap; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.File; -import java.util.Collection; -import java.util.List; public class AMLBlockProcessorTest extends AbstractTest { - private static AMLSettings settings = new AMLSettings(); - private static ActionRequirements actionRequirements = Mockito.mock(ActionRequirements.class); - private static ActionInfo actionInfo = Mockito.mock(ActionInfo.class); - private static ActionManager actionManager = Mockito.mock(ActionManager.class); + private static final AMLSettings settings = new AMLSettings(); + private static final ActionRequirements actionRequirements = Mockito.mock(ActionRequirements.class); + private static final ActionInfo actionInfo = Mockito.mock(ActionInfo.class); + private static final ActionManager actionManager = Mockito.mock(ActionManager.class); @BeforeClass public static void init() { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLConverterTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLConverterTest.java index c902fdee..c3c5bea5 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLConverterTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/AMLConverterTest.java @@ -39,11 +39,11 @@ import com.google.common.collect.ListMultimap; public class AMLConverterTest extends AbstractTest { - private static AMLSettings settings = new AMLSettings(); - private static ActionRequirements actionRequirements = Mockito.mock(ActionRequirements.class); - private static ActionInfo actionInfo = Mockito.mock(ActionInfo.class); - private static ActionInfo actionInfoVoid = Mockito.mock(ActionInfo.class); - private static ActionManager actionManager = Mockito.mock(ActionManager.class); + private static final AMLSettings settings = new AMLSettings(); + private static final ActionRequirements actionRequirements = Mockito.mock(ActionRequirements.class); + private static final ActionInfo actionInfo = Mockito.mock(ActionInfo.class); + private static final ActionInfo actionInfoVoid = Mockito.mock(ActionInfo.class); + private static final ActionManager actionManager = Mockito.mock(ActionManager.class); @SuppressWarnings("serial") @BeforeClass diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReaderTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReaderTest.java index ca76ca88..a0cf0eab 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReaderTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixReaderTest.java @@ -32,7 +32,7 @@ import com.exactpro.sf.aml.AMLException; public class AdvancedMatrixReaderTest { - private File csv = new File("src/test/resources/aml/iomatrix/TestDefineHeader.csv"); + private final File csv = new File("src/test/resources/aml/iomatrix/TestDefineHeader.csv"); private final String PATH = "src/test/resources/aml/iomatrix/"; private final String XLSX_MATRIX = "Execl_2007_2013.xlsx"; private final String XLS_MATRIX = "Execl_97_2003.xls"; @@ -83,7 +83,7 @@ public void testDefineHeaderCsv() throws Exception { } private void checkMap(File file) throws Exception { - try (AdvancedMatrixReader reader = new AdvancedMatrixReader(file);) { + try (AdvancedMatrixReader reader = new AdvancedMatrixReader(file)) { Assert.assertEquals(asList("#1", "#2", "#3", "#4", "#action", "6", "7", "8", "9", "#10"), reader.getHeader()); @@ -116,7 +116,7 @@ private void checkMap(File file) throws Exception { public void someTest() throws Exception{ try (AdvancedMatrixReader reader = new AdvancedMatrixReader(new File("/home/sergey.smirnov/coding/TMP/validTests1AFTERSAVE.csv"))) { while (reader.hasNext()) { - for (Map.Entry cell:reader.readCells().entrySet()) { + for (Entry cell:reader.readCells().entrySet()) { if (!cell.getValue().getValue().isEmpty()) { System.out.print(cell.getKey() + " = " + cell.getValue() + ", "); } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriterTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriterTest.java index ef3b44c4..8fec2570 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriterTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/AdvancedMatrixWriterTest.java @@ -32,10 +32,10 @@ public class AdvancedMatrixWriterTest { // TODO 1.8 fails - private static List> rows = new ArrayList<>(); + private static final List> rows = new ArrayList<>(); - private String tmpDir = "build" + File.separator + "tmp"; - private File csv = new File(tmpDir + File.separator + "test.csv"); + private final String tmpDir = "build" + File.separator + "tmp"; + private final File csv = new File(tmpDir + File.separator + "test.csv"); static { Map first = new HashMap<>(); @@ -60,7 +60,7 @@ public class AdvancedMatrixWriterTest { public void test() throws Exception { try (AdvancedMatrixWriter writer = new AdvancedMatrixWriter(csv, - Arrays.asList(new SimpleCell[] { new SimpleCell("#action"), new SimpleCell("value") }));) { + Arrays.asList(new SimpleCell[] { new SimpleCell("#action"), new SimpleCell("value") }))) { writer.writeCells(rows.get(0)); // Define header for row with new fields diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReaderTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReaderTest.java index d9b26e62..aaa20708 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReaderTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixReaderTest.java @@ -15,7 +15,8 @@ ******************************************************************************/ package com.exactpro.sf.aml.iomatrix; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; import java.io.FileInputStream; import java.util.Arrays; @@ -130,7 +131,7 @@ public void get() { public void testReadFromNoMarkSupportInputStream() { try (CSVMatrixReader reader = new CSVMatrixReader( new FileInputStream("src/test/resources/aml/iomatrix/testcsv.csv"))) { - String[] expectedCells = new String[]{"1494574053", "1000199004", "975277106", "-900841273", "-1205771794", + String[] expectedCells = { "1494574053", "1000199004", "975277106", "-900841273", "-1205771794", "-436980907","-544962948","-1060190917","1082171287","284431925"}; String[] actualCells = reader.read(); assertArrayEquals("Wrong reading line", expectedCells, actualCells); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixWriterTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixWriterTest.java index 15fb0446..5bf76dea 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixWriterTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/CSVMatrixWriterTest.java @@ -25,9 +25,9 @@ public class CSVMatrixWriterTest { - private String tmpDir = System.getProperty("java.io.tmpdir"); - private String fileName = tmpDir + File.separator + "test.csv"; - private File tmpFile = new File(fileName); + private final String tmpDir = System.getProperty("java.io.tmpdir"); + private final String fileName = tmpDir + File.separator + "test.csv"; + private final File tmpFile = new File(fileName); @Test public void testCSVMatrixWriterString() { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriterTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriterTest.java index cc98bb18..14e2a1a4 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriterTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/iomatrix/ExcelMatrixWriterTest.java @@ -36,11 +36,11 @@ public class ExcelMatrixWriterTest { - private String tmpDir = System.getProperty("java.io.tmpdir"); - private String fileName = tmpDir + File.separator + "test.xls"; - private String fileNameX = tmpDir + File.separator + "test.xlsx"; - private File tmpFile = new File(fileName); - private File tmpFileX = new File(fileNameX); + private final String tmpDir = System.getProperty("java.io.tmpdir"); + private final String fileName = tmpDir + File.separator + "test.xls"; + private final String fileNameX = tmpDir + File.separator + "test.xlsx"; + private final File tmpFile = new File(fileName); + private final File tmpFileX = new File(fileNameX); @Test public void testExcelMatrixWriterStringBoolean() { @@ -134,7 +134,7 @@ public void testExcelMatrixWriterOutputStreamBooleanStringXlsx() { public void testWriteCells() { HSSFWorkbook fakeWorkbook = new HSSFWorkbook(); CellStyle style = fakeWorkbook.createCellStyle(); - HSSFColor myColor = HSSFColor.HSSFColorPredefined.RED.getColor(); + HSSFColor myColor = HSSFColorPredefined.RED.getColor(); try (ExcelMatrixWriter e = new ExcelMatrixWriter(new FileOutputStream(tmpFile), false, "someName")) { SimpleCell[] cells = new SimpleCell[10]; @@ -312,6 +312,6 @@ public void testCloseXlsx() { @Test public void testFlush() { - assert (true); + assert true; } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/script/actions/WaitActionTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/script/actions/WaitActionTest.java index c83820ad..b3341943 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/script/actions/WaitActionTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/script/actions/WaitActionTest.java @@ -52,7 +52,7 @@ public void init() { @Test public void TestWaitForApplicationMessage() throws Exception { - IMessage mInstrumentDirectoryDerivatives = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage mInstrumentDirectoryDerivatives = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); mInstrumentDirectoryDerivatives.addField("InstrumentClassId", "AAA"); MetaContainer metaContainer = new MetaContainer(); @@ -62,7 +62,7 @@ public void TestWaitForApplicationMessage() throws Exception IServiceHandler handler = new CollectorServiceHandler(); ISession isession = new FakeSession(null); - IMessage m = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m.addField("InstrumentClassId", "AAA"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m); @@ -73,7 +73,7 @@ public void TestWaitForApplicationMessage() throws Exception @Test public void TestWaitForAdministrationMessage() throws Exception { - IMessage mLogout = this.messageFactory.createMessage("Logout", "namespace"); + IMessage mLogout = messageFactory.createMessage("Logout", "namespace"); mLogout.addField("userid", "AAA"); MetaContainer metaContainer = new MetaContainer(); @@ -83,7 +83,7 @@ public void TestWaitForAdministrationMessage() throws Exception IServiceHandler handler = new CollectorServiceHandler(); ISession isession = new FakeSession(null); - IMessage m = this.messageFactory.createMessage("Logout", "namespace"); + IMessage m = messageFactory.createMessage("Logout", "namespace"); m.addField("userid", "AAA"); handler.putMessage(isession, ServiceHandlerRoute.FROM_ADMIN, m); @@ -94,13 +94,13 @@ public void TestWaitForAdministrationMessage() throws Exception @Test public void TestWaitForMessageWithUpdatedCheckPointValid() throws Exception { - IMessage f1 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f1.addField("InstrumentClassId", "AAA"); - IMessage f2 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f2.addField("InstrumentClassId", "BBB"); - IMessage f3 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f3.addField("InstrumentClassId", "CCC"); - IMessage f4 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f4.addField("InstrumentClassId", "DDD"); MetaContainer metaContainer = new MetaContainer(); @@ -113,19 +113,19 @@ public void TestWaitForMessageWithUpdatedCheckPointValid() throws Exception CheckPoint checkPoint = new CheckPoint(true); handler.registerCheckPoint(isession, ServiceHandlerRoute.FROM_APP, checkPoint); - IMessage m1 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m1.addField("InstrumentClassId", "AAA"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m1); - IMessage m2 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m2.addField("InstrumentClassId", "BBB"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m2); - IMessage m3 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m3.addField("InstrumentClassId", "CCC"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m3); - IMessage m4 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m4.addField("InstrumentClassId", "DDD"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m4); @@ -154,13 +154,13 @@ public void TestWaitForMessageWithUpdatedCheckPointValid() throws Exception public void TestWaitForMessageWithUpdatedCheckPointInvalid() throws Exception { // create filters - IMessage f1 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f1.addField("InstrumentClassId", "AAA"); - IMessage f2 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f2.addField("InstrumentClassId", "BBB"); - IMessage f3 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f3.addField("InstrumentClassId", "CCC"); - IMessage f4 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f4.addField("InstrumentClassId", "DDD"); MetaContainer metaContainer = new MetaContainer(); @@ -174,19 +174,19 @@ public void TestWaitForMessageWithUpdatedCheckPointInvalid() throws Exception CheckPoint checkPoint = new CheckPoint(true); handler.registerCheckPoint(isession, ServiceHandlerRoute.FROM_APP, checkPoint); - IMessage m1 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m1.addField("InstrumentClassId", "AAA"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m1); - IMessage m2 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m2.addField("InstrumentClassId", "BBB"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m2); - IMessage m3 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m3.addField("InstrumentClassId", "CCC"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m3); - IMessage m4 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m4.addField("InstrumentClassId", "DDD"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m4); @@ -215,13 +215,13 @@ public void TestWaitForMessageWithUpdatedCheckPointInvalid() throws Exception @Test public void TestWaitForMessageWithUpdatedCheckPointInvalid2() throws Exception { - IMessage f1 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f1.addField("InstrumentClassId", "AAA"); - IMessage f2 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f2.addField("InstrumentClassId", "BBB"); - IMessage f3 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f3.addField("InstrumentClassId", "CCC"); - IMessage f4 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage f4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); f4.addField("InstrumentClassId", "DDD"); MetaContainer metaContainer = new MetaContainer(); @@ -231,22 +231,22 @@ public void TestWaitForMessageWithUpdatedCheckPointInvalid2() throws Exception CollectorServiceHandler handler = new CollectorServiceHandler(); ISession isession = new FakeSession(null); - IMessage m1 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m1.addField("InstrumentClassId", "AAA"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m1); CheckPoint checkPoint = new CheckPoint(true); handler.registerCheckPoint(isession, ServiceHandlerRoute.FROM_APP, checkPoint); - IMessage m2 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m2.addField("InstrumentClassId", "BBB"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m2); - IMessage m3 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m3.addField("InstrumentClassId", "CCC"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m3); - IMessage m4 = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m4.addField("InstrumentClassId", "DDD"); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m4); @@ -270,7 +270,7 @@ public void TestWaitForMessageWithUpdatedCheckPointInvalid2() throws Exception @Test public void TestCountApplicationMessages() throws Exception { - IMessage mInstrumentDirectoryDerivatives = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage mInstrumentDirectoryDerivatives = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); mInstrumentDirectoryDerivatives.addField("InstrumentClassId", "PRY"); MetaContainer metaContainer = new MetaContainer(); @@ -280,10 +280,10 @@ public void TestCountApplicationMessages() throws Exception IServiceHandler handler = new CollectorServiceHandler(); ISession isession = new FakeSession(null); - IMessage m = this.messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); + IMessage m = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace"); m.addField("InstrumentClassId", "PRY"); - IMessage addOrder = this.messageFactory.createMessage("AddOrder", "namespace"); + IMessage addOrder = messageFactory.createMessage("AddOrder", "namespace"); addOrder.addField("Instrument", 1); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, addOrder); @@ -292,7 +292,7 @@ public void TestCountApplicationMessages() throws Exception handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, addOrder.cloneMessage()); } - addOrder = this.messageFactory.createMessage("AddOrder", "namespace"); + addOrder = messageFactory.createMessage("AddOrder", "namespace"); addOrder.addField("Instrument", 2); handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, addOrder); @@ -304,7 +304,7 @@ public void TestCountApplicationMessages() throws Exception @Test public void TestCountAdministrationMessages() throws Exception { - IMessage mLogout = this.messageFactory.createMessage("Logout", "namespace"); + IMessage mLogout = messageFactory.createMessage("Logout", "namespace"); mLogout.addField("userid", "AAA"); MetaContainer metaContainer = new MetaContainer(); @@ -314,10 +314,10 @@ public void TestCountAdministrationMessages() throws Exception IServiceHandler handler = new CollectorServiceHandler(); ISession isession = new FakeSession(null); - IMessage m = this.messageFactory.createMessage("Logout", "namespace"); + IMessage m = messageFactory.createMessage("Logout", "namespace"); m.addField("userid", "AAA"); - IMessage addOrder = this.messageFactory.createMessage("AddOrder", "namespace"); + IMessage addOrder = messageFactory.createMessage("AddOrder", "namespace"); addOrder.addField("Instrument", 1); handler.putMessage(isession, ServiceHandlerRoute.FROM_ADMIN, addOrder); @@ -326,7 +326,7 @@ public void TestCountAdministrationMessages() throws Exception handler.putMessage(isession, ServiceHandlerRoute.FROM_ADMIN, addOrder.cloneMessage()); } - addOrder = this.messageFactory.createMessage("AddOrder", "namespace"); + addOrder = messageFactory.createMessage("AddOrder", "namespace"); addOrder.addField("Instrument", 2); handler.putMessage(isession, ServiceHandlerRoute.FROM_ADMIN, addOrder); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/LegReorderTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/LegReorderTest.java index f526f67b..d1f89457 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/LegReorderTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/LegReorderTest.java @@ -29,7 +29,7 @@ public class LegReorderTest extends AbstractTest { - private final static String NS = "namespace"; + private static final String NS = "namespace"; @SuppressWarnings("unchecked") @Test @@ -178,7 +178,7 @@ public static IMessage fromString(String name, String str, Object...nested) { MapMessage result = new MapMessage(NS, name); if (str != null) { - while (str.length() != 0) { + while (!str.isEmpty()) { List pair = pareseKV(str); String key = pair.get(0); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/MessageCountTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/MessageCountTest.java index 89403446..fd94d99f 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/MessageCountTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/MessageCountTest.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import org.junit.Before; import org.junit.Test; @@ -29,7 +30,7 @@ import com.exactpro.sf.aml.scriptutil.MessageCount.Operation; public class MessageCountTest { - private Map> inputStrings = new HashMap>(); + private final Map> inputStrings = new HashMap>(); @Before public void before() throws Exception { @@ -98,7 +99,7 @@ public void testIsValidExpression() throws Exception { checkIsValidExpression("${ref.field1} + ${ref.field2} + 100"); checkIsValidExpression("${ref.field1} + ${ref.field2} + ${ref.field3}"); - for (Operation operation : MessageCount.Operation.values()) { + for (Operation operation : Operation.values()) { checkIsValidExpression(operation.getValue() + " ${ref.field}"); } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/StaticUtilTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/StaticUtilTest.java index d111c26f..89e5d119 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/StaticUtilTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/aml/scriptutil/StaticUtilTest.java @@ -55,7 +55,7 @@ public void testSimpleFilterWithInsertMvel() throws Exception { IMessage iMessage = new MapMessage("namespace", "name"); iMessage.addField("ref", refMessage); - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "mes.ref.value + mes.ref.valu + mes.ref.val + mes.ref.va + mes.ref.v > x", "mes", iMessage); + IFilter filter = StaticUtil.filter(0, null, "mes.ref.value + mes.ref.valu + mes.ref.val + mes.ref.va + mes.ref.v > x", "mes", iMessage); String condition = filter.getCondition(); Assert.assertEquals("\"1\" + \"2\" + \"3\" + \"4\" + \"5\" > x", condition); @@ -72,7 +72,7 @@ public void testSimpleFilterWithInsertMvel_2() throws Exception { IMessage iMessage = new MapMessage("namespace", "name"); iMessage.addField("ref", lst); - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "mes.ref[0].val + mes.ref[3].val > x", "mes", iMessage); + IFilter filter = StaticUtil.filter(0, null, "mes.ref[0].val + mes.ref[3].val > x", "mes", iMessage); String condition = filter.getCondition(); Assert.assertEquals("0 + 3 > x", condition); @@ -89,7 +89,7 @@ public void testSimpleFilterWithInsertMvel_simpleCollections() throws Exception IMessage iMessage = new MapMessage("namespace", "name"); iMessage.addField("ref", Arrays.asList(1, 2, 3, 4, 5)); - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "mes.ref[0] + mes.ref[3] > x", "mes", iMessage); + IFilter filter = StaticUtil.filter(0, null, "mes.ref[0] + mes.ref[3] > x", "mes", iMessage); String condition = filter.getCondition(); Assert.assertEquals("1 + 4 > x", condition); @@ -101,7 +101,7 @@ public void testFilter() throws Exception { IMessage refMessage = new MapMessage("namespace1", "name1"); refMessage.addField("val", value); iMessage.addField("ref", refMessage); - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "mes.ref.val", "mes", iMessage); + IFilter filter = StaticUtil.filter(0, null, "mes.ref.val", "mes", iMessage); String condition = filter.getCondition(); Assert.assertEquals("\"" + value + "\"", condition); } @@ -115,7 +115,7 @@ public void testFilterWithArray() throws Exception { ref.addField("subRef", Collections.singletonList(refMessage1)); IMessage mes = new MapMessage("mes", "mes"); mes.addField("ref", ref); - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "mes.ref.subRef[0].val", "mes", mes); + IFilter filter = StaticUtil.filter(0, null, "mes.ref.subRef[0].val", "mes", mes); String condition = filter.getCondition(); Assert.assertEquals("\"" + value + "\"", condition); } @@ -128,7 +128,7 @@ public void testFilterHashMap() throws Exception { msg.addField("val", value); map.put("msg", msg); - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "map.msg.val", "map", map); + IFilter filter = StaticUtil.filter(0, null, "map.msg.val", "map", map); String condition = filter.getCondition(); Assert.assertEquals("\"" + value + "\"", condition); } @@ -139,14 +139,13 @@ public void testFilter_TernaryOperator() throws Exception { Integer value = 123; IMessage request = new MapMessage("namespace", "name"); request.addField("ReceivedMarketDepth", value); - StaticUtil.IFilter filter = null; - filter = StaticUtil.filter( + IFilter filter = StaticUtil.filter( 0, null, - "v0.ReceivedMarketDepth != '#' ? x == v1.ReceivedMarketDepth : x == null", - "v0", request, - "v1", request + "v0.ReceivedMarketDepth != '#' ? x == v1.ReceivedMarketDepth : x == null", + "v0", request, + "v1", request ); Assert.assertEquals("123 != '#' ? x == 123 : x == null", filter.getCondition()); @@ -167,7 +166,7 @@ public void testFilter_StringEscape() throws Exception { IMessage request = new MapMessage("namespace", "name"); request.addField("ReceivedMarketDepth", value); - StaticUtil.IFilter filter = StaticUtil.filter( + IFilter filter = StaticUtil.filter( 0, null, "v0.ReceivedMarketDepth!='v0.ReceivedMarketDepth'", @@ -192,7 +191,7 @@ public void testFilter_UtilFn() throws Exception { IMessage request = new MapMessage("namespace", "name"); request.addField("OrderQty", value); - StaticUtil.IFilter filter = StaticUtil.filter( + IFilter filter = StaticUtil.filter( 0, null, "com.exactpro.sf.actions.MathUtil.roundZero(Double.valueOf(s1), x, v0.OrderQty, )", @@ -204,14 +203,14 @@ public void testFilter_UtilFn() throws Exception { @Test public void testSimpleFilter_TernaryOperator() throws Exception { - StaticUtil.IFilter filter = StaticUtil.simpleFilter(0, null, "2==3 ? 3 : 4"); + IFilter filter = StaticUtil.simpleFilter(0, null, "2==3 ? 3 : 4"); String condition = filter.getCondition(); Assert.assertEquals("4", condition); } @Test public void testFilter_IncorrectReference() throws Exception { - StaticUtil.IFilter filter = StaticUtil.filter(0, null, "v0.ReceivedMarketDepth != 1"); + IFilter filter = StaticUtil.filter(0, null, "v0.ReceivedMarketDepth != 1"); Assert.assertEquals("v0.ReceivedMarketDepth != 1", filter.getCondition()); } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/impl/messages/TestStrictMessageWrapper.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/impl/messages/TestStrictMessageWrapper.java index bca0e3cd..68f53076 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/impl/messages/TestStrictMessageWrapper.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/impl/messages/TestStrictMessageWrapper.java @@ -44,8 +44,8 @@ */ public class TestStrictMessageWrapper { private static IDictionaryStructure dictionary; - private static String dictionaryName = "/messages/strictMessage.xml"; - private String namespace = "TestStrictmessage"; + private static final String dictionaryName = "/messages/strictMessage.xml"; + private final String namespace = "TestStrictmessage"; @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -104,7 +104,7 @@ public void testPositive() { // add single element in collection strictMsg.addField("double_collection", 10.1d); - System.out.println(strictMsg.toString()); + System.out.println(strictMsg); } @Test diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/messages/CreateIMessageVisitor.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/messages/CreateIMessageVisitor.java index 93811049..87d7a970 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/messages/CreateIMessageVisitor.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/messages/CreateIMessageVisitor.java @@ -27,8 +27,8 @@ import com.exactpro.sf.util.DateTimeUtility; public class CreateIMessageVisitor extends DefaultMessageStructureVisitor { - private IMessageFactory factory; - private IMessage imessage; + private final IMessageFactory factory; + private final IMessage imessage; public IMessage getImessage() { return imessage; diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/profiler/ProfilerTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/profiler/ProfilerTest.java index 2c859f85..853d707e 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/profiler/ProfilerTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/profiler/ProfilerTest.java @@ -21,7 +21,7 @@ public class ProfilerTest { private static final String trace1 = "1"; private static final String trace2 = "2"; - public static final String[] tracesNames = new String[]{trace1, trace2}; + public static final String[] tracesNames = { trace1, trace2 }; @Test public void simpleTest() throws InterruptedException { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/util/TestGenericConverter.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/util/TestGenericConverter.java index bc7a2e1d..b76d4843 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/util/TestGenericConverter.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/common/util/TestGenericConverter.java @@ -36,11 +36,11 @@ public final class TestGenericConverter extends EPSTestCase { private static final Logger logger = LoggerFactory.getLogger(TestGenericConverter.class); - private static Charset charsetISO_8859 = Charset.forName("ISO-8859-1"); + private static final Charset charsetISO_8859 = Charset.forName("ISO-8859-1"); @SuppressWarnings("unused") - private static CharsetDecoder charsetDecoder = charsetISO_8859.newDecoder(); - private static CharsetEncoder charsetEncoder = charsetISO_8859.newEncoder(); + private static final CharsetDecoder charsetDecoder = charsetISO_8859.newDecoder(); + private static final CharsetEncoder charsetEncoder = charsetISO_8859.newEncoder(); @Test public void testConvertStringToArray() throws Exception @@ -705,7 +705,7 @@ public void testConvertByteBufferToAnyBigDecimal() throws Exception byte[] encoded = GenericConverter.convertUnsignedNumericToArray(length, model, precision); BigDecimal fromByteArray = GenericConverter.convertByteArrayToAnyDecimal(length, encoded, precision ); - Assert.assertTrue( "Unsigned BigDecimal values does not equal.", 0 == model.compareTo( fromByteArray )); + Assert.assertTrue("Unsigned BigDecimal values does not equal.", model.compareTo(fromByteArray) == 0); model = new BigDecimal( "12344321.9876" ); encoded = GenericConverter.convertSignedNumericToArray(length, model, precision); @@ -713,7 +713,7 @@ public void testConvertByteBufferToAnyBigDecimal() throws Exception BigDecimal zero = new BigDecimal( "0.0" ); BigDecimal substr = model.subtract( fromByteArray ); - boolean zeroResult = ( 0 == substr.compareTo( zero )); + boolean zeroResult = substr.compareTo(zero) == 0; Assert.assertTrue( "Positive Signed BigDecimal values does not equal.", zeroResult ); model = new BigDecimal( "-2344321.9876" ); @@ -722,7 +722,7 @@ public void testConvertByteBufferToAnyBigDecimal() throws Exception zero = new BigDecimal( "0.0" ); substr = model.subtract( fromByteArray ); - zeroResult = ( 0 == substr.compareTo( zero )); + zeroResult = substr.compareTo(zero) == 0; Assert.assertTrue( "Negative Signed BigDecimal values does not equal.", zeroResult ); logger.info("Test of GenericConverter.FromByteArrayToAnyDecimal(): PASSED."); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/TestMessageComparator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/TestMessageComparator.java index 29a81bb5..6b313964 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/TestMessageComparator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/TestMessageComparator.java @@ -50,7 +50,7 @@ @SuppressWarnings("deprecation") public class TestMessageComparator extends AbstractTest { - private final static Set uncheckedFields = new HashSet<>(); + private static final Set uncheckedFields = new HashSet<>(); static { uncheckedFields.add("BeginString"); @@ -71,8 +71,8 @@ public class TestMessageComparator extends AbstractTest { @Test public void testNullAndNotNull() { - IMessage message = this.messageFactory.createMessage("name", "namespace"); - IMessage filter = this.messageFactory.createMessage("name", "namespace"); + IMessage message = messageFactory.createMessage("name", "namespace"); + IMessage filter = messageFactory.createMessage("name", "namespace"); IFilter nullFilter = StaticUtil.nullFilter(0, null); IFilter notNullFilter = StaticUtil.notNullFilter(0, null); @@ -108,8 +108,8 @@ public void testPrecision() { String failed = StatusType.FAILED.name(); String passed = StatusType.PASSED.name(); - IMessage message = this.messageFactory.createMessage("name", "namespace"); - IMessage filter = this.messageFactory.createMessage("name", "namespace"); + IMessage message = messageFactory.createMessage("name", "namespace"); + IMessage filter = messageFactory.createMessage("name", "namespace"); message.addField("float" + failed, 1.001f); filter.addField("float" + failed, 1.002f); @@ -277,83 +277,71 @@ private ComparisonResult doUnexpectedCompareIMessage(String failUnexpected, int { //System.out.println("------- failUnexpected="+failUnexpected+", expected="+expected+", actual="+actual); String namespace = "namespace"; - IMessage message; - IMessage filter; IMessage noPartyIDs; - IMessage header; - IMessage trailer; - List group; - { - message = new MapMessage(namespace, "ExecutionReport"); - header = new MapMessage(namespace, "header"); - trailer = new MapMessage(namespace, "trailer"); - - header.addField("BeginString", "FIXT.1.1"); - header.addField("BodyLength", 20); - header.addField("MsgType", "8"); - header.addField("MsgSeqNum", 1); - header.addField("TargetCompID", "TCI"); - header.addField("SenderCompID", "SCI"); - trailer.addField("CheckSum", 10); - message.addField("header", header); - message.addField("trailer", trailer); - message.addField("ClOrdID", "ClOrdID"); - - group = new ArrayList<>(actual); - for (int i=0; i group = new ArrayList<>(actual); + for(int i = 0; i < actual; i++) { + noPartyIDs = new MapMessage(namespace, "NoPartyIDs"); + noPartyIDs.addField("PartyID", "PartyID"); + noPartyIDs.addField("PartyIDSource", 'B'); + noPartyIDs.addField("PartyRole", 1); + group.add(noPartyIDs); + } + message.addField("group_NoPartyIDs", group); + + IMessage filter = new MapMessage(namespace, "ExecutionReport"); + header = new MapMessage(namespace, "header"); + trailer = new MapMessage(namespace, "trailer"); + + header.addField("BeginString", "FIXT.1.1"); + header.addField("BodyLength", 21); + header.addField("MsgType", "8"); + header.addField("MsgSeqNum", 2); + header.addField("TargetCompID", "TCI*"); + trailer.addField("CheckSum", 11); + filter.addField("header", header); + filter.addField("trailer", trailer); + + switch(filterType) { + case VALUE: + group = new ArrayList<>(expected); + for(int i = 0; i < expected; i++) { noPartyIDs = new MapMessage(namespace, "NoPartyIDs"); noPartyIDs.addField("PartyID", "PartyID"); - noPartyIDs.addField("PartyIDSource", 'B'); noPartyIDs.addField("PartyRole", 1); group.add(noPartyIDs); } - message.addField("group_NoPartyIDs", group); - - } - - { - filter = new MapMessage(namespace, "ExecutionReport"); - header = new MapMessage(namespace, "header"); - trailer = new MapMessage(namespace, "trailer"); - - header.addField("BeginString", "FIXT.1.1"); - header.addField("BodyLength", 21); - header.addField("MsgType", "8"); - header.addField("MsgSeqNum", 2); - header.addField("TargetCompID", "TCI*"); - trailer.addField("CheckSum", 11); - filter.addField("header", header); - filter.addField("trailer", trailer); - - switch (filterType) { - case VALUE: - group = new ArrayList<>(expected); - for (int i=0; i map = new HashMap<>(); + HashMap map = new HashMap<>(); map.put("OldGrossConsideration", new Boolean(true)); - mEXECUTION_REPORT = messageFactory.createMessage("EXECUTION_REPORT", "namespace"); + IMessage mEXECUTION_REPORT = messageFactory.createMessage("EXECUTION_REPORT", "namespace"); mEXECUTION_REPORT.addField("CounterParty", "CounterParty0"); mEXECUTION_REPORT.addField("OrderStatus", "OrderStatus.Filled"); mEXECUTION_REPORT.addField("Origin", 1); @@ -454,7 +441,7 @@ public void testDSGComparing() mEXECUTION_REPORT.addField("ContingentValue", 0); mEXECUTION_REPORT.addField("ContingentCondition", -1); mEXECUTION_REPORT.addField("TraderIndex", 5710); - mEXECUTION_REPORT.addField("SourceGatewayType", new java.lang.Byte("0")); + mEXECUTION_REPORT.addField("SourceGatewayType", new Byte("0")); mEXECUTION_REPORT.addField("ExecType", "ExecType.Fill"); mEXECUTION_REPORT.addField("Symbol", "AKPS1"); mEXECUTION_REPORT.addField("AllocatedSize", 0); @@ -493,7 +480,7 @@ public void testDSGComparing() mEXECUTION_REPORT.addField("OnlyForMarketDataSystem", "OnlyForMarketDataSystem.RegularTrade"); mEXECUTION_REPORT.addField("Qualifier", "Qualifier.Conventional"); mEXECUTION_REPORT.addField("SideQualifier", "SideQualifier.BUY"); - mEXECUTION_REPORT.addField("CrossType", new java.lang.Byte("0")); + mEXECUTION_REPORT.addField("CrossType", new Byte("0")); mEXECUTION_REPORT.addField("TransactTime", "*"); mEXECUTION_REPORT.addField("RoutingSeq", -999L); mEXECUTION_REPORT.addField("ClearingAccountType", "ClearingAccountType.House"); @@ -510,14 +497,13 @@ public void testDSGComparing() @Test public void testComparingWithNegativeMap() { - IMessage mEXECUTION_REPORT; - HashMap map = new HashMap<>(); + HashMap map = new HashMap<>(); map.put("OldGrossConsideration", true); map.put("LevelID", true); map.put("OrderStatus", true); - mEXECUTION_REPORT = this.messageFactory.createMessage("EXECUTION_REPORT", "namespace"); + IMessage mEXECUTION_REPORT = messageFactory.createMessage("EXECUTION_REPORT", "namespace"); mEXECUTION_REPORT.addField("CounterParty", "CounterParty"); mEXECUTION_REPORT.addField("OrderStatus", "OrderStatus.Filled"); mEXECUTION_REPORT.addField("Origin", 1); @@ -542,14 +528,13 @@ public void testComparingWithNegativeMap() @Test public void testComparingPresentMissedEnums() { - IMessage mEXECUTION_REPORT; - HashMap map = new HashMap<>(); + HashMap map = new HashMap<>(); map.put("OldGrossConsideration", true); map.put("LevelID", true); map.put("OrderStatus", true); - mEXECUTION_REPORT = this.messageFactory.createMessage("EXECUTION_REPORT", "namespace"); + IMessage mEXECUTION_REPORT = messageFactory.createMessage("EXECUTION_REPORT", "namespace"); mEXECUTION_REPORT.addField("CounterParty", "CounterParty"); mEXECUTION_REPORT.addField("OrderStatus", "OrderStatus.Filled"); mEXECUTION_REPORT.addField("Origin", 1); @@ -565,8 +550,7 @@ public void testComparingPresentMissedEnums() { ComparatorSettings compSettings = new ComparatorSettings(); compSettings.setNegativeMap(map); - IMessage mEXECUTION_REPORT_FILTER; - mEXECUTION_REPORT_FILTER = this.messageFactory.createMessage("EXECUTION_REPORT", "namespace"); + IMessage mEXECUTION_REPORT_FILTER = messageFactory.createMessage("EXECUTION_REPORT", "namespace"); mEXECUTION_REPORT_FILTER.addField("CounterParty", "CounterParty"); mEXECUTION_REPORT_FILTER.addField("OrderStatus", "OrderStatus.Present"); mEXECUTION_REPORT_FILTER.addField("Origin", 1); @@ -588,114 +572,102 @@ public void testComparingPresentMissedEnums() { public void testCompareMultipleSubmessages() { Map actions = new HashMap<>(); - IMessage messageTradeConfirmation; - IMessage messageTradeConfirmation2; - IMessage messageOTHRPRTY; - IMessage messageSETDET; - IMessage messageSETPRTY; - IMessage messageBasicHeader; - IMessage messageCONFDET; - IMessage messageCONFPRTY; - IMessage messageGENL; - IMessage messageLINK; - IMessage messageTrailer; - IMessage messageApplicationHeaderInput; - - messageOTHRPRTY = this.messageFactory.createMessage("OTHRPRTY", "namespace"); - messageOTHRPRTY.addField("CounterParty", new java.lang.String("CounterParty")); + + IMessage messageOTHRPRTY = messageFactory.createMessage("OTHRPRTY", "namespace"); + messageOTHRPRTY.addField("CounterParty", new String("CounterParty")); actions.put("othrprty", messageOTHRPRTY); - messageSETPRTY = this.messageFactory.createMessage("SETPRTY", "namespace"); - messageSETPRTY.addField("SettlementAccount", new java.lang.String("SettlementAccount_1")); - messageSETPRTY.addField("SettlementParty_Seller_R", new java.lang.String( "SettlementParty_Seller_R_1" )); - messageSETPRTY.addField("PlaceOfSettlement", new java.lang.String( "PlaceOfSettlement_1" )); - messageSETPRTY.addField("SettlementParty_Seller_P", new java.lang.String( "SettlementParty_Seller_P_1" )); - messageSETPRTY.addField("SettlementParty_Buyer_R", new java.lang.String( "SettlementParty_Buyer_R_1" )); - messageSETPRTY.addField("SettlementParty_Buyer_P", new java.lang.String( "SettlementParty_Buyer_P_1" )); + IMessage messageSETPRTY = messageFactory.createMessage("SETPRTY", "namespace"); + messageSETPRTY.addField("SettlementAccount", new String("SettlementAccount_1")); + messageSETPRTY.addField("SettlementParty_Seller_R", new String("SettlementParty_Seller_R_1")); + messageSETPRTY.addField("PlaceOfSettlement", new String("PlaceOfSettlement_1")); + messageSETPRTY.addField("SettlementParty_Seller_P", new String("SettlementParty_Seller_P_1")); + messageSETPRTY.addField("SettlementParty_Buyer_R", new String("SettlementParty_Buyer_R_1")); + messageSETPRTY.addField("SettlementParty_Buyer_P", new String("SettlementParty_Buyer_P_1")); actions.put("setprty1", messageSETPRTY); - messageSETPRTY = this.messageFactory.createMessage("SETPRTY", "namespace"); - messageSETPRTY.addField("SettlementAccount", new java.lang.String("SettlementAccount_2")); - messageSETPRTY.addField("SettlementParty_Seller_R", new java.lang.String( "SettlementParty_Seller_R_2" )); - messageSETPRTY.addField("PlaceOfSettlement", new java.lang.String( "PlaceOfSettlement_2" )); - messageSETPRTY.addField("SettlementParty_Seller_P", new java.lang.String( "SettlementParty_Seller_P_2" )); - messageSETPRTY.addField("SettlementParty_Buyer_R", new java.lang.String( "SettlementParty_Buyer_R_2" )); - messageSETPRTY.addField("SettlementParty_Buyer_P", new java.lang.String( "SettlementParty_Buyer_P_2" )); + messageSETPRTY = messageFactory.createMessage("SETPRTY", "namespace"); + messageSETPRTY.addField("SettlementAccount", new String("SettlementAccount_2")); + messageSETPRTY.addField("SettlementParty_Seller_R", new String("SettlementParty_Seller_R_2")); + messageSETPRTY.addField("PlaceOfSettlement", new String("PlaceOfSettlement_2")); + messageSETPRTY.addField("SettlementParty_Seller_P", new String("SettlementParty_Seller_P_2")); + messageSETPRTY.addField("SettlementParty_Buyer_R", new String("SettlementParty_Buyer_R_2")); + messageSETPRTY.addField("SettlementParty_Buyer_P", new String("SettlementParty_Buyer_P_2")); actions.put("setprty2", messageSETPRTY); - messageSETDET = this.messageFactory.createMessage("SETDET", "namespace"); - messageSETDET.addField("TypeOfSettlementIndicator", new java.lang.String( "TypeOfSettlementIndicator" )); + IMessage messageSETDET = messageFactory.createMessage("SETDET", "namespace"); + messageSETDET.addField("TypeOfSettlementIndicator", new String("TypeOfSettlementIndicator")); messageSETDET.addField("SETPRTY", actions.get("setprty1")); messageSETDET.addField("SETPRTY", actions.get("setprty2")); actions.put("setdet", messageSETDET); - messageBasicHeader = this.messageFactory.createMessage("BasicHeader", "namespace"); + IMessage messageBasicHeader = messageFactory.createMessage("BasicHeader", "namespace"); messageBasicHeader.addField("ServiceID", 1 ); - messageBasicHeader.addField("LogicalTerminalAddress", new java.lang.String( "ANASCH20AXXX" )); + messageBasicHeader.addField("LogicalTerminalAddress", new String("ANASCH20AXXX")); messageBasicHeader.addField("SessionNumber", 4321 ); messageBasicHeader.addField("SequenceNumber", 654321 ); - messageBasicHeader.addField("ApplicationID", new java.lang.String( "F" )); + messageBasicHeader.addField("ApplicationID", new String("F")); actions.put("bh", messageBasicHeader); - messageCONFPRTY = this.messageFactory.createMessage("CONFPRTY", "namespace"); - messageCONFPRTY.addField("ClearingMember_P", new java.lang.String( "ClearingMember_P" )); - messageCONFPRTY.addField("PartyCapacity", new java.lang.String( "PartyCapacity" )); - messageCONFPRTY.addField("AccountAtTradingVenue", new java.lang.String( "AccountAtTradingVenue" )); - messageCONFPRTY.addField("ClearingMember_R", new java.lang.String( "ClearingMember_R" )); - messageCONFPRTY.addField("Buyer_P", new java.lang.String( "Buyer_P" )); - messageCONFPRTY.addField("PositionAccount", new java.lang.String("PositionAccount")); - messageCONFPRTY.addField("Buyer_R", new java.lang.String( "Buyer_R" )); - messageCONFPRTY.addField("TradingPartyReference", new java.lang.String( "TradingPartyReference" )); - messageCONFPRTY.addField("PartyNarrative", new java.lang.String( "PartyNarrative" )); - messageCONFPRTY.addField("Seller_P", new java.lang.String( "Seller_P" )); - messageCONFPRTY.addField("Seller_R", new java.lang.String( "Seller_R" )); + IMessage messageCONFPRTY = messageFactory.createMessage("CONFPRTY", "namespace"); + messageCONFPRTY.addField("ClearingMember_P", new String("ClearingMember_P")); + messageCONFPRTY.addField("PartyCapacity", new String("PartyCapacity")); + messageCONFPRTY.addField("AccountAtTradingVenue", new String("AccountAtTradingVenue")); + messageCONFPRTY.addField("ClearingMember_R", new String("ClearingMember_R")); + messageCONFPRTY.addField("Buyer_P", new String("Buyer_P")); + messageCONFPRTY.addField("PositionAccount", new String("PositionAccount")); + messageCONFPRTY.addField("Buyer_R", new String("Buyer_R")); + messageCONFPRTY.addField("TradingPartyReference", new String("TradingPartyReference")); + messageCONFPRTY.addField("PartyNarrative", new String("PartyNarrative")); + messageCONFPRTY.addField("Seller_P", new String("Seller_P")); + messageCONFPRTY.addField("Seller_R", new String("Seller_R")); actions.put("confprty", messageCONFPRTY); - messageCONFDET = this.messageFactory.createMessage("CONFDET", "namespace"); - messageCONFDET.addField("PlaceOfTrade", new java.lang.String( "PlaceOfTrade" )); - messageCONFDET.addField("SettlementDate", new java.lang.String( "SettlementDate" )); + IMessage messageCONFDET = messageFactory.createMessage("CONFDET", "namespace"); + messageCONFDET.addField("PlaceOfTrade", new String("PlaceOfTrade")); + messageCONFDET.addField("SettlementDate", new String("SettlementDate")); messageCONFDET.addField("CONFPRTY", actions.get("confprty")); - messageCONFDET.addField("QuantityTraded", new java.lang.String( "QuantityTraded" )); - messageCONFDET.addField("DealPriceAndCurrency_B", new java.lang.String( "DealPriceAndCurrency_B" )); - messageCONFDET.addField("BuySellIndicator", new java.lang.String( "BuySellIndicator" )); - messageCONFDET.addField("SettlementAmountAndCurrency", new java.lang.String( "SettlementAmountAndCurrency" )); - messageCONFDET.addField("DealPriceAndCurrency_A", new java.lang.String( "DealPriceAndCurrency_A" )); - messageCONFDET.addField("TradeDateTime", new java.lang.String( "TradeDateTime" )); - messageCONFDET.addField("FinancialInstrument", new java.lang.String( "FinancialInstrument" )); - messageCONFDET.addField("PaymentIndicator", new java.lang.String( "PaymentIndicator" )); - messageCONFDET.addField("TradeProcessingNarrative", new java.lang.String( "TradeProcessingNarrative" )); + messageCONFDET.addField("QuantityTraded", new String("QuantityTraded")); + messageCONFDET.addField("DealPriceAndCurrency_B", new String("DealPriceAndCurrency_B")); + messageCONFDET.addField("BuySellIndicator", new String("BuySellIndicator")); + messageCONFDET.addField("SettlementAmountAndCurrency", new String("SettlementAmountAndCurrency")); + messageCONFDET.addField("DealPriceAndCurrency_A", new String("DealPriceAndCurrency_A")); + messageCONFDET.addField("TradeDateTime", new String("TradeDateTime")); + messageCONFDET.addField("FinancialInstrument", new String("FinancialInstrument")); + messageCONFDET.addField("PaymentIndicator", new String("PaymentIndicator")); + messageCONFDET.addField("TradeProcessingNarrative", new String("TradeProcessingNarrative")); actions.put("confdet", messageCONFDET); - messageLINK = this.messageFactory.createMessage("LINK", "namespace"); - messageLINK.addField("LinkedMessage", new java.lang.String( "LinkedMessage" )); - messageLINK.addField("TradeReference", new java.lang.String("TradeReference")); - messageLINK.addField("PreviousReference", new java.lang.String( "PreviousReference" )); - messageLINK.addField("VenueTradeReference", new java.lang.String( "VenueTradeReference" )); + IMessage messageLINK = messageFactory.createMessage("LINK", "namespace"); + messageLINK.addField("LinkedMessage", new String("LinkedMessage")); + messageLINK.addField("TradeReference", new String("TradeReference")); + messageLINK.addField("PreviousReference", new String("PreviousReference")); + messageLINK.addField("VenueTradeReference", new String("VenueTradeReference")); actions.put("link", messageLINK); - messageGENL = this.messageFactory.createMessage("GENL", "namespace"); - messageGENL.addField("TradeType", new java.lang.String( "TradeType" )); - messageGENL.addField("SendersReference", new java.lang.String( "SendersReference" )); - messageGENL.addField("PreparationDateTime", new java.lang.String( "PreparationDateTime" )); + IMessage messageGENL = messageFactory.createMessage("GENL", "namespace"); + messageGENL.addField("TradeType", new String("TradeType")); + messageGENL.addField("SendersReference", new String("SendersReference")); + messageGENL.addField("PreparationDateTime", new String("PreparationDateTime")); messageGENL.addField("LINK", actions.get("link")); actions.put("genl", messageGENL); - messageTrailer = this.messageFactory.createMessage("Trailer", "namespace"); - messageTrailer.addField("TNG", new java.lang.String( "TNG" )); - messageTrailer.addField("CHK", new java.lang.String( "CHK" )); - messageTrailer.addField("MAC", new java.lang.String( "MAC" )); + IMessage messageTrailer = messageFactory.createMessage("Trailer", "namespace"); + messageTrailer.addField("TNG", new String("TNG")); + messageTrailer.addField("CHK", new String("CHK")); + messageTrailer.addField("MAC", new String("MAC")); actions.put("trailer", messageTrailer); - messageApplicationHeaderInput = this.messageFactory.createMessage("ApplicationHeaderInput", "namespace"); + IMessage messageApplicationHeaderInput = messageFactory.createMessage("ApplicationHeaderInput", "namespace"); messageApplicationHeaderInput.addField("ObsolescencePeriod", 3 ); - messageApplicationHeaderInput.addField("Input", new java.lang.String( "I" )); - messageApplicationHeaderInput.addField("ReceiversAddress", new java.lang.String( "BANKDEFFXXXX" )); - messageApplicationHeaderInput.addField("MessagePriority", new java.lang.String( "U" )); + messageApplicationHeaderInput.addField("Input", new String("I")); + messageApplicationHeaderInput.addField("ReceiversAddress", new String("BANKDEFFXXXX")); + messageApplicationHeaderInput.addField("MessagePriority", new String("U")); messageApplicationHeaderInput.addField("MessageType", 518 ); - messageApplicationHeaderInput.addField("DeliveryMonitoring", new java.lang.String( "3" )); + messageApplicationHeaderInput.addField("DeliveryMonitoring", new String("3")); actions.put("h1", messageApplicationHeaderInput); - messageTradeConfirmation = this.messageFactory.createMessage("TradeConfirmation", "namespace"); + IMessage messageTradeConfirmation = messageFactory.createMessage("TradeConfirmation", "namespace"); messageTradeConfirmation.addField("OTHRPRTY", actions.get("othrprty")); messageTradeConfirmation.addField("SETDET", actions.get("setdet")); messageTradeConfirmation.addField("BasicHeader", actions.get("bh")); @@ -704,19 +676,19 @@ public void testCompareMultipleSubmessages() messageTradeConfirmation.addField("Trailer", actions.get("trailer")); messageTradeConfirmation.addField("ApplicationHeaderInput", actions.get("h1")); - messageSETPRTY = this.messageFactory.createMessage("SETPRTY", "namespace"); - messageSETPRTY.addField("SettlementAccount", new java.lang.String("another value")); - messageSETPRTY.addField("SettlementParty_Seller_R", new java.lang.String( "another value" )); - messageSETPRTY.addField("PlaceOfSettlement", new java.lang.String( "another value" )); + messageSETPRTY = messageFactory.createMessage("SETPRTY", "namespace"); + messageSETPRTY.addField("SettlementAccount", new String("another value")); + messageSETPRTY.addField("SettlementParty_Seller_R", new String("another value")); + messageSETPRTY.addField("PlaceOfSettlement", new String("another value")); actions.put("setprty2", messageSETPRTY); - messageSETDET = this.messageFactory.createMessage("SETDET", "namespace"); - messageSETDET.addField("TypeOfSettlementIndicator", new java.lang.String( "TypeOfSettlementIndicator" )); + messageSETDET = messageFactory.createMessage("SETDET", "namespace"); + messageSETDET.addField("TypeOfSettlementIndicator", new String("TypeOfSettlementIndicator")); messageSETDET.addField("SETPRTY", messageSETPRTY); messageSETDET.addField("SETPRTY", actions.get("setprty1")); actions.put("setdet", messageSETDET); - messageTradeConfirmation2 = this.messageFactory.createMessage("TradeConfirmation", "namespace"); + IMessage messageTradeConfirmation2 = messageFactory.createMessage("TradeConfirmation", "namespace"); messageTradeConfirmation2.addField("OTHRPRTY", actions.get("othrprty")); messageTradeConfirmation2.addField("SETDET", actions.get("setdet")); messageTradeConfirmation2.addField("BasicHeader", actions.get("bh")); @@ -736,21 +708,17 @@ public void testCompareMultipleSubmessages() @Test public void testDoublePresicion() { - IMessage mGrossRecord; - IMessage mGrossRecord2; - com.exactpro.sf.aml.script.MetaContainer metaContainer; - ComparatorSettings settings; - mGrossRecord = this.messageFactory.createMessage("GrossRecord", "namespace"); + IMessage mGrossRecord = messageFactory.createMessage("GrossRecord", "namespace"); mGrossRecord.addField("CurrentGross", 89518.08d); - mGrossRecord2 = this.messageFactory.createMessage("GrossRecord", "namespace"); + IMessage mGrossRecord2 = messageFactory.createMessage("GrossRecord", "namespace"); mGrossRecord2.addField("CurrentGross", 89519d); - metaContainer = new com.exactpro.sf.aml.script.MetaContainer(); + MetaContainer metaContainer = new MetaContainer(); metaContainer.addDoublePrecision("CurrentGross=10"); - settings = new ComparatorSettings(); + ComparatorSettings settings = new ComparatorSettings(); settings.setMetaContainer(metaContainer); ComparisonResult result = MessageComparator.compare(mGrossRecord, mGrossRecord2, settings); @@ -762,20 +730,20 @@ public void testDoublePresicion() @Test public void testDoublePre() { - IMessage mGrossRecord = this.messageFactory.createMessage("GrossRecord", "namespace"); + IMessage mGrossRecord = messageFactory.createMessage("GrossRecord", "namespace"); mGrossRecord.addField("BrokerId", "MEMBERFIRM1"); mGrossRecord.addField("CurrentGross", 74598.4); mGrossRecord.addField("UserId", "NAT_MAX_1"); - IMessage mGrossRecord2 = this.messageFactory.createMessage("GrossRecord", "namespace"); + IMessage mGrossRecord2 = messageFactory.createMessage("GrossRecord", "namespace"); mGrossRecord2.addField("BrokerId", "MEMBERFIRM1"); mGrossRecord2.addField("CurrentGross", 74599); mGrossRecord2.addField("UserId", "NAT_MAX_1"); - MetaContainer metaContainer = new com.exactpro.sf.aml.script.MetaContainer(); + MetaContainer metaContainer = new MetaContainer(); metaContainer.addDoublePrecision("CurrentGross=10"); - DefaultSettings settings = new com.exactpro.sf.aml.script.DefaultSettings(getScriptContext(), true); + DefaultSettings settings = new DefaultSettings(getScriptContext(), true); settings.setMetaContainer(metaContainer); settings.setFailUnexpected("N"); settings.setDescription("check CGC in database"); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/conversion/TestMultiConverter.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/conversion/TestMultiConverter.java index 9c7c67fa..c80c9c24 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/conversion/TestMultiConverter.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/comparison/conversion/TestMultiConverter.java @@ -32,7 +32,7 @@ import junit.framework.Assert; public class TestMultiConverter { - private static final Object[][] VALUES = new Object[][] { + private static final Object[][] VALUES = { { null, null, null, null, null, null, null, null, null, true, null, null, null }, { null, null, (byte)65, (byte)66, (byte)67, (byte)68, (byte)69, (byte)70, (byte)71, (byte)72, null, null, null }, { null, (short)97, null, (short)98, (short)99, (short)100, (short)101, (short)102, (short)103, (short)104, null, null, null }, diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestAbstractDictionaryValidator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestAbstractDictionaryValidator.java index fa11092c..6cda39d2 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestAbstractDictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestAbstractDictionaryValidator.java @@ -79,13 +79,13 @@ public TestAbstractDictionaryValidator() { this.fieldStructure = Mockito.mock(IFieldStructure.class); this.messageStructure = Mockito.mock(IMessageStructure.class); - Map fields = singletonMap(this.fieldStructure.getName(), this.fieldStructure); - Mockito.when(this.messageStructure.getFields()).thenReturn(fields); + Map fields = singletonMap(fieldStructure.getName(), fieldStructure); + Mockito.when(messageStructure.getFields()).thenReturn(fields); this.dictionaryStructure = Mockito.mock(IDictionaryStructure.class); - Map messages = singletonMap(this.messageStructure.getName(), this.messageStructure); - Mockito.when(this.dictionaryStructure.getMessages()).thenReturn(messages); - Mockito.when(this.dictionaryStructure.getFields()).thenReturn(fields); + Map messages = singletonMap(messageStructure.getName(), messageStructure); + Mockito.when(dictionaryStructure.getMessages()).thenReturn(messages); + Mockito.when(dictionaryStructure.getFields()).thenReturn(fields); AbstractDictionaryValidator parent = new AbstractDictionaryValidator() { @@ -108,11 +108,7 @@ public List validate(IDictionaryStructure dictionary, @Override public List validate(IMessageStructure message, IFieldStructure field) { List list = super.validate(message, field); - if (message != null) { - list.add(parentMessageFieldError); - } else { - list.add(parentFieldError); - } + list.add(message != null ? parentMessageFieldError : parentFieldError); return list; } }; @@ -137,11 +133,7 @@ public List validate(IDictionaryStructure dictionary, @Override public List validate(IMessageStructure message, IFieldStructure field) { List list = super.validate(message, field); - if (message != null) { - list.add(childMessageFieldError); - } else { - list.add(childFieldError); - } + list.add(message != null ? childMessageFieldError : childFieldError); return list; } }; @@ -150,35 +142,35 @@ public List validate(IMessageStructure message, IFiel @Test public void testCallTrace() { Assert.assertArrayEquals(new Object[] { parentMessageFieldError, childMessageFieldError }, - childDictionaryValidator.validate(this.messageStructure, this.fieldStructure).toArray()); + childDictionaryValidator.validate(messageStructure, fieldStructure).toArray()); Assert.assertArrayEquals( new Object[] { parentMessageOldError, parentMessageNewError, parentMessageFieldError, childMessageFieldError, childMessageOldError, childMessageNewError }, - childDictionaryValidator.validate(this.dictionaryStructure, this.messageStructure, true).toArray()); + childDictionaryValidator.validate(dictionaryStructure, messageStructure, true).toArray()); Assert.assertArrayEquals( new Object[] { parentMessageOldError, parentMessageNewError, childMessageOldError, childMessageNewError }, - childDictionaryValidator.validate(this.dictionaryStructure, this.messageStructure, false).toArray()); + childDictionaryValidator.validate(dictionaryStructure, messageStructure, false).toArray()); Assert.assertArrayEquals( new Object[] { parentDictionaryError, childDictionaryError }, - childDictionaryValidator.validate(this.dictionaryStructure, false, false).toArray()); + childDictionaryValidator.validate(dictionaryStructure, false, false).toArray()); Assert.assertArrayEquals( new Object[] { parentDictionaryError, childDictionaryError }, - childDictionaryValidator.validate(this.dictionaryStructure, false, true).toArray()); + childDictionaryValidator.validate(dictionaryStructure, false, true).toArray()); Assert.assertArrayEquals( new Object[] { parentDictionaryError, childDictionaryError }, - childDictionaryValidator.validate(this.dictionaryStructure, false, null).toArray()); + childDictionaryValidator.validate(dictionaryStructure, false, null).toArray()); Assert.assertArrayEquals( new Object[] { parentDictionaryError, parentMessageOldError, parentMessageNewError, parentMessageFieldError, childMessageFieldError, childMessageOldError, childMessageNewError, childDictionaryError }, - childDictionaryValidator.validate(this.dictionaryStructure, true, false).toArray()); + childDictionaryValidator.validate(dictionaryStructure, true, false).toArray()); Assert.assertArrayEquals( new Object[] { parentDictionaryError, parentFieldError, childFieldError, childDictionaryError }, - childDictionaryValidator.validate(this.dictionaryStructure, true, true).toArray()); + childDictionaryValidator.validate(dictionaryStructure, true, true).toArray()); Assert.assertArrayEquals( new Object[] { parentDictionaryError, parentFieldError, childFieldError, parentMessageOldError, parentMessageNewError, parentMessageFieldError, childMessageFieldError, childMessageOldError, childMessageNewError, childDictionaryError }, - childDictionaryValidator.validate(this.dictionaryStructure, true, null).toArray()); + childDictionaryValidator.validate(dictionaryStructure, true, null).toArray()); } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestDefaultWorkspaceDispatcher.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestDefaultWorkspaceDispatcher.java index 5bf13d07..e0751f09 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestDefaultWorkspaceDispatcher.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestDefaultWorkspaceDispatcher.java @@ -115,12 +115,7 @@ public void testCRUD() throws IOException { // CREATE FILE #3: use None-system separator in path path = "nested3" + File.separator + "test4.xml"; - String pathOtherSys; - if ('/' == File.separatorChar) { - pathOtherSys = FilenameUtils.separatorsToWindows(path); - } else { - pathOtherSys = FilenameUtils.separatorsToUnix(path); - } + String pathOtherSys = File.separatorChar == '/' ? FilenameUtils.separatorsToWindows(path) : FilenameUtils.separatorsToUnix(path); expected = new File(new File(topLayer, LOGS_DIR_PATH), path); actual = wd.createFile(FolderType.LOGS, true, pathOtherSys); compareFiles(expected, actual); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestRules.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestRules.java index 01d162eb..ce429477 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestRules.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/TestRules.java @@ -55,10 +55,8 @@ public void testSimpleRules() throws FileNotFoundException, WorkspaceSecurityExc Rules rules = load("TestSimpleRules"); RulesProcessor processor = new RulesProcessor(rules); - IMessage msg = null; - - // empty messages - msg = DefaultMessageFactory.getFactory().createMessage("AddOrder", "TEST"); + // empty messages + IMessage msg = DefaultMessageFactory.getFactory().createMessage("AddOrder", "TEST"); processor.processMessage(msg); Assert.assertTrue(msg.getFieldNames().isEmpty()); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestDefaultDictionaryValidator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestDefaultDictionaryValidator.java index 075355d3..dcccb3a7 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestDefaultDictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestDefaultDictionaryValidator.java @@ -45,7 +45,7 @@ public static void init() throws Exception { @Test public void testValidator() { List errors = validator.validate(dictionaryStructure, true, null); - String[] expectedErrors = new String[] { + String[] expectedErrors = { "DictionaryValidationError[message=,field=UnknownDefaultValue,error=Value \"3.3\" wasn't found in values table,level=FIELD,type=ERR_DEFAULT_VALUE]", "DictionaryValidationError[message=,field=WrongAttributeValue,error=Value \"net\" is not applicable for Boolean type,level=FIELD,type=ERR_ATTRIBUTES]", "DictionaryValidationError[message=,field=for,error=Prohibited name for for Field. Name can't be Java keyword or have value that presents in this list [_],level=FIELD,type=ERR_NAME]", @@ -59,7 +59,9 @@ public void testValidator() { "DictionaryValidationError[message=DuplicateMessage,field=SomeField1,error=Value \"net\" is not applicable for Boolean type,level=FIELD,type=ERR_ATTRIBUTES]" }; if (expectedErrors.length != errors.size()) { - errors.forEach(System.err::println); + for(DictionaryValidationError error : errors) { + System.err.println(error); + } } Assert.assertEquals("Unexpected errors", expectedErrors.length, errors.size()); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestPrototypeDictionaryValidator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestPrototypeDictionaryValidator.java index 3a70e3d9..795bb6a0 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestPrototypeDictionaryValidator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/configuration/dictionary/TestPrototypeDictionaryValidator.java @@ -31,9 +31,9 @@ public class TestPrototypeDictionaryValidator { - private final static String PROTOTYPE_DICTIONARY = Paths.get("dictionaries","prototypeDictionary.xml").toString(); - private final static String VALID_DICTIONARY = Paths.get("dictionaries", "validDictionary.xml").toString(); - private final static String INVALID_DICTIONARY = Paths.get("dictionaries", "invalidDictionary.xml").toString(); + private static final String PROTOTYPE_DICTIONARY = Paths.get("dictionaries", "prototypeDictionary.xml").toString(); + private static final String VALID_DICTIONARY = Paths.get("dictionaries", "validDictionary.xml").toString(); + private static final String INVALID_DICTIONARY = Paths.get("dictionaries", "invalidDictionary.xml").toString(); private static IDictionaryValidator prototypeValidator; private static IDictionaryStructure validDictionary; @@ -50,7 +50,7 @@ public static void init() { @Test public void testInvalid() { List errors = prototypeValidator.validate(invalidDictionary, true, null); - String[] expectedErrors = new String[] { + String[] expectedErrors = { "DictionaryValidationError[message=,field=EnumNumber,error=Value SECOND was missed,level=FIELD,type=ERR_VALUES]", "DictionaryValidationError[message=,field=EnumNumber,error=Value THIRD should be 3 but was 4,level=FIELD,type=ERR_VALUES]", "DictionaryValidationError[message=SecondMessage,field=ComplexField,error=JavaType should be null but was JAVA_LANG_INTEGER,level=FIELD,type=ERR_FIELD_TYPE]", @@ -83,7 +83,9 @@ public void testInvalid() { "DictionaryValidationError[message=ThirdMessage,field=,error=Missed required message ThirdMessage,level=DICTIONARY,type=ERR_REQUIRED_FIELD]" }; if (expectedErrors.length != errors.size()) { - errors.forEach(System.out::println); + for(DictionaryValidationError error : errors) { + System.out.println(error); + } } Assert.assertEquals("Some unexpected errors", expectedErrors.length, errors.size()); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestAbstractCaller.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestAbstractCaller.java index f226e0c8..41db3f7b 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestAbstractCaller.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestAbstractCaller.java @@ -23,7 +23,7 @@ import com.exactpro.sf.scriptrunner.utilitymanager.exceptions.UtilityNotFoundException; public class TestAbstractCaller { - private UtilityClass util = new UtilityClass(); + private final UtilityClass util = new UtilityClass(); @Test public void testIntFunc() throws UtilityCallException, UtilityNotFoundException, InterruptedException { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestScriptRunner.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestScriptRunner.java index a73f8e75..e806a160 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestScriptRunner.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/scriptrunner/TestScriptRunner.java @@ -24,6 +24,8 @@ import com.exactpro.sf.center.impl.SFLocalContext; import com.exactpro.sf.configuration.suri.SailfishURI; +import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptState; +import com.exactpro.sf.scriptrunner.TestScriptDescription.ScriptStatus; import com.exactpro.sf.util.AbstractTest; public class TestScriptRunner extends AbstractTest @@ -38,8 +40,9 @@ public void setUp() throws Exception { File workFolder = new File(WORK_FOLDER); - if ( !workFolder.exists() ) - workFolder.mkdir(); + if(!workFolder.exists()) { + workFolder.mkdir(); + } runner = new SyncScriptRunner( SFLocalContext.getDefault().getWorkspaceDispatcher(), @@ -67,8 +70,9 @@ public void testScriptRunner() throws InterruptedException long id = runner.enqueueScript(scriptSettingsPath, scriptMatrixPath, "Desc", "matrix", "", false, false, true, false, false, false, LANGUAGE, "UTF-8", "default", System.getProperty("user.name"), null, null, null, null, SFLocalContext.getDefault()); - if ( id == -1 ) - throw new RuntimeException("Script was not added to the queue"); + if(id == -1) { + throw new RuntimeException("Script was not added to the queue"); + } } @Test @@ -78,16 +82,19 @@ public void test3TestScripts() throws InterruptedException String scriptMatrixPath = "matrixes" + File.separator + "test.csv"; long id1 = runner.enqueueScript(scriptSettingsPath, scriptMatrixPath, "Desc1", "Matrix1", "", false, false, true, false, false, false, LANGUAGE, "UTF-8", "default", System.getProperty("user.name"), null, null, null, null, SFLocalContext.getDefault()); - if ( id1 == -1 ) - Assert.assertEquals(0, id1); + if(id1 == -1) { + Assert.assertEquals(0, id1); + } long id2 = runner.enqueueScript(scriptSettingsPath, scriptMatrixPath, "Desc2", "Matrix2", "", false, false, true, false, false, false, LANGUAGE, "UTF-8", "default", System.getProperty("user.name"), null, null, null, null, SFLocalContext.getDefault()); - if ( id2 == -1 ) - Assert.assertEquals(0, id2); + if(id2 == -1) { + Assert.assertEquals(0, id2); + } long id3 = runner.enqueueScript(scriptSettingsPath, scriptMatrixPath, "Desc3", "Matrix3", "", false, false, true, false, false, false, LANGUAGE, "UTF-8", "default", System.getProperty("user.name"), null, null, null, null, SFLocalContext.getDefault()); - if ( id3 == -1 ) - Assert.assertEquals(0, id3); + if(id3 == -1) { + Assert.assertEquals(0, id3); + } boolean finished = false; @@ -112,22 +119,23 @@ public void test3TestScripts() throws InterruptedException } - Assert.assertEquals(TestScriptDescription.ScriptState.FINISHED, descr1.getState()); + Assert.assertEquals(ScriptState.FINISHED, descr1.getState()); - Assert.assertEquals(TestScriptDescription.ScriptStatus.INIT_FAILED, descr1.getStatus()); //TODO: Check possibility add custom actions for this test + Assert.assertEquals(ScriptStatus.INIT_FAILED, descr1.getStatus()); //TODO: Check possibility add custom actions for this test - Assert.assertEquals(TestScriptDescription.ScriptState.FINISHED, descr2.getState()); + Assert.assertEquals(ScriptState.FINISHED, descr2.getState()); - Assert.assertEquals(TestScriptDescription.ScriptStatus.INIT_FAILED, descr2.getStatus()); + Assert.assertEquals(ScriptStatus.INIT_FAILED, descr2.getStatus()); - Assert.assertEquals(TestScriptDescription.ScriptState.FINISHED, descr3.getState()); + Assert.assertEquals(ScriptState.FINISHED, descr3.getState()); - Assert.assertEquals(TestScriptDescription.ScriptStatus.INIT_FAILED, descr3.getStatus()); + Assert.assertEquals(ScriptStatus.INIT_FAILED, descr3.getStatus()); } @After public void tearDown() throws Exception { - if ( runner != null ) - runner.dispose(); + if(runner != null) { + runner.dispose(); + } } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/EnabledSettings.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/EnabledSettings.java index 6da51750..4b6b515d 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/EnabledSettings.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/EnabledSettings.java @@ -15,10 +15,10 @@ ******************************************************************************/ package com.exactpro.sf.services; -import com.exactpro.sf.configuration.suri.SailfishURI; - import javax.xml.bind.annotation.XmlRootElement; +import com.exactpro.sf.configuration.suri.SailfishURI; + @XmlRootElement public class EnabledSettings extends AbstractServiceSettings { private int integerSetting; @@ -28,7 +28,7 @@ public class EnabledSettings extends AbstractServiceSettings { @Override public SailfishURI getDictionaryName() { - return this.dictionaryName; + return dictionaryName; } @Override diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestCSHIterator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestCSHIterator.java index 32b7d124..7b6ca264 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestCSHIterator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestCSHIterator.java @@ -27,8 +27,8 @@ import com.exactpro.sf.common.util.EPSCommonException; public class TestCSHIterator { - private final static long UPDATE_INTERVAL = 100L; - private final static List SOURCE = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + private static final long UPDATE_INTERVAL = 100L; + private static final List SOURCE = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); @Test public void testTimeout() throws InterruptedException { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestDisabledServiceSettings.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestDisabledServiceSettings.java index 68c67c25..2bce9649 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestDisabledServiceSettings.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestDisabledServiceSettings.java @@ -15,24 +15,6 @@ ******************************************************************************/ package com.exactpro.sf.services; -import com.exactpro.sf.aml.DictionarySettings; -import com.exactpro.sf.configuration.IDictionaryManager; -import com.exactpro.sf.configuration.StaticServiceDescription; -import com.exactpro.sf.configuration.dictionary.interfaces.IDictionaryValidator; -import com.exactpro.sf.configuration.suri.SailfishURI; -import com.exactpro.sf.scriptrunner.services.IStaticServiceManager; -import com.exactpro.sf.storage.util.ServiceStorageHelper; -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -41,10 +23,30 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import com.exactpro.sf.aml.DictionarySettings; +import com.exactpro.sf.configuration.IDictionaryManager; +import com.exactpro.sf.configuration.StaticServiceDescription; +import com.exactpro.sf.configuration.dictionary.interfaces.IDictionaryValidator; +import com.exactpro.sf.configuration.suri.SailfishURI; +import com.exactpro.sf.scriptrunner.services.IStaticServiceManager; public class TestDisabledServiceSettings { - private File enabledExpectedFile = new File("src/test/resources/services/enabled_expected.xml"); - private File disabledExpectedFile = new File("src/test/resources/services/disabled_expected.xml"); + private final File enabledExpectedFile = new File("src/test/resources/services/enabled_expected.xml"); + private final File disabledExpectedFile = new File("src/test/resources/services/disabled_expected.xml"); private File enabledActualFile; private File disabledActualFile; @@ -80,8 +82,8 @@ public void setUp() throws Exception { @After public void tearDown() throws Exception { - this.enabledActualFile.delete(); - this.disabledActualFile.delete(); + enabledActualFile.delete(); + disabledActualFile.delete(); } @Test @@ -92,7 +94,7 @@ public void testEnabledToEnabled() throws Exception { Map stringFileMap = enabledMarshalManager.exportServices(Arrays.asList(enabledDescription)); Assert.assertEquals(1, stringFileMap.size()); - Map.Entry next = stringFileMap.entrySet().iterator().next(); + Entry next = stringFileMap.entrySet().iterator().next(); File exported = next.getValue(); Assert.assertTrue(FileUtils.contentEquals(enabledExpectedFile, exported)); exported.deleteOnExit(); @@ -120,7 +122,7 @@ public void testDisabledToDisabled() throws Exception { Map stringFileMap = disabledMarshalManager.exportServices(Arrays.asList(disabledDescription)); Assert.assertEquals(1, stringFileMap.size()); - Map.Entry next = stringFileMap.entrySet().iterator().next(); + Entry next = stringFileMap.entrySet().iterator().next(); File exported = next.getValue(); Assert.assertTrue(FileUtils.contentEquals(disabledExpectedFile, exported)); exported.deleteOnExit(); @@ -160,7 +162,7 @@ public void testEnabledToDisabled() throws IOException { Map stringFileMap = disabledMarshalManager.exportServices(Arrays.asList(description)); Assert.assertEquals(1, stringFileMap.size()); - Map.Entry next = stringFileMap.entrySet().iterator().next(); + Entry next = stringFileMap.entrySet().iterator().next(); File exported = next.getValue(); Assert.assertTrue(FileUtils.contentEquals(disabledExpectedFile, exported)); exported.deleteOnExit(); @@ -270,7 +272,7 @@ private ServiceDescription createDisabledDescription() { private class ServiceManagerWithEnabled implements IStaticServiceManager { private final List descriptions = new ArrayList<>(); - private final SailfishURI[] serviceURIs = new SailfishURI[]{SailfishURI.unsafeParse("test:enabled_service")}; + private final SailfishURI[] serviceURIs = { SailfishURI.unsafeParse("test:enabled_service") }; { StaticServiceDescription description = new StaticServiceDescription( @@ -291,10 +293,7 @@ public SailfishURI[] getServiceURIs() { @Override public StaticServiceDescription findStaticServiceDescription(SailfishURI serviceURI) { - if (serviceURI.equals(serviceURIs[0])) { - return descriptions.get(0); - } - return null; + return serviceURI.equals(serviceURIs[0]) ? descriptions.get(0) : null; } @Override @@ -304,10 +303,7 @@ public IService createService(SailfishURI serviceURI) { @Override public IServiceSettings createServiceSettings(SailfishURI serviceURI) { - if (serviceURI.equals(serviceURIs[0])) { - return new EnabledSettings(); - } - return null; + return serviceURI.equals(serviceURIs[0]) ? new EnabledSettings() : null; } @Override diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestExternalApi.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestExternalApi.java index f99b90fd..3354e1d7 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestExternalApi.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestExternalApi.java @@ -33,6 +33,8 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; import com.exactpro.sf.center.IVersion; import com.exactpro.sf.common.messages.IMessage; @@ -54,8 +56,8 @@ @RunWith(Parameterized.class) public class TestExternalApi { - private File writableLayer = Paths.get("build", "tmp", "test_external_api").toFile(); - private ServiceName serviceName = new ServiceName("env", "serviceName"); + private final File writableLayer = Paths.get("build", "tmp", "test_external_api").toFile(); + private final ServiceName serviceName = new ServiceName("env", "serviceName"); private SailfishURI serviceType; private SailfishURI testServiceType; private SailfishURI testDictionary; @@ -64,10 +66,10 @@ public class TestExternalApi { @Rule public ExpectedException exception = ExpectedException.none(); - @Parameterized.Parameter + @Parameter public boolean strict = true; - @Parameterized.Parameters(name = "strictMode = {0}") + @Parameters(name = "strictMode = {0}") public static Collection data() { return Arrays.asList(false, true); } @@ -126,7 +128,7 @@ public void onMessage(IServiceProxy service, IMessage message, boolean rejected, e.printStackTrace(); Assert.fail(e.getMessage()); } finally { - if (ServiceStatus.STARTED.equals(sp.getStatus())) { + if(sp.getStatus() == ServiceStatus.STARTED) { sp.stop(); } } @@ -141,7 +143,7 @@ public void test() { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { - if (ServiceStatus.STARTED.equals(sp.getStatus())) { + if(sp.getStatus() == ServiceStatus.STARTED) { sp.stop(); } } @@ -160,7 +162,7 @@ public void testResourceLayer() { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { - if (sp != null && ServiceStatus.STARTED.equals(sp.getStatus())) { + if(sp != null && sp.getStatus() == ServiceStatus.STARTED) { sp.stop(); } } @@ -203,7 +205,7 @@ public void testMessageFactory() { e1.printStackTrace(); Assert.fail(e1.getMessage()); } finally { - if (ServiceStatus.STARTED.equals(sp.getStatus())) { + if(sp.getStatus() == ServiceStatus.STARTED) { sp.stop(); } } @@ -259,7 +261,7 @@ public void testServiceProxy() { e1.printStackTrace(); Assert.fail(e1.getMessage()); } finally { - if (ServiceStatus.STARTED.equals(sp.getStatus())) { + if(sp.getStatus() == ServiceStatus.STARTED) { sp.stop(); } } @@ -311,7 +313,7 @@ public void testSettingsProxy() { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { - if (ServiceStatus.STARTED.equals(sp.getStatus())) { + if(sp.getStatus() == ServiceStatus.STARTED) { sp.stop(); } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestTaskExecutor.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestTaskExecutor.java index 5f90d30a..a528d83d 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestTaskExecutor.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/services/TestTaskExecutor.java @@ -20,14 +20,14 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import junit.framework.Assert; - import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.junit.BeforeClass; import org.junit.Test; +import junit.framework.Assert; + /** * @author nikita.smirnov * @@ -100,15 +100,15 @@ public void testException() throws InterruptedException { } } - private class Task implements Runnable, Callable { - - private volatile int maxRun = 0; - private volatile int runCount = 0; + private class Task implements Runnable, Callable { + + private volatile int maxRun; + private volatile int runCount; @Override public void run() { System.out.println(Thread.currentThread().getName()); - if (++this.runCount >= this.maxRun) { + if(++this.runCount >= maxRun) { throw new RuntimeException("Test"); } } @@ -120,7 +120,7 @@ public String call() throws Exception { } public int getRunCount() { - return this.runCount; + return runCount; } public void setMaxRun(int value) { diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/storage/impl/TestStorage.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/storage/impl/TestStorage.java index 0ca58f18..a4056c0a 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/storage/impl/TestStorage.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/storage/impl/TestStorage.java @@ -138,7 +138,7 @@ public void testMassStoring() throws InterruptedException, WorkspaceStructureExc Thread.sleep(3); } - System.out.println(((double)(System.currentTimeMillis() - start))/10000.00); + System.out.println((double)(System.currentTimeMillis() - start) /10000.00); defMsgStorage.closeScriptRun(scriptRun); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/AbstractTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/AbstractTest.java index df9f0767..eb416a31 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/AbstractTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/AbstractTest.java @@ -78,8 +78,8 @@ public class AbstractTest { protected static IServiceContext serviceContext; protected static IWorkspaceDispatcher workspaceDispatcher; - private static boolean isLoggingAlreadyConfigured = false; - private static boolean isAlreadyConfigured = false; + private static boolean isLoggingAlreadyConfigured; + private static boolean isAlreadyConfigured; private static final String DEFAULT_CFG_FILENAME = "sf.cfg.xml"; @@ -115,7 +115,7 @@ public static void initTestToolsTestCase() throws Throwable { synchronized(logger) { try { if(!isLoggingAlreadyConfigured) { - try (InputStream inputStream = AbstractTest.class.getClassLoader().getResourceAsStream(LOG_PROPERTIES_PATH);) { + try (InputStream inputStream = AbstractTest.class.getClassLoader().getResourceAsStream(LOG_PROPERTIES_PATH)) { PropertyConfigurator.configure(inputStream); } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/JsonMessageConverterTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/JsonMessageConverterTest.java index 86ca8f22..8becfe98 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/JsonMessageConverterTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/JsonMessageConverterTest.java @@ -194,7 +194,7 @@ public void testHumanFormat() { message.addField("FBoolean", new Object() { //Markers for special actions public String toString() { return "excluded field"; - }; + } }); message.addField("FakeMessage", map); message.addField("FakeMessages", Lists.newArrayList(map)); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/KnownBugPostValidationTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/KnownBugPostValidationTest.java index b9b32a2d..81cb4db4 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/KnownBugPostValidationTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/KnownBugPostValidationTest.java @@ -15,33 +15,33 @@ ******************************************************************************/ package com.exactpro.sf.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.junit.Assert; +import org.junit.Test; + +import com.exactpro.sf.aml.scriptutil.StaticUtil; +import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; +import com.exactpro.sf.center.impl.SFLocalContext; import com.exactpro.sf.common.impl.messages.DefaultMessageFactory; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.common.util.StringUtil; -import com.exactpro.sf.aml.scriptutil.StaticUtil; -import com.exactpro.sf.aml.scriptutil.StaticUtil.IFilter; -import com.exactpro.sf.center.impl.SFLocalContext; import com.exactpro.sf.comparison.ComparatorSettings; import com.exactpro.sf.comparison.ComparisonResult; import com.exactpro.sf.comparison.ComparisonUtil; import com.exactpro.sf.comparison.MessageComparator; import com.exactpro.sf.scriptrunner.StatusType; import com.exactpro.sf.scriptrunner.utilitymanager.IUtilityManager; -import com.google.common.collect.Lists; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Stream; - import com.google.common.collect.ImmutableList; -import org.apache.commons.lang3.ArrayUtils; +import com.google.common.collect.Lists; /** * @author sergey.vasiliev * @@ -967,47 +967,43 @@ public KnownBugBuilder(String expectedValue) { public KnownBugBuilder(String expectedValue, boolean list) { if(list) { - this.builder.append("List"); + builder.append("List"); } - this.builder.append("\"), ").append(expectedValue).append(" )"); + builder.append("\"), ").append(expectedValue).append(" )"); } public KnownBugBuilder(boolean empty, boolean list) { - if (empty) { - this.builder.append("Empty"); - } else { - this.builder.append("Any"); - } + builder.append(empty ? "Empty" : "Any"); if (list) { - this.builder.append("List"); + builder.append("List"); } - this.builder.append("\"))"); + builder.append("\"))"); } public KnownBugBuilder bug(String description, String value, String... categories) { - this.builder.append(".Bug( \"").append(description).append("\" , ").append(value); + builder.append(".Bug( \"").append(description).append("\" , ").append(value); for (String category : categories) { - this.builder.append(" , \"").append(category).append("\""); + builder.append(" , \"").append(category).append("\""); } - this.builder.append(" )"); + builder.append(" )"); return this; } public KnownBugBuilder bug(String description, String value) { - this.builder.append(".Bug( \"").append(description).append("\" , ").append(value).append(" )"); + builder.append(".Bug( \"").append(description).append("\" , ").append(value).append(" )"); return this; } public KnownBugBuilder bugEmpty(String description) { - this.builder.append(".BugEmpty( \"").append(description).append("\" )"); + builder.append(".BugEmpty( \"").append(description).append("\" )"); return this; } public KnownBugBuilder bugAny(String description) { - this.builder.append(".BugAny( \"").append(description).append("\" )"); + builder.append(".BugAny( \"").append(description).append("\" )"); return this; } @@ -1017,7 +1013,7 @@ public IFilter build(boolean setActual, Object ... args) { postfix = ".Actual(x)"; } args = ArrayUtils.addAll(args, "um", utilityManger); - return StaticUtil.filter(0, null, this.builder.toString() + postfix, args); + return StaticUtil.filter(0, null, builder + postfix, args); } } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/NettyTestUtility.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/NettyTestUtility.java index 97f90ac8..836632b9 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/NettyTestUtility.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/NettyTestUtility.java @@ -30,7 +30,7 @@ public class NettyTestUtility { - public static ByteBuf encode(IMessage msg, final Logger logger, ChannelHandler... handlers) throws IOException { + public static ByteBuf encode(IMessage msg, Logger logger, ChannelHandler... handlers) throws IOException { EmbeddedChannel encodeChannel = getEmbeddedChannel(logger, handlers); encodeChannel.writeOutbound(msg); ByteBuf buf = (ByteBuf) encodeChannel.outboundMessages().poll(); @@ -38,13 +38,13 @@ public static ByteBuf encode(IMessage msg, final Logger logger, ChannelHandler.. return buf; } - public static IMessage decode(ByteBuf buf, final Logger logger, ChannelHandler... handlers) { + public static IMessage decode(ByteBuf buf, Logger logger, ChannelHandler... handlers) { EmbeddedChannel decodeChannel = getEmbeddedChannel(logger, handlers); decodeChannel.writeInbound(buf); return (IMessage) decodeChannel.inboundMessages().poll(); } - public static EmbeddedChannel getEmbeddedChannel(final Logger logger, ChannelHandler... handlers) { + public static EmbeddedChannel getEmbeddedChannel(Logger logger, ChannelHandler... handlers) { EmbeddedChannel channel = new EmbeddedChannel(handlers); channel.pipeline().addLast( new ChannelInboundHandlerAdapter() { @@ -60,7 +60,7 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E } public static IMessage encodeDecode(IMessage msg, ChannelHandler[] encodeHandlers, - ChannelHandler[] decodeHandlers, final Logger logger) + ChannelHandler[] decodeHandlers, Logger logger) throws IOException { try { ByteBuf buf = encode(msg, logger, encodeHandlers); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestCodeGenerator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestCodeGenerator.java index 91025479..0a601908 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestCodeGenerator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestCodeGenerator.java @@ -50,7 +50,7 @@ public class TestCodeGenerator extends EPSTestCase { - private final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java");; + private final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java"); private final List baseOption = Arrays.asList("-g", "-classpath", System.getProperty("java.class.path"), "-d"); private final Path basePath = BASE_DIR.resolve("build").resolve("generated"); private final CodeGenerator codeGenerator = new CodeGenerator(); @@ -109,7 +109,7 @@ private void doCompile(String testName, int countElements, boolean adminOnly, bo StringWriter writer = new StringWriter(); try (PrintWriter printWriter = new PrintWriter(writer)) { - Assert.assertTrue(testName + ": " + writer.toString(), compiler.getTask(printWriter, fileManager,null, option, null, units).call()); + Assert.assertTrue(testName + ": " + writer, compiler.getTask(printWriter, fileManager,null, option, null, units).call()); } try (URLClassLoader classLoader = new URLClassLoader(new URL[] { compileFolder.toUri().toURL() }, getClass().getClassLoader())) { @@ -119,7 +119,7 @@ private void doCompile(String testName, int countElements, boolean adminOnly, bo String name = path.getFileName().toString(); boolean isField = CodeGenUtils.COMPONENTS_SUB_PACKAGE.equals(path.getParent().getFileName().toString()); if (underscoreAsPackageSeparator) { - name = path.getParent().getFileName().toString() + "_" + path.getFileName().toString(); + name = path.getParent().getFileName() + "_" + path.getFileName(); isField = CodeGenUtils.COMPONENTS_SUB_PACKAGE.equals(path.getParent().getParent().getFileName().toString()); } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestConfigurationReader.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestConfigurationReader.java index 99b6abd5..5de5d20e 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestConfigurationReader.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestConfigurationReader.java @@ -35,7 +35,7 @@ public class TestConfigurationReader extends EPSTestCase { @Test public void testConfigurationXmlNegative() throws Exception { - String dictName = this.getBaseDir() + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "negative.xml"; + String dictName = getBaseDir() + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "negative.xml"; IDictionaryStructureLoader loader = new XmlDictionaryStructureLoader(); @@ -48,11 +48,7 @@ public void testConfigurationXmlNegative() throws Exception } catch (EPSCommonException e) { e.printStackTrace(); String err = "A field null with an id S4 has neither a type nor a reference"; - if (e.getCause() != null) { - Assert.assertEquals(err, e.getCause().getMessage()); - } else { - Assert.assertEquals(err, e.getMessage()); - } + Assert.assertEquals(err, e.getCause() != null ? e.getCause().getMessage() : e.getMessage()); error = true; } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestHexDump.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestHexDump.java index 0b3a6a59..b0deebed 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestHexDump.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestHexDump.java @@ -26,6 +26,7 @@ public class TestHexDump { @Test public void testHexDump() { + @SuppressWarnings("ConfusingOctalEscapeSequence") byte[] b = "8=FIXT.1.1\0019=467\00135=AE\00149=PTGW\00156=User4\00134=409\00152=20100408-16:49:12.581\0011128=9\00135=AE\001487=0\00148=GB0031215220\00122=4\00132=600\00131=234.5\00160=20100408-16:49:12.528\00164=20100408\001574=4\001552=1\00154=2\00111=1270745351693\00137=O107I6_192\0011427=E107I6_369\001528=A\001453=4\001448=TEST\001447=C\001452=1\001448=User3\001447=C\001452=12\001448=User3\001447=C\001452=76\001448=Euro\001447=C\001452=17\001581=1\0011180=1\0011181=116\0011350=115\0011352=N\0011003=T107I6_64\001856=0\0011123=0\001828=0\001820=Z107I6_191\001150=F\00120111=1\001571=L107II_116\001455=GB0031215220\001456=4\00155=CCLl\00115=GBX\00110=174\001".getBytes(); String expected = "00000000: 383d 4649 5854 2e31 2e31 0139 3d34 3637 8=FIXT.1.1.9=467\r\n" + diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestMatrixActionsGenerator.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestMatrixActionsGenerator.java index a5edda20..b1a03dcf 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestMatrixActionsGenerator.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestMatrixActionsGenerator.java @@ -15,15 +15,17 @@ ******************************************************************************/ package com.exactpro.sf.util; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import org.junit.Test; + import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.messages.structures.loaders.IDictionaryStructureLoader; import com.exactpro.sf.common.messages.structures.loaders.XmlDictionaryStructureLoader; -import junit.framework.Assert; -import org.junit.Test; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; +import junit.framework.Assert; public class TestMatrixActionsGenerator extends AbstractTest { @@ -48,7 +50,8 @@ public void testMatrixActionsGenerator() throws Exception ); File actionFile = new File(path + "/com/exactpro/sf/actions/EXAMPLE_SndRcvMatrixActions.java"); - if (!actionFile.exists()) + if(!actionFile.exists()) { Assert.fail(); + } } } diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestStringUtil.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestStringUtil.java index fdea00e3..a9ad220f 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestStringUtil.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/util/TestStringUtil.java @@ -115,18 +115,18 @@ public void testSplit() @Test public void testReplaceChars() { - final String chars = " ?#;"; - final char replacement = '_'; + String chars = " ?#;"; + char replacement = '_'; - final String src0 = "#123 ?(A;B).csv"; + String src0 = "#123 ?(A;B).csv"; String dst0 = StringUtil.replaceChars(src0.trim(), chars, replacement); Assert.assertEquals("_123__(A_B).csv", dst0); - final String src1 = "API_Auction_Negative _Testing(OrdPlecement;Replace).csv"; + String src1 = "API_Auction_Negative _Testing(OrdPlecement;Replace).csv"; String dst1 = StringUtil.replaceChars(src1.trim(), chars, replacement); Assert.assertEquals("API_Auction_Negative__Testing(OrdPlecement_Replace).csv", dst1); - final String src2 = "USD_Real_Real_v8 Semi betta1.csv"; + String src2 = "USD_Real_Real_v8 Semi betta1.csv"; String dst2 = StringUtil.replaceChars(src2.trim(), chars, replacement); Assert.assertEquals("USD_Real_Real_v8_Semi_betta1.csv", dst2); diff --git a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/xml/StoreTest.java b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/xml/StoreTest.java index b5abce64..7b7fd839 100644 --- a/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/xml/StoreTest.java +++ b/BackEnd/Core/sailfish-core/src/test/java/com/exactpro/sf/xml/StoreTest.java @@ -36,6 +36,7 @@ import com.exactpro.sf.common.messages.structures.IMessageStructure; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.storage.FilterCriterion; +import com.exactpro.sf.storage.FilterCriterion.Operation; import com.exactpro.sf.storage.xml.DataMessage; import com.exactpro.sf.storage.xml.DataMessageConverter; import com.exactpro.sf.storage.xml.DataMessagePersister; @@ -137,7 +138,7 @@ public void dbStoring() throws Exception { public void dbRetrieve() throws Exception { DBPersister persister = new DBPersister(); - FilterCriterion crirerion = new FilterCriterion(XmlDataMessage.RAW_DATA, "0", FilterCriterion.Operation.LIKE); + FilterCriterion crirerion = new FilterCriterion(XmlDataMessage.RAW_DATA, "0", Operation.LIKE); List filterCriterions = new LinkedList(); filterCriterions.add(crirerion); DataMessage dataMessage = persister.getDataMessage(filterCriterions, null); diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/AML3LanguageFactory.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/AML3LanguageFactory.java index 3682bd9f..31ff0c05 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/AML3LanguageFactory.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/AML3LanguageFactory.java @@ -24,11 +24,11 @@ import com.exactpro.sf.scriptrunner.languagemanager.ICompatibilityChecker; import com.exactpro.sf.scriptrunner.languagemanager.ILanguageFactory; -@Description(value = "Automation Matrix Language version 3") +@Description("Automation Matrix Language version 3") public class AML3LanguageFactory implements ILanguageFactory { public static final SailfishURI URI = SailfishURI.unsafeParse("AML_v3"); - private ICompatibilityChecker checker = new AML3Checker(); + private final ICompatibilityChecker checker = new AML3Checker(); @Override public void init(ClassLoader... pluginClassLoaders) { @@ -56,6 +56,6 @@ public ICompatibilityChecker getChecker() { @Override public ClassLoader createClassLoader(URL binFolder, ClassLoader parent) { - return new URLClassLoader(new URL[] { binFolder }, this.getClass().getClassLoader()); + return new URLClassLoader(new URL[] { binFolder }, getClass().getClassLoader()); } } \ No newline at end of file diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/checkers/AML3Checker.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/checkers/AML3Checker.java index fcbd4a7d..19d91926 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/checkers/AML3Checker.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/checkers/AML3Checker.java @@ -27,10 +27,6 @@ public class AML3Checker implements ICompatibilityChecker { - public AML3Checker() { - // TODO Auto-generated constructor stub - } - @Override public boolean isCompatible(Method method) { int modifiers = method.getModifiers(); diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/AbstractCodeBuilder.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/AbstractCodeBuilder.java index 5a393f84..d536cd0f 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/AbstractCodeBuilder.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/AbstractCodeBuilder.java @@ -19,6 +19,9 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.Calendar; import java.util.Iterator; import java.util.List; @@ -27,11 +30,8 @@ import java.util.TreeSet; import java.util.stream.Collectors; -import com.exactpro.sf.aml.Tags; import org.apache.commons.lang3.StringUtils; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; +import org.apache.log4j.Logger; import com.exactpro.sf.actions.ActionUtil; import com.exactpro.sf.aml.AML; @@ -47,6 +47,7 @@ import com.exactpro.sf.aml.Hash; import com.exactpro.sf.aml.Id; import com.exactpro.sf.aml.Reference; +import com.exactpro.sf.aml.Tags; import com.exactpro.sf.aml.Type; import com.exactpro.sf.aml.script.AMLHashMap; import com.exactpro.sf.aml.script.CheckPoint; @@ -130,7 +131,7 @@ public void writeImports(TextOutputStream stream) throws IOException { imports.add(IScriptReport.class.getCanonicalName()); imports.add(Map.class.getCanonicalName()); imports.add(Outcome.class.getCanonicalName()); - imports.add(Outcome.Status.class.getCanonicalName()); + imports.add(Status.class.getCanonicalName()); imports.add(SailFishAction.class.getCanonicalName()); imports.add(SailFishTestCase.class.getCanonicalName()); imports.add(ScriptContext.class.getCanonicalName()); @@ -183,7 +184,7 @@ public void writeMessagesMapDefinition(TextOutputStream stream, String mapName) public abstract void writeActionClassDefinition(TextOutputStream stream, String className) throws IOException; public void writeLogger(TextOutputStream stream, String loggerName, boolean isStatic) throws IOException { - String loggerClass = org.apache.log4j.Logger.class.getCanonicalName(); + String loggerClass = Logger.class.getCanonicalName(); String varPrefix = isStatic ? "static " : ""; stream.writeLine(1, "%s%s %s = %2$s.getLogger(\"TimeStamps\");", varPrefix, loggerClass, loggerName); diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/CodeGenerator_new.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/CodeGenerator_new.java index a5430b7c..297c1a2e 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/CodeGenerator_new.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/CodeGenerator_new.java @@ -49,7 +49,6 @@ import com.exactpro.sf.aml.AMLException; import com.exactpro.sf.aml.AMLLangConst; import com.exactpro.sf.aml.AMLLangUtil; -import com.exactpro.sf.aml.AMLList; import com.exactpro.sf.aml.AMLPrivateActions; import com.exactpro.sf.aml.AMLSettings; import com.exactpro.sf.aml.AMLTestCase; @@ -105,7 +104,7 @@ public class CodeGenerator_new implements ICodeGenerator { private static final Logger logger = LoggerFactory.getLogger(CodeGenerator_new.class); - protected final static String EOL = System.getProperty("line.separator"); + protected static final String EOL = System.getProperty("line.separator"); private final Set imports = new HashSet<>(); public static final String MAP_NAME = "messages"; @@ -121,10 +120,10 @@ public class CodeGenerator_new implements ICodeGenerator { private final AlertCollector alertCollector; private Set definedReferences; // references defined in the current test case - private Map definedServiceNames = new HashMap<>(); + private final Map definedServiceNames = new HashMap<>(); private final Set resolvedServiceNames = new HashSet<>(); - private int cycleCount = 0; + private int cycleCount; public static final String TAB1 = "\t"; public static final String TAB2 = "\t\t"; @@ -135,23 +134,7 @@ public class CodeGenerator_new implements ICodeGenerator { public static final String ERROR_HOOK = "line:uid:reference:column:value"; public static final int MAX_SETTERS_PER_CLASS = 10000; - /** - * Value starts with this string should interpreted as java code - * and will be used without transformation. - * Before insertion it should be checked via compilation. - */ - private static final String TAG_INTERPRET_AS_JAVA = "java:"; - - private static final String BEGIN_REFERENCE = "${"; - private static final String END_REFERENCE = "}"; - - private static final String BEGIN_STATIC = "%{"; - private static final String END_STATIC = "}"; - - private static final String BEGIN_FUNCTION = "#{"; - private static final String END_FUNCTION = "}"; - - private boolean autoStart; + private boolean autoStart; private AMLSettings amlSettings; @@ -162,13 +145,13 @@ public class CodeGenerator_new implements ICodeGenerator { private int loadedTestCases; private int totalActions; - OldImpl impl; - NewImpl newImpl; + private OldImpl impl; + private NewImpl newImpl; private ScriptContext scriptContext; - private final static int CAPACITY_4K = 4096; - private final static int CAPACITY_128K = 131072; + private static final int CAPACITY_4K = 4096; + private static final int CAPACITY_128K = 131072; private final TestCaseCodeBuilder tcCodeBuilder; @@ -215,8 +198,8 @@ public void init(IWorkspaceDispatcher workspaceDispatcher, setAutoStart(amlSettings.getAutoStart()); this.amlSettings = amlSettings; - this.impl.setContinueOnFailed(amlSettings.getContinueOnFailed()); - this.newImpl.setContinueOnFailed(amlSettings.getContinueOnFailed()); + impl.setContinueOnFailed(amlSettings.getContinueOnFailed()); + newImpl.setContinueOnFailed(amlSettings.getContinueOnFailed()); } protected void setAutoStart(boolean b) { @@ -224,12 +207,12 @@ protected void setAutoStart(boolean b) { } protected boolean getAutoStart() { - return this.autoStart; + return autoStart; } @Override public ScriptContext getScriptContext() { - return this.scriptContext; + return scriptContext; } /* (non-Javadoc) @@ -263,13 +246,13 @@ public GeneratedScript generateCode(List testCases, List testCases, List beforeTCBlocks, List afterTCBlocks, TextOutputStream mainClass, GeneratedScript script) throws AMLException, IOException, InterruptedException @@ -285,7 +268,7 @@ private void writeJavaClass(List testCases, List befor writeTestCases(beforeTCBlocks, mainClass, script); scriptContext.getServiceList().addAll(resolvedServiceNames); - final String servNames = tcCodeBuilder.getServiceNamesArray(resolvedServiceNames); + String servNames = tcCodeBuilder.getServiceNamesArray(resolvedServiceNames); tcCodeBuilder.writeBeforeMatrixPreparations(mainClass, servNames, getAutoStart()); tcCodeBuilder.writeBeforeTestCasePreparations(mainClass, servNames, LOGGER_NAME, CONTEXT_NAME, amlSettings.isRunNetDumper(), @@ -308,7 +291,7 @@ private void writeTestCases(List testCases, TextOutputStream mainCl try { AMLTestCase tc = testCases.get(i); - if(tc.getActions().size() == 0) { + if(tc.getActions().isEmpty()) { continue; } @@ -319,7 +302,7 @@ private void writeTestCases(List testCases, TextOutputStream mainCl } String actionClassName = String.format("%s_Actions_%s", type.name(), i + 1); - File file = new File(this.dir, actionClassName + ".java"); + File file = new File(dir, actionClassName + ".java"); actionClass = new TextOutputStream(new FileOutputStream(file)); script.addFile(file); @@ -394,7 +377,7 @@ private void writeTestCase(AMLTestCase tc, TextOutputStream mainClass, TextOutpu line = writeServiceNameDefinition(action); break; default: - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Java statement not implemented: " + statement)); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Java statement not implemented: " + statement)); break; } @@ -424,13 +407,13 @@ private void writeTestCase(AMLTestCase tc, TextOutputStream mainClass, TextOutpu if (methodBody == null) { if(!action.isStaticAction()) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Action already generated [generation path: " + action.getGenerationPath() + "] or another error occured...")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Action already generated [generation path: " + action.getGenerationPath() + "] or another error occured...")); } continue; } - if (methodBody.length() != 0) { + if(!methodBody.isEmpty()) { String methodName = String.format("Action_%s_%s", ++actionNumber, action.getActionURI().getResourceName()); mainClass.writeLine(3, "%s.%s(%s, %s);", actionClassName, methodName, MAP_NAME, CONTEXT_NAME); @@ -481,16 +464,16 @@ private void writeTestCase(AMLTestCase tc, TextOutputStream mainClass, TextOutpu actionClass.writeLine("}"); actionClass.close(); - if (this.alertCollector.getCount(AlertType.ERROR) != 0) { - String s = StringUtil.getSSuffix(this.alertCollector.getCount(AlertType.ERROR)); + if(alertCollector.getCount(AlertType.ERROR) != 0) { + String s = StringUtil.getSSuffix(alertCollector.getCount(AlertType.ERROR)); if (logger.isErrorEnabled()) { - for (Alert alert : this.alertCollector.getAlerts(AlertType.ERROR)) { + for(Alert alert : alertCollector.getAlerts(AlertType.ERROR)) { logger.error(alert.toString()); } } - throw new AMLException("Error" + s + " in matrix", this.alertCollector); + throw new AMLException("Error" + s + " in matrix", alertCollector); } } @@ -501,7 +484,7 @@ private String writeStaticDefinition(AMLTestCase tc, AMLAction action) { } if (action.getGenerateStatus() == AMLGenerateStatus.GENERATING) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); return null; } @@ -521,7 +504,7 @@ private String writeStaticDefinition(AMLTestCase tc, AMLAction action) { try { newValue = TypeHelper.convertValue(action.getStaticType(), newValue); } catch (AMLException e) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), Column.StaticType.getName(), e.getMessage())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), Column.StaticType.getName(), e.getMessage())); return null; } } else { @@ -552,7 +535,7 @@ private String writeJavaStatement(AMLTestCase tc, AMLAction action, JavaStatemen switch (word) { case BEGIN_LOOP: - String in = "i"+(cycleCount++); + String in = "i" + cycleCount++; String column = Column.MessageCount.getName(); Value count = new Value(action.getMessageCount()); @@ -591,7 +574,7 @@ private String writeJavaStatement(AMLTestCase tc, AMLAction action, JavaStatemen case END_IF: return TAB3+"}"+EOL; default: - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Java statement not implemented: "+word)); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Java statement not implemented: " + word)); return null; } @@ -711,20 +694,22 @@ public String createFillSettings(AMLTestCase tc, AMLAction action, String messag getMethod(alertCollector, DefaultSettings.class, "setMetaContainer", action, null, MetaContainer.class); sb.append(TAB2+varName+".setMetaContainer(metaContainer);"+EOL); - if (false == action.getFailUnexpected().equals("")) + if(!"".equals(action.getFailUnexpected())) { getMethod(alertCollector, DefaultSettings.class, "setFailUnexpected", action, Column.FailUnexpected.getName(), String.class); String s = action.getFailUnexpected(); - if (s.equalsIgnoreCase("Y") || s.equalsIgnoreCase("A")) - sb.append(TAB2+varName+".setFailUnexpected(\""+s+"\");"+EOL); + if("Y".equalsIgnoreCase(s) || "A".equalsIgnoreCase(s)) { + sb.append(TAB2 + varName + ".setFailUnexpected(\"" + s + "\");" + EOL); + } } else { getMethod(alertCollector, DefaultSettings.class, "setFailUnexpected", action, Column.FailUnexpected.getName(), String.class); String s = environmentManager.getEnvironmentSettings().getFailUnexpected(); - if (s.equalsIgnoreCase("Y") || s.equalsIgnoreCase("A")) - sb.append(TAB2+varName+".setFailUnexpected(\""+s+"\");"+EOL); + if("Y".equalsIgnoreCase(s) || "A".equalsIgnoreCase(s)) { + sb.append(TAB2 + varName + ".setFailUnexpected(\"" + s + "\");" + EOL); + } } - if (false == action.getDescrption().equals("")) + if(!"".equals(action.getDescrption())) { getMethod(alertCollector, DefaultSettings.class, "setDescription", action, Column.Description.getName(), String.class); @@ -871,406 +856,18 @@ protected static Method getMethod(AlertCollector alertCollector, { sb.delete(sb.length()-2, sb.length()); } - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot find setting method '"+methodName+"("+sb.toString()+")' for column "+column+" in class '"+clazz.getCanonicalName()+"'")); - return null; - } - - static Method getMethod(AMLList errors, Class clazz, String methodName, AMLAction action, String column) - { - String ref = action.getReference() == null ? "" : action.getReference(); - if (clazz == null) { - errors.add("Error in line "+action.getLine()+" ["+ref+"]: Class cannot be null."); - return null; - } - - if (methodName == null) { - errors.add("Error in line "+action.getLine()+" ["+ref+"]: Setting method name cannot be null."); - return null; - } - - if ("".equals(methodName)) - { - errors.add("Error in line "+action.getLine()+" ["+ref+"]: Setting method name cannot be empty."); - return null; - } - - Class tempClass = clazz; - while (tempClass != null) - { - Method[] methods = tempClass.getDeclaredMethods(); - for (Method method : methods) - { - if (method.getName().equals(methodName)) - return method; - } - tempClass = tempClass.getSuperclass(); - } - errors.add("Error in line "+action.getLine()+" ["+ref+"]: can not find setting method '"+methodName+"' for column "+column+" in class '"+clazz.getCanonicalName()+"'"); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot find setting method '" + methodName + "(" + sb + ")' for column " + column + " in class '" + clazz.getCanonicalName() + "'")); return null; } - public void substituteReference(AMLTestCase tc, AMLAction action, AlertCollector alertCollector, String column, Value value) - { - logger.debug("substituteReference: column: {}; Value: {}", column ,value); - if (column == null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Key is null")); - return; - } - - if (value.getValue() == null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Value is null for parameter '"+column+"'")); - return; - } - - if ("".equals(value.getValue())) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Empty value found for parameter '"+column+"'")); - return; - } - - // value is java code - - if (value.getValue().toLowerCase().startsWith(TAG_INTERPRET_AS_JAVA)) - { - String v = value.getValue().substring(TAG_INTERPRET_AS_JAVA.length()).trim(); - value.setValue(v); - value.setReference(true); - } - - if (value.getValue().contains(BEGIN_REFERENCE)) - { - // expand complex value - - int index1 = value.getValue().indexOf(BEGIN_REFERENCE); - while (index1 != -1) - { - index1 = expandReferenceValue(tc, action, column, value, index1, alertCollector); - } - } - - if (value.getValue().contains(BEGIN_STATIC)) - { - // expand static value - - int index1 = value.getValue().indexOf(BEGIN_STATIC); - while (index1 != -1) - { - index1 = expandStaticValue(tc, action, column, value, index1, alertCollector); - } - } - - if (value.getValue().contains(BEGIN_FUNCTION)) - { - // expand function - - int index1 = value.getValue().indexOf(BEGIN_FUNCTION); - while (index1 != -1) - { - index1 = expandUtilityFunction(action, column, value, index1, alertCollector); - } - } - } - - private int expandReferenceValue(AMLTestCase tc, AMLAction action, - String column, Value value, int index, AlertCollector alertCollector) - { - - int index2 = value.getValue().indexOf(END_REFERENCE, index); - if (index2 == -1) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Unbalansed brackets found in column '"+column+"'.")); - return -1; - } - - // get reference to previous message and field name - - String var = value.getValue().substring(index+BEGIN_REFERENCE.length(), index2); - String lineRef; - String columnRef; - - if (var.length() == 0) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference is empty column '"+column+"'.")); - return -1; - } - - String[] arr = StringUtil.split(var, ":"); - if (arr.length == 0 || arr.length > 2) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Invalid reference format in column '"+column+"': '"+var+"'. " - +"Expected format: ${reference:column} or ${reference}.")); - return -1; - } - - lineRef = arr[0].trim(); // reference to message - columnRef = (arr.length == 2) ? arr[1].trim() : column; // reference to field - - if (lineRef.length() == 0) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to row is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); - return -1; - } - if (columnRef.length() == 0) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to column is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); - return -1; - } - - // find action by reference - - AMLAction refAction = tc.findActionByRef(lineRef); - - if (refAction == null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to unknown action '"+lineRef - +"' is found in column '"+column+"': '"+value.getOrigValue()+"'.")); - return -1; - } - - // ${ref:field} linked to submessage we should not be expanded immediately - // because type of the submessage is not yet defined until it expanded - if (!definedReferences.contains(lineRef)) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference '"+lineRef+"' is not yet defined in column '" - +column+"': '"+value.getOrigValue()+"'.")); - return -1; - } - - Class messageType = refAction.getActionInfo().getReturnType(); - - if(messageType == void.class) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot refer to action.")); - return -1; - } - - // check field in referred message - - boolean columnExist = action.getHeaders().contains(columnRef); - boolean getterExist = false; - if (columnExist == false) - { - Method[] methods = messageType.getMethods(); - for (Method method : methods) - { - if (method.getName().equalsIgnoreCase("get"+columnRef)) { - getterExist = true; - break; - } - } - } - - - if (false == (getterExist || columnExist)) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to unknown column '" - +columnRef+"' is found in column '"+column+"': '"+value.getOrigValue()+"'.")); - return -1; - } - - // replace reference - - IGetterSetterGenerator gs = (IGetterSetterGenerator)adapterManager.getAdapter(messageType, IGetterSetterGenerator.class); - if (gs == null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference error in column '"+column+"': " - +"No getter/setter factory registered for class '"+messageType - +"' in line "+refAction.getLine()+" ["+lineRef+"]")); - return -1; - } - - String getter = ""; - String source = "(("+messageType.getCanonicalName()+")"+CodeGenerator_new.MAP_NAME+".get(\""+lineRef+"\"))"; - try { - getter = gs.getGetter(messageType, columnRef, source); - } catch (AMLException e) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '"+column+"': "+e.getMessage())); - return -1; - } - - if (getter == null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference error in column '"+column+"': "+ - "Cannot extract value '"+columnRef+"' from message '" - +messageType.getCanonicalName()+"' in line " - +refAction.getLine()+"["+lineRef+"].")); - return -1; - } - - String src = BEGIN_REFERENCE+var+END_REFERENCE; - String v = value.getValue().replaceFirst(Pattern.quote(src), getter); - value.setValue(v); - value.setReference(true); - - // search for the next reference - - index = value.getValue().indexOf(BEGIN_REFERENCE); - - return index; - } - - private int expandStaticValue(AMLTestCase tc, AMLAction action, - String column, Value value, int index, AlertCollector alertCollector) - { - - int index2 = value.getValue().indexOf(END_STATIC, index); - - if (index == -1) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Unbalansed brackets found in column '"+column+"'.")); - return -1; - } - - // get reference to previous message and field name - - String val = value.getValue().substring(index+2, index2); - if (val.length() == 0) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference is empty in column '"+column+"'.")); - return -1; - } - - if (val.contains(":")) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Invalid reference format to static variable in column '"+column+"': '"+val+"'. " - +"Expected format: %{reference}.")); - return -1; - } - - // find action by reference - - AMLAction refAction = tc.findActionByRef(val); - - if (refAction == null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Undefined reference ["+val - +"] is found column '" - +column+"': '"+value.getOrigValue()+"'.")); - return -1; - } - - - // replace reference - - String var = value.getValue().substring(index, index2+1); - String targ = "("+refAction.getStaticType()+")("+CodeGenerator_new.STATIC_MAP_NAME+".get(\""+val+"\"))"; - String v = value.getValue().replaceFirst(Pattern.quote(var), targ); - value.setValue(v); - value.setReference(true); - - // search for the next reference - - index = value.getValue().indexOf(BEGIN_STATIC); - - return index; - } - - private int expandUtilityFunction(AMLAction action, - String column, Value value, int index, AlertCollector alertCollector) - throws SecurityException - { - - int index2 = CodeGenerator_new.indexOfCloseBracket(value.getValue(), BEGIN_FUNCTION, END_FUNCTION, index); - if (index2 == -1) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Unbalansed brackets in column '"+column+"'.")); - return -1; - } - - // get name of the static method declared in action class - // with @UtilFunction annotation - - String var = value.getValue().substring(index+2, index2); - - if (var.length() == 0) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Utility function name is empty in column '"+column+"'.")); - return -1; - } - - int openSpaceIndex = var.indexOf("("); - - if (openSpaceIndex == -1) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Syntaxis error in column '"+column+"': missed close bracket ')'.")); - return -1; - } - - int closeSpaceIndex = CodeGenerator_new.indexOfCloseBracket(var, "(", ")", openSpaceIndex); - - if (closeSpaceIndex == -1) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Syntaxis error in column '"+column+"': missed close bracket ')'.")); - return -1; - } - - SailfishURI utilityURI; - - try { - utilityURI = SailfishURI.parse(var.substring(0, openSpaceIndex).trim()); - } catch(SailfishURIException e) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, e.getMessage())); - return -1; - } - - StringBuilder utilityArgs = new StringBuilder(var.substring(openSpaceIndex + 1, closeSpaceIndex).trim()); - - if(utilityArgs.length() > 0) { - utilityArgs.insert(0, ", "); - } - utilityArgs.append(')').append(var.substring(closeSpaceIndex + 1).trim()); - - if (action.getStaticType() != null) - { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Invalid use of function in static variable definition: "+var)); - return -1; - } - - if (action.getActionInfo() == null) - { - throw new NullPointerException("action.getActionInfo()"); - } - - ActionInfo actionInfo = action.getActionInfo(); - UtilityInfo utilityInfo; - - try { - utilityInfo = actionManager.getUtilityInfo(actionInfo.getURI(), utilityURI); - } catch(SailfishURIException e) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, e.getMessage())); - return -1; - } - - if(utilityInfo == null) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Unable to resolve utility function: " + utilityURI)); - return -1; - } - - String src = BEGIN_FUNCTION+var+END_FUNCTION; - String targ = String.format("%s(%s.parse(\"%s\")%s", UTILITY_MANAGER_CALL, SailfishURI.class.getSimpleName(), utilityInfo.getURI(), utilityArgs); - targ = targ.replace("\\", "\\\\").replace("$", "\\$"); - - String v = value.getValue().replaceFirst(Pattern.quote(src), targ); - value.setValue(v); - value.setReference(true); - value.addParameter(new RefParameter(CodeGenerator_new.UTILITY_MANAGER_VARIABLE, CodeGenerator_new.UTILITY_MANAGER)); - - // search next function - - index = value.getValue().indexOf(BEGIN_FUNCTION); - - return index; - } - - /** + /** * Compile simple class to check whether value valid. * If compilation failed appropriate message will be stored in ErrorStore. * @throws AMLException */ protected final String compileTest(File javaFile, File classFile) throws AMLException { - String status = null; - try { + try { List args = new LinkedList<>(); args.add("-classpath"); args.add(compilerClassPath); @@ -1300,11 +897,11 @@ protected final String compileTest(File javaFile, File classFile) throws AMLExce classFile.delete(); } - } catch (IOException e) { + return null; + } catch(IOException e) { throw new AMLException("Failed write to file '"+javaFile+"':"+e.getLocalizedMessage(), e); } - return status; - } + } private void testCode(List testCases) throws WorkspaceSecurityException, AMLException, FileNotFoundException, IOException { progressChanged(60); @@ -1368,13 +965,13 @@ private void parseErrors(String error) String value = new String(bytes); error = "Invalid value in column '"+vals[3]+"': "+value; if (!alertCollector.contains(AlertType.ERROR, error)) { - this.alertCollector.add(new Alert(Long.parseLong(vals[0]), Long.parseLong(vals[1]), vals[2], vals[3], error)); + alertCollector.add(new Alert(Long.parseLong(vals[0]), Long.parseLong(vals[1]), vals[2], vals[3], error)); } } } return; } - this.alertCollector.add(new Alert(error)); + alertCollector.add(new Alert(error)); } @@ -1383,7 +980,7 @@ private void parseErrors(String error) */ @Override public AlertCollector getAlertCollector() { - return this.alertCollector; + return alertCollector; } /* (non-Javadoc) @@ -1399,14 +996,14 @@ public void cleanup() definedServiceNames.clear(); resolvedServiceNames.clear(); - if(this.imports != null) { - this.imports.clear(); + if(imports != null) { + imports.clear(); } } private void progressChanged(int progress) { - for (IProgressListener listener : this.progressListeners) + for(IProgressListener listener : progressListeners) { listener.onProgressChanged(progress); } diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImpl.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImpl.java index a01eed63..30523720 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImpl.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImpl.java @@ -17,11 +17,12 @@ import static com.exactpro.sf.aml.AMLLangUtil.isFunction; import static com.exactpro.sf.common.messages.structures.StructureUtils.getAttributeValue; +import static com.exactpro.sf.common.util.StringUtil.enclose; +import static com.exactpro.sf.common.util.StringUtil.toJavaString; import static java.lang.String.format; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; @@ -75,7 +76,7 @@ public class NewImpl { private static final Logger logger = LoggerFactory.getLogger(NewImpl.class); - protected final static String EOL = System.getProperty("line.separator"); + protected static final String EOL = System.getProperty("line.separator"); public static final String TAB1 = "\t"; public static final String TAB2 = "\t\t"; @@ -89,7 +90,7 @@ public class NewImpl { public static final String STATIC_MAP_NAME = CONTEXT_NAME+".getStaticMap()"; public static final String SERVICE_MAP_NAME = CONTEXT_NAME+".getServiceNames()"; private static final String LOGGER_NAME = "logger"; - private boolean continueOnFailed = false; + private boolean continueOnFailed; private List variables; private final AlertCollector alertCollector; @@ -98,8 +99,8 @@ public class NewImpl { private final IActionManager actionManager; private final IUtilityManager utilityManager; - private final static int CAPACITY_4K = 4096; - private final static int CAPACITY_128K = 131072; + private static final int CAPACITY_4K = 4096; + private static final int CAPACITY_128K = 131072; public NewImpl(AlertCollector alertCollector, IAdapterManager adapterManager, IConnectionManager connectionManager, IDictionaryManager dictionaryManager, IActionManager actionManager, IUtilityManager utilityManager, IStaticServiceManager staticServiceManager, CodeGenerator_new codeGenerator) { this.dictionaryManager = dictionaryManager; @@ -122,7 +123,7 @@ public String writeSendMessage(AMLTestCase tc, AMLAction action, List } if (action.getGenerateStatus() == AMLGenerateStatus.GENERATING) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); return null; } @@ -145,7 +146,7 @@ public String writeSendMessage(AMLTestCase tc, AMLAction action, List if (type != null) { if (!action.hasDictionaryURI()) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), Column.Dictionary.getName(), "Dictionary is not specified")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), Column.Dictionary.getName(), "Dictionary is not specified")); return null; } @@ -176,7 +177,7 @@ private String writeFillComparisonErrorsDefinition(AMLTestCase tc, AMLAction act IDictionaryStructure dictionary = getDictionary(action.getDictionaryURI()); if (dictionary == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Can't find dictionary [" + action.getDictionaryURI() + "]")); return ""; } @@ -192,11 +193,11 @@ private String writeFillMetaContainer(AMLTestCase tc, AMLAction action, ActionIn if (action.getFailUnexpected() != null && !"".equals(action.getFailUnexpected())) // TODO: do this on per Repeating group level. { - failUnexpected = TypeConverter.convert(java.lang.String.class, action.getFailUnexpected()); + failUnexpected = TypeConverter.convert(String.class, action.getFailUnexpected()); } if (parentVar != null) { - sb.append(TAB2+metaContainer.getName()+" = createMetaContainer(" + parentVar + ", " + TypeConverter.convert(java.lang.String.class, field) + ", " + failUnexpected + ");" + EOL); + sb.append(TAB2 + metaContainer.getName() + " = createMetaContainer(" + parentVar + ", " + TypeConverter.convert(String.class, field) + ", " + failUnexpected + ");" + EOL); } else { sb.append(TAB2+metaContainer.getName()+" = createMetaContainer(" + failUnexpected + ");" + EOL); } @@ -262,11 +263,7 @@ private String createSendCall(AMLTestCase tc, AMLAction action, sb.append(settings.getName()); sb.append(".getCheckPoint(), "); - if(action.hasTag()) { - sb.append(StringUtil.enclose(StringUtil.toJavaString(action.getTag()), '"')); - } else { - sb.append("null"); - } + sb.append(action.hasTag() ? enclose(toJavaString(action.getTag()), '"') : "null"); sb.append(","); sb.append(action.getHash()); @@ -282,7 +279,7 @@ private String createSendCall(AMLTestCase tc, AMLAction action, } ActionInfo actionInfo = action.getActionInfo(); - String mainCallArgs = String.format("%s.parse(\"%s\"), %s", SailfishURI.class.getSimpleName(), actionInfo.getURI(), settings.getName()); + String mainCallArgs = format("%s.parse(\"%s\"), %s", SailfishURI.class.getSimpleName(), actionInfo.getURI(), settings.getName()); Variable outputVariable = null; if (returnType != void.class) { @@ -337,13 +334,13 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var { SailfishURI dictionaryURI = action.getDictionaryURI(); if (dictionaryURI == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Empty namespace for action: " + action.getActionURI())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Empty namespace for action: " + action.getActionURI())); return ""; } IDictionaryStructure dictionary = getDictionary(dictionaryURI); if (dictionary == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Can't find dictionary [" + dictionaryURI + "]")); return ""; } @@ -352,7 +349,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var IFieldStructure dm = dictionary.getMessages().get(action.getMessageTypeColumn()); if (dm == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Dictionary "+action.getDictionaryURI()+ + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Dictionary " + action.getDictionaryURI() + " does not contain message "+action.getMessageTypeColumn())); return ""; } @@ -378,7 +375,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var if(templateDictionary == null || !templateDictionary.matches(dictionaryURI)) { alertCollector.add(new Alert(action.getLine(), action.getReference(), Column.Template.getName(), - String.format("Template's dictionary '%s' differs from this action's dictionary '%s'. Template: %s", templateDictionary, dictionaryURI, template))); + format("Template's dictionary '%s' differs from this action's dictionary '%s'. Template: %s", templateDictionary, dictionaryURI, template))); return StringUtils.EMPTY; } @@ -387,7 +384,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var if(!StringUtils.equals(messageType, templateMessageType)) { alertCollector.add(new Alert(action.getLine(), action.getReference(), Column.Template.getName(), - String.format("Template's message type '%s' differs from this action's message type '%s'. Template: %s", templateMessageType, messageType, template))); + format("Template's message type '%s' differs from this action's message type '%s'. Template: %s", templateMessageType, messageType, template))); return StringUtils.EMPTY; } @@ -398,7 +395,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var sb.append(")"); sb.append(CodeGenerator_new.MAP_NAME); sb.append(".get("); - sb.append(StringUtil.enclose(template, '"')); + sb.append(enclose(template, '"')); sb.append(")).cloneMessage();"); sb.append(EOL); } else { @@ -422,7 +419,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var boolean isCollection = AMLLangUtil.isCollection(value.getValue()); fStruct = new FieldStructure(null, null, null, null, null, null, null, false, isCollection, false, null); } else { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Message '"+dm.getName()+"' in namespace '"+dm.getNamespace()+"' does not contain '"+fieldName+"' field")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Message '" + dm.getName() + "' in namespace '" + dm.getNamespace() + "' does not contain '" + fieldName + "' field")); continue; } } @@ -439,7 +436,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var try { refs = AMLLangUtil.getReferences(value.getValue()); } catch (AMLException e) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': " + e.getMessage())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': " + e.getMessage())); continue; } @@ -459,7 +456,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var } } - value.setValue("[" + newValue.toString() + "]"); + value.setValue("[" + newValue + "]"); } for(String ref : refs) { @@ -491,7 +488,7 @@ private String createSendMessageDefinition(AMLTestCase tc, AMLAction action, Var String strValue = value.getValue(); if(!AMLLangUtil.isCollection(strValue)) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': Invalid collection format '" + value.getValue() + "'")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': Invalid collection format '" + value.getValue() + "'")); continue; } @@ -534,12 +531,12 @@ else if (fStruct.isSimple()) if(collection) { if(!AMLLangUtil.isCollection(value.getValue())) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': Invalid collection format '" + value.getValue() + "'")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': Invalid collection format '" + value.getValue() + "'")); continue; } if(isDirty) { - value.setValue(String.format("(($ != null ? $.toString() : 'null') in %s)", value.getValue())); + value.setValue(format("(($ != null ? $.toString() : 'null') in %s)", value.getValue())); } sb.append(TAB2+inputVariable.getName()+".addField(\""+fieldName+"\", "); @@ -562,13 +559,13 @@ else if (fStruct.isSimple()) else if (fStruct.isComplex()) { if(!AMLLangUtil.isSubmessage(value.getValue())) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': Invalid collection format '" + value.getValue() + "'")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': Invalid collection format '" + value.getValue() + "'")); continue; } if (!fStruct.isCollection()) { if (value.getValue().split(",").length > 1) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Cannot set multiple values to field " + fStruct.getName())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Cannot set multiple values to field " + fStruct.getName())); continue; } @@ -615,7 +612,7 @@ private void writeServiceFieldDefinition(Value value, AMLAction action, String f return; } - elements[i] = StringUtil.enclose(service.getServiceName().getServiceName()); + elements[i] = enclose(service.getServiceName().getServiceName()); } valueString = "Arrays.asList(" + StringUtils.join(elements, ", ") + ")"; @@ -631,13 +628,13 @@ private void writeServiceFieldDefinition(Value value, AMLAction action, String f return; } - valueString = StringUtil.enclose(service.getServiceName().getServiceName()); + valueString = enclose(service.getServiceName().getServiceName()); } sb.append(TAB2); sb.append(inputVariable.getName()); sb.append(".addField("); - sb.append(StringUtil.enclose(fieldName)); + sb.append(enclose(fieldName)); sb.append(", "); sb.append(valueString); sb.append(");//service name field"); @@ -650,7 +647,7 @@ private boolean isValueTypeOf(String v, JavaType valueType) { } boolean isEmptyString(String string) { - return string == null || string.equals(""); + return string == null || "".equals(string); } private String getEnumValue(String value, IFieldStructure enumField, long line, long uid, String column, boolean isDirty) { @@ -676,17 +673,17 @@ private String castValue(Object object, JavaType valueType, long line, long uid, { switch (valueType) { - case JAVA_LANG_BOOLEAN: { - String value = object.toString().toLowerCase(); - if (value.equals("n") || value.equals("false")) { + case JAVA_LANG_BOOLEAN: + String value = object.toString().toLowerCase(); + if("n".equals(value) || "false".equals(value)) { return "false"; - } else if (value.equals("y") || value.equals("true")) { + } else if("y".equals(value) || "true".equals(value)) { return "true"; } - alertCollector.add(new Alert(line, uid, null, column, "Unknown boolean value: " + value)); + alertCollector.add(new Alert(line, uid, null, column, "Unknown boolean value: " + value)); return null; - } - case JAVA_LANG_BYTE: return "(byte)("+object+")"; + case JAVA_LANG_BYTE: + return "(byte)(" + object + ")"; case JAVA_LANG_CHARACTER: return "'"+object+"'"; case JAVA_TIME_LOCAL_DATE_TIME: case JAVA_TIME_LOCAL_DATE: @@ -695,7 +692,7 @@ private String castValue(Object object, JavaType valueType, long line, long uid, return null; case JAVA_LANG_SHORT: return "(short)("+object+")"; case JAVA_LANG_INTEGER: return "(int)("+object+")"; - case JAVA_LANG_LONG: { + case JAVA_LANG_LONG: try { String string = object.toString(); Long.valueOf(StringUtils.removeEndIgnoreCase(string, "L")); @@ -704,11 +701,12 @@ private String castValue(Object object, JavaType valueType, long line, long uid, alertCollector.add(new Alert(line, uid, null, column, "Invalid long value: " + object)); return null; } - } - case JAVA_LANG_FLOAT: return "(float)("+object+")"; + case JAVA_LANG_FLOAT: + return "(float)(" + object + ")"; case JAVA_LANG_DOUBLE: return "(double)("+object+")"; case JAVA_MATH_BIG_DECIMAL: return "new java.math.BigDecimal(\""+object+"\")"; - case JAVA_LANG_STRING: return "\""+StringUtil.toJavaString(object.toString())+"\""; + case JAVA_LANG_STRING: + return "\"" + toJavaString(object.toString()) + "\""; default: return null; } } @@ -717,17 +715,17 @@ private String castReceiveValue(Object object, JavaType valueType, AlertCollecto { switch (valueType) { - case JAVA_LANG_BOOLEAN: { - String value = object.toString().toLowerCase(); - if (value.equals("n") || value.equals("false")) { + case JAVA_LANG_BOOLEAN: + String value = object.toString().toLowerCase(); + if("n".equals(value) || "false".equals(value)) { return "false"; - } else if (value.equals("y") || value.equals("true")) { + } else if("y".equals(value) || "true".equals(value)) { return "true"; } - alertCollector.add(new Alert(line, uid, null, column, "Unknown boolean value: " + value)); + alertCollector.add(new Alert(line, uid, null, column, "Unknown boolean value: " + value)); return null; - } - case JAVA_LANG_BYTE: return "(byte)("+object+")"; + case JAVA_LANG_BYTE: + return "(byte)(" + object + ")"; case JAVA_LANG_CHARACTER: return "'"+object+"'.charAt(0)"; // case CHAR: return object.toString(); case JAVA_TIME_LOCAL_DATE_TIME: @@ -737,7 +735,7 @@ private String castReceiveValue(Object object, JavaType valueType, AlertCollecto return null; case JAVA_LANG_SHORT: return "(short)("+object+")"; case JAVA_LANG_INTEGER: return "(int)("+object+")"; - case JAVA_LANG_LONG: { + case JAVA_LANG_LONG: try { String string = object.toString(); Long.valueOf(StringUtils.removeEndIgnoreCase(string, "L")); @@ -746,18 +744,18 @@ private String castReceiveValue(Object object, JavaType valueType, AlertCollecto alertCollector.add(new Alert(line, uid, null, column, "Invalid long value: " + object)); return null; } - } - case JAVA_LANG_FLOAT: return "(float)("+object+")"; + case JAVA_LANG_FLOAT: + return "(float)(" + object + ")"; case JAVA_LANG_DOUBLE: return "(double)("+object+")"; - case JAVA_MATH_BIG_DECIMAL: { - try { - new BigDecimal(object.toString()); - return "new BigDecimal(\"" + object.toString() + "\")"; - } catch(NumberFormatException e) { - return "" + object+""; - } - } - case JAVA_LANG_STRING: return "\""+StringUtil.toJavaString(object.toString())+"\""; + case JAVA_MATH_BIG_DECIMAL: + try { + new BigDecimal(object.toString()); + return "new BigDecimal(\"" + object + "\")"; + } catch(NumberFormatException e) { + return "" + object + ""; + } + case JAVA_LANG_STRING: + return "\"" + toJavaString(object.toString()) + "\""; default: return null; } } @@ -765,11 +763,8 @@ private String castReceiveValue(Object object, JavaType valueType, AlertCollecto private String castReceiveEnum(Object object, JavaType valueType, boolean isSimpleExpression, long line, long uid, String column) { if (isSimpleExpression) { - if (valueType==JavaType.JAVA_LANG_BOOLEAN) { - return object.toString().toLowerCase(); - } - return "" + object; - } + return valueType == JavaType.JAVA_LANG_BOOLEAN ? object.toString().toLowerCase() : String.valueOf(object); + } return castReceiveValue(object, valueType, alertCollector, line, uid, column); } @@ -779,7 +774,7 @@ private Variable getVariable(Class type, String varNameOrig) Variable var = new Variable(varName, type); // check if variable with same name and type already exists - if (this.variables.contains(var)) + if(variables.contains(var)) { return var; } @@ -791,12 +786,12 @@ private Variable getVariable(Class type, String varNameOrig) while (found) { found = false; - for (Variable v : this.variables) + for(Variable v : variables) { if (v.getName().equals(varName)) { found = true; - varName = varNameOrig+(i++); + varName = varNameOrig + i++; break; } } @@ -806,7 +801,7 @@ private Variable getVariable(Class type, String varNameOrig) throw new NullPointerException("Variable type is null"); } var = new Variable(varName, type); - this.variables.add(var); + variables.add(var); return var; } } @@ -866,7 +861,7 @@ public String writeReceiveMessage(AMLTestCase tc, AMLAction action, } if (action.getGenerateStatus() == AMLGenerateStatus.GENERATING) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); return null; } @@ -889,7 +884,7 @@ public String writeReceiveMessage(AMLTestCase tc, AMLAction action, if (type != null) { if (!action.hasDictionaryURI()) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), Column.Dictionary.getName(), "Dictionary is not specified")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), Column.Dictionary.getName(), "Dictionary is not specified")); return null; } @@ -943,11 +938,7 @@ private Object createReceiveCall(AMLTestCase tc, AMLAction action, sb.append(settings.getName()); sb.append(".getCheckPoint(), "); - if(action.hasTag()) { - sb.append(StringUtil.enclose(StringUtil.toJavaString(action.getTag()), '"')); - } else { - sb.append("null"); - } + sb.append(action.hasTag() ? enclose(toJavaString(action.getTag()), '"') : "null"); sb.append(","); sb.append(action.getHash()); @@ -963,7 +954,7 @@ private Object createReceiveCall(AMLTestCase tc, AMLAction action, } ActionInfo actionInfo = action.getActionInfo(); - String callArgs = String.format("%s.parse(\"%s\"), %s, %s", SailfishURI.class.getSimpleName(), actionInfo.getURI(), settings.getName(), inputVariable.getName()); + String callArgs = format("%s.parse(\"%s\"), %s, %s", SailfishURI.class.getSimpleName(), actionInfo.getURI(), settings.getName(), inputVariable.getName()); Variable outputVariable = null; if (returnType != void.class) { @@ -1074,18 +1065,14 @@ protected static void writeCreateTestCase(AMLTestCase tc, StringBuilder sb) { sb.append(REPORT_NAME); sb.append(".createTestCase("); - if(tc.hasReference()) { - sb.append(StringUtil.enclose(tc.getReference())); - } else { - sb.append("null"); - } + sb.append(tc.hasReference() ? enclose(tc.getReference()) : "null"); sb.append(", "); String description = tc.getDescription(); if(StringUtils.isNotBlank(description)) { - sb.append(StringUtil.enclose(StringUtil.toJavaString(description))); + sb.append(enclose(toJavaString(description))); sb.append(", "); } else { sb.append("null, "); @@ -1100,7 +1087,7 @@ protected static void writeCreateTestCase(AMLTestCase tc, StringBuilder sb) { String id = tc.getId(); if(StringUtils.isNotBlank(id)) { - sb.append(StringUtil.enclose(StringUtil.toJavaString(id))); + sb.append(enclose(toJavaString(id))); sb.append(", "); } else { sb.append("null, "); @@ -1135,7 +1122,7 @@ private void writeCreateAction(AMLAction action, StringBuilder sb, String id, St + "\"" + messageType.trim() + "\", " + description + " , null, null, " - + (action.hasTag() ? StringUtil.enclose(StringUtil.toJavaString(action.getTag()), '"') : "null") + ", " + + (action.hasTag() ? enclose(toJavaString(action.getTag()), '"') : "null") + ", " + action.getHash() + ", " + "Arrays.asList( " + verificationsOrder + ")" +");" + EOL); @@ -1190,7 +1177,7 @@ private String createReceiveMessageDefinition(AMLTestCase tc, AMLAction action, IDictionaryStructure dictionary = getDictionary(action.getDictionaryURI()); if (dictionary == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Can't find dictionary [" + action.getDictionaryURI() + "]")); return ""; } @@ -1199,7 +1186,7 @@ private String createReceiveMessageDefinition(AMLTestCase tc, AMLAction action, IFieldStructure dm = dictionary.getMessages().get(action.getMessageTypeColumn()); if (dm == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Dictionary "+action.getDictionaryURI()+ + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Dictionary " + action.getDictionaryURI() + " does not contain message "+action.getMessageTypeColumn())); return ""; } @@ -1234,7 +1221,7 @@ private String createReceiveMessageDefinition(AMLTestCase tc, AMLAction action, IFieldStructure fStruct = dm.getFields().get(fieldName); if (fStruct == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Message '"+dm.getName()+"' in namespace '"+dm.getNamespace()+"' does not contain '"+fieldName+"' field")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Message '" + dm.getName() + "' in namespace '" + dm.getNamespace() + "' does not contain '" + fieldName + "' field")); } else { if(fStruct.isSimple() && fStruct.isServiceName()) { writeServiceFieldDefinition(value, action, fieldName, fStruct, sb, inputVariable); @@ -1249,7 +1236,7 @@ private String createReceiveMessageDefinition(AMLTestCase tc, AMLAction action, try { refs = AMLLangUtil.getReferences(value.getValue()); } catch (AMLException e) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': " + e.getMessage())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': " + e.getMessage())); continue; } @@ -1269,7 +1256,7 @@ private String createReceiveMessageDefinition(AMLTestCase tc, AMLAction action, } } - value.setValue("[" + newValue.toString() + "]"); + value.setValue("[" + newValue + "]"); } for(String ref : refs) { @@ -1304,7 +1291,7 @@ private String createReceiveMessageDefinition(AMLTestCase tc, AMLAction action, } if(!AMLLangUtil.isCollection(strValue)) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': Invalid collection format '" + value.getValue() + "'")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': Invalid collection format '" + value.getValue() + "'")); continue; } @@ -1344,7 +1331,7 @@ else if (fStruct.isSimple()) } if(!AMLLangUtil.isCollection(value.getValue())) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': Invalid collection format '" + value.getValue() + "'")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': Invalid collection format '" + value.getValue() + "'")); continue; } @@ -1376,13 +1363,13 @@ else if (fStruct.isComplex()) } if(!AMLLangUtil.isSubmessage(value.getValue())) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '"+fieldName+"': Invalid collection format")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Column '" + fieldName + "': Invalid collection format")); continue; } if (!fStruct.isCollection()) { if (value.getValue().split(",").length > 1) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Cannot set multiple values to field " + fStruct.getName())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, "Cannot set multiple values to field " + fStruct.getName())); continue; } @@ -1417,7 +1404,7 @@ private void generateSubAction(AMLTestCase tc, AMLAction action, IFieldStructure AMLAction subAction = tc.findActionByRef(refName); if(subAction == null || action.equals(subAction)) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, String.format( + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, format( "Column '%s': Reference '%s' is not defined in matrix", fieldName, refName))); return; @@ -1429,7 +1416,7 @@ private void generateSubAction(AMLTestCase tc, AMLAction action, IFieldStructure SailfishURI actionDictionary = action.getDictionaryURI(); if(dictionary != null && !dictionary.matches(actionDictionary)) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, String.format( + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, format( "Subaction dictionary '%s' differs from action dictionary '%s'", dictionary, actionDictionary))); return; @@ -1443,13 +1430,13 @@ private void generateSubAction(AMLTestCase tc, AMLAction action, IFieldStructure if(StringUtils.isEmpty(subMsgType)) { subAction.setMessageTypeColumn(msgType); } else if(!subMsgType.equals(msgType)) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, String.format( + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, format( "Subaction message type '%s' differs from action message type '%s'", subMsgType, msgType))); return; } } else { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, String.format( + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, format( "Subaction must predefined to use references to it's fields."))); return; } @@ -1473,13 +1460,13 @@ private void generateSubAction(AMLTestCase tc, AMLAction action, IFieldStructure IMessageStructure msgStruct = getMessageStructure(dictURI, msgType); if(msgStruct == null) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, String.format( + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, format( "Column '%s': Reference to unknown message('%s')/dictionary('%s') in reference '%s'", fieldName, msgType, dictURI, reference))); return; } if(msgStruct.getFields().get(subField) == null) { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, String.format( + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), fieldName, format( "Column '%s': Reference to unknown column '%s' in reference '%s'", fieldName, subField, reference))); return; } @@ -1497,7 +1484,7 @@ private void generateSubAction(AMLTestCase tc, AMLAction action, IFieldStructure if (subAction.getGenerateStatus() != AMLGenerateStatus.GENERATED) { if (subAction.getGenerateStatus() == AMLGenerateStatus.GENERATING) { - this.alertCollector.add(new Alert(subAction.getLine(), action.getUID(), subAction.getReference(), "Recursion detected")); + alertCollector.add(new Alert(subAction.getLine(), action.getUID(), subAction.getReference(), "Recursion detected")); return; } @@ -1549,7 +1536,7 @@ public static String getMvelString(AMLTestCase tc, AMLAction action, String inpu return sb.toString(); } else { - return "\"" + StringUtil.toJavaString(input) + "\""; + return "\"" + toJavaString(input) + "\""; } } @@ -1559,15 +1546,15 @@ public static String generateEval(long line, String column, Value value, String sb.append("eval("); sb.append(line); sb.append(", "); - sb.append(StringUtil.enclose(column)); + sb.append(enclose(column)); sb.append(", "); - sb.append(StringUtil.enclose(StringUtil.toJavaString(value.getValue()))); + sb.append(enclose(toJavaString(value.getValue()))); for(RefParameter p : value.getParameters()) { sb.append(EOL); sb.append(indent); sb.append(", "); - sb.append(StringUtil.enclose(p.getName())); + sb.append(enclose(p.getName())); sb.append(", "); sb.append(p.getValue()); } @@ -1583,7 +1570,7 @@ public static String generateFilter(long line, String column, Value value, Strin } public static String generateFilter(long line, String column, Value value, String indent, String type) { - String v = StringUtil.toJavaString(value.getValue()); + String v = toJavaString(value.getValue()); if("regexFilter".equals(type)) { v = getRegex(value.getValue()); @@ -1594,15 +1581,15 @@ public static String generateFilter(long line, String column, Value value, Strin sb.append("("); sb.append(line); sb.append(", "); - sb.append(StringUtil.enclose(column)); + sb.append(enclose(column)); sb.append(", "); - sb.append(StringUtil.enclose(v)); + sb.append(enclose(v)); for(RefParameter p : value.getParameters()) { sb.append(EOL); sb.append(indent); sb.append(", "); - sb.append(StringUtil.enclose(p.getName())); + sb.append(enclose(p.getName())); sb.append(", "); sb.append(p.getValue()); } @@ -1626,20 +1613,20 @@ private String createFilterExpression(IFieldStructure fType, String origValue, l String v = origValue; if (origValue.equals(CONV_VALUE_PRESENT)) { - return "notNullFilter(" + line + ", " + StringUtil.enclose(column) + ")"; + return "notNullFilter(" + line + ", " + enclose(column) + ")"; } else if (origValue.equals(CONV_VALUE_MISSING)) { - return "nullFilter(" + line + ", " + StringUtil.enclose(column) + ")"; + return "nullFilter(" + line + ", " + enclose(column) + ")"; } else if (checkValue(origValue)) { - if (JavaType.JAVA_LANG_BOOLEAN.equals(fType.getJavaType())){ + if(fType.getJavaType() == JavaType.JAVA_LANG_BOOLEAN) { v = v.replace("TRUE", "true"); // TODO: add parameter TRUE and FALSE v = v.replace("FALSE", "false"); // TODO: add parameter TRUE and FALSE - } else if (JavaType.JAVA_LANG_STRING.equals(fType.getJavaType())){ - v = StringUtil.toJavaString(v); + } else if(fType.getJavaType() == JavaType.JAVA_LANG_STRING) { + v = toJavaString(v); } - return "filter(" + line + ", " + StringUtil.enclose(column) + ", " + StringUtil.enclose(v) +")"; + return "filter(" + line + ", " + enclose(column) + ", " + enclose(v) + ")"; } else if (isRegex(origValue)) { String regexp = getRegex(origValue); - return "regexFilter(" + line + ", " + StringUtil.enclose(column) + ", " + StringUtil.enclose(regexp) + ")"; + return "regexFilter(" + line + ", " + enclose(column) + ", " + enclose(regexp) + ")"; } // v = "x == "+v; @@ -1652,9 +1639,9 @@ private String createFilterExpression(IFieldStructure fType, String origValue, l // return "filter(\""+v+"\")"; v = castReceiveValue(v, fType.getJavaType(), alertCollector, line, uid, column); - v = StringUtil.toJavaString(v); + v = toJavaString(v); - return "simpleFilter(" + line + ", " + StringUtil.enclose(column) + ", " + StringUtil.enclose(v) + ")"; + return "simpleFilter(" + line + ", " + enclose(column) + ", " + enclose(v) + ")"; } /* @@ -1675,14 +1662,14 @@ private String prepareEnum(String v, IFieldStructure s, long line, long uid, Str while (index != -1) { - char c = (char)(v.getBytes()[index-1]); + char c = (char)v.getBytes()[index - 1]; if (isAlpha(c)) { index = v.indexOf(e, index+1); continue; } // check next byte after end of alias - c = (char)(v.getBytes()[index+e.length()]); + c = (char)v.getBytes()[index + e.length()]; if (isAlphaNum(c)) { index = v.indexOf(e, index+1); continue; @@ -1719,8 +1706,9 @@ private static boolean checkValue(String v) { if (!"x".equals(v)) { String[] tokens = v.split(AMLLangConst.REGEX_MVEL_NOT_VARIABLE); for (String token : tokens) { - if ("x".equals(token)) - return true; + if("x".equals(token)) { + return true; + } } } return false; @@ -1731,7 +1719,7 @@ private static boolean isRegex(String v) { } private static String getRegex(String regex) { - return StringUtil.toJavaString(regex.substring(regex.indexOf("[")+1, regex.lastIndexOf(REGEX_VALUE_SUFFIX))); + return toJavaString(regex.substring(regex.indexOf("[") + 1, regex.lastIndexOf(REGEX_VALUE_SUFFIX))); } /** diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImplHelper.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImplHelper.java index 6e7b3c4c..47acdaef 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImplHelper.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/NewImplHelper.java @@ -139,7 +139,7 @@ private static int expandReferenceValue(AMLTestCase tc, AMLAction action, String var = value.getValue().substring(index+BEGIN_REFERENCE.length(), index2); - if (var.length() == 0) + if (var.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference is empty in column '"+column+"'.")); return -1; @@ -160,7 +160,7 @@ private static int expandReferenceValue(AMLTestCase tc, AMLAction action, String lineRef = arr[0].trim(); // reference to message - if (lineRef.length() == 0) + if (lineRef.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to row is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); return -1; @@ -217,16 +217,15 @@ private static int expandReferenceValue(AMLTestCase tc, AMLAction action, targ.append(".").append(columnRef); } value.addParameter(new RefParameter(paramName, CodeGenerator_new.MAP_NAME + ".get(\"" + lineRef + "\")")); - String v = value.getValue().replaceFirst(Pattern.quote(src), " " + targ.toString() + " "); + String v = value.getValue().replaceFirst(Pattern.quote(src), " " + targ + " "); value.setValue(v); value.setReference(true); // search for the next reference - index = value.getValue().indexOf(BEGIN_REFERENCE); + return value.getValue().indexOf(BEGIN_REFERENCE); - return index; - } + } private static boolean verifyMessageColumns( @@ -256,27 +255,25 @@ private static boolean verifyMessageColumns( for (int i = 0; i < columns.length; i++) { String columnRef = columns[i]; - boolean itLastField = (i + 1 == columns.length); + boolean itLastField = i + 1 == columns.length; boolean collectionRequired = false; - { - int idx = columnRef.indexOf('['); - if (idx != -1) { - //FIXME: need gramma parser - String dimensions = columnRef.substring(idx+1); - if (dimensions.charAt(dimensions.length()-1) != ']') { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "No trailing ']' in the column " + - "reference " + columnRef + - "column '"+column+"': '"+value.getOrigValue()+"'." - )); - } - dimensions = dimensions.substring(0, dimensions.length()-1); - columnRef = columnRef.substring(0, idx); - collectionRequired = true; - - } - } - - IFieldStructure fld = null; + int idx = columnRef.indexOf('['); + if (idx != -1) { + //FIXME: need gramma parser + String dimensions = columnRef.substring(idx+1); + if (dimensions.charAt(dimensions.length()-1) != ']') { + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "No trailing ']' in the column " + + "reference " + columnRef + + "column '"+column+"': '"+value.getOrigValue()+"'." + )); + } + dimensions = dimensions.substring(0, dimensions.length()-1); + columnRef = columnRef.substring(0, idx); + collectionRequired = true; + + } + + IFieldStructure fld = null; if (!fldType.isComplex()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Type " + fldType.getName() + " is not complex in the column " + "reference " + columnRef + @@ -324,7 +321,7 @@ private static boolean verifyMessageColumns( for (String columnRef : columns) { - if (columnRef.length() == 0) + if (columnRef.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to column is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); return false; @@ -370,7 +367,7 @@ private static int expandStaticValue(AMLTestCase tc, AMLAction action, // get reference to previous message and field name String val = value.getValue().substring(index+2, index2); - if (val.length() == 0) + if (val.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference is empty in column '"+column+"'.")); return -1; @@ -386,7 +383,7 @@ private static int expandStaticValue(AMLTestCase tc, AMLAction action, String lineRef = arr[0].trim(); // reference to message - if (lineRef.length() == 0) + if (lineRef.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to row is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); return -1; @@ -450,10 +447,9 @@ private static int expandStaticValue(AMLTestCase tc, AMLAction action, // search for the next reference - index = value.getValue().indexOf(BEGIN_STATIC); + return value.getValue().indexOf(BEGIN_STATIC); - return index; - } + } private static int expandUtilityFunction(AMLAction action, String column, Value value, int index, AlertCollector alertCollector, IDictionaryManager dictionaryManager, IActionManager actionManager, IUtilityManager utilityManager) @@ -472,7 +468,7 @@ private static int expandUtilityFunction(AMLAction action, String var = stringValue.substring(index+2, index2); - if (var.length() == 0) + if (var.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Utility function name is empty in column '"+column+"'.")); return -1; @@ -539,8 +535,7 @@ private static int expandUtilityFunction(AMLAction action, // search next function - index = value.getValue().indexOf(BEGIN_FUNCTION); + return value.getValue().indexOf(BEGIN_FUNCTION); - return index; - } + } } diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImpl.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImpl.java index 4fadc704..d4d9b7ab 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImpl.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImpl.java @@ -15,6 +15,10 @@ ******************************************************************************/ package com.exactpro.sf.aml.generator; +import static com.exactpro.sf.common.util.StringUtil.enclose; +import static com.exactpro.sf.common.util.StringUtil.toJavaString; +import static org.apache.commons.lang3.ClassUtils.getSimpleName; + import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; @@ -53,7 +57,7 @@ public class OldImpl { private static final Logger logger = LoggerFactory.getLogger(OldImpl.class); - protected final static String EOL = System.getProperty("line.separator"); + protected static final String EOL = System.getProperty("line.separator"); public static final String TAB1 = "\t"; public static final String TAB2 = "\t\t"; @@ -78,8 +82,8 @@ public class OldImpl { private final IUtilityManager utilityManager; private final CodeGenerator_new codeGenerator; - private final static int CAPACITY_4K = 4096; - private final static int CAPACITY_128K = 131072; + private static final int CAPACITY_4K = 4096; + private static final int CAPACITY_128K = 131072; public OldImpl(AlertCollector alertCollector, IAdapterManager adapterManager, IDictionaryManager dictionaryManager, IActionManager actionManager, IUtilityManager utilityManager, CodeGenerator_new codeGenerator) { this.alertCollector = alertCollector; @@ -102,7 +106,7 @@ String writeFillMessage(AMLTestCase tc, AMLAction action, List variabl } if (action.getGenerateStatus() == AMLGenerateStatus.GENERATING) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Recursion detected")); return null; } @@ -140,10 +144,9 @@ String writeFillMessage(AMLTestCase tc, AMLAction action, List variabl Class returnType = action.getActionInfo().getReturnType(); if (action.hasReference() && void.class.equals(returnType)) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Cannot refer to void method: "+action.getActionURI()+". " + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Cannot refer to void method: " + action.getActionURI() + ". " + "Please remove reference label and all reference occurrences to this row.", AlertType.WARNING)); - } - else if (false == void.class.equals(returnType)) + } else if(!void.class.equals(returnType)) { outputVariable = getVariable(returnType, MESSAGE_PREFIX + returnType.getSimpleName()); } @@ -161,7 +164,7 @@ else if (false == void.class.equals(returnType)) } Variable settings = getVariable(DefaultSettings.class, "settings"); - String s = codeGenerator.createFillSettings(tc, action, null, settings, this.alertCollector); + String s = codeGenerator.createFillSettings(tc, action, null, settings, alertCollector); sb.append(s); sb.append(TAB2+LOGGER_NAME+".debug(\"start action: "+action.getActionURI()+", line:"+action.getLine()+"\");"+EOL); @@ -193,7 +196,7 @@ else if (false == void.class.equals(returnType)) writeCreateAction(action, sb); NewImpl.addActionToReport(action, sb, true, variable, TAB3); - closeTryClause(tc, action, sb, action.getContinueOnFailed() || this.continueOnFailed); + closeTryClause(tc, action, sb, action.getContinueOnFailed() || continueOnFailed); } else { @@ -218,11 +221,11 @@ private String writeFillMetaContainer(AMLTestCase tc, AMLAction action, ActionIn String failUnexpected = null; if(action.getFailUnexpected() != null && !"".equals(action.getFailUnexpected())) { - failUnexpected = TypeConverter.convert(java.lang.String.class, action.getFailUnexpected()); + failUnexpected = TypeConverter.convert(String.class, action.getFailUnexpected()); } if(parentVar != null) { - sb.append(TAB2 + metaContainer.getName() + " = createMetaContainer(" + parentVar + ", " + TypeConverter.convert(java.lang.String.class, field) + ", " + failUnexpected + ");" + EOL); + sb.append(TAB2 + metaContainer.getName() + " = createMetaContainer(" + parentVar + ", " + TypeConverter.convert(String.class, field) + ", " + failUnexpected + ");" + EOL); } else { sb.append(TAB2 + metaContainer.getName() + " = createMetaContainer(" + failUnexpected + ");" + EOL); } @@ -238,16 +241,9 @@ private String writeFillMetaContainer(AMLTestCase tc, AMLAction action, ActionIn } private String getReturnTypeName(AMLAction action) { - - String msgType = null; - - if(action.getActionInfo() != null && action.getActionInfo().getReturnType() != null) { - msgType = action.getActionInfo().getReturnType().getSimpleName(); - } - - return msgType; - - } + ActionInfo actionInfo = action.getActionInfo(); + return actionInfo != null ? getSimpleName(actionInfo.getReturnType(), null) : null; + } private Variable getVariable(Class type, String varNameOrig) { @@ -255,7 +251,7 @@ private Variable getVariable(Class type, String varNameOrig) Variable var = new Variable(varName, type); // check if variable with same name and type already exists - if (this.variables.contains(var)) + if(variables.contains(var)) { return var; } @@ -267,19 +263,19 @@ private Variable getVariable(Class type, String varNameOrig) while (found) { found = false; - for (Variable v : this.variables) + for(Variable v : variables) { if (v.getName().equals(varName)) { found = true; - varName = varNameOrig+(i++); + varName = varNameOrig + i++; break; } } if (found == false) { var = new Variable(varName, type); - this.variables.add(var); + variables.add(var); return var; } } @@ -301,11 +297,11 @@ private String createMessageDefinition(AMLTestCase tc, AMLAction action, Variabl try { IGetterSetterGenerator gsFactory = (IGetterSetterGenerator) - this.adapterManager.getAdapter(action.getActionInfo().getMessageType(), IGetterSetterGenerator.class); + adapterManager.getAdapter(action.getActionInfo().getMessageType(), IGetterSetterGenerator.class); if (gsFactory == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Cannot find getter&setter generator instance for type '" + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Cannot find getter&setter generator instance for type '" +action.getActionInfo().getMessageType().getCanonicalName()+"'")); continue; } @@ -330,7 +326,7 @@ else if (AMLLangUtil.isArray(v.getValue())) expandSetter(action, gsFactory, sb, column, v, v.getValue(), variable.getName()); } } catch (AMLException | SailfishURIException ex) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '"+column+"': "+ex.getMessage())); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '" + column + "': " + ex.getMessage())); continue; } } @@ -361,7 +357,7 @@ private void expandSetter(AMLAction action, IGetterSetterGenerator gsFactory, St String setter = gsFactory.getSetter(action.getActionInfo().getMessageType(), column, val, v.isReference() || v.isJava()); if (setter == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot set value '"+val+"' of type '" + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot set value '" + val + "' of type '" +column+"' for message '"+action.getActionInfo().getMessageType().getCanonicalName()+"'")); return; } @@ -403,7 +399,7 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl if (subAction == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '"+column+"'" + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '" + column + "'" +": Reference '"+ref+"' not defined in matrix.")); continue; } @@ -430,18 +426,18 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl eval.append("eval("); eval.append(action.getLine()); eval.append(", "); - eval.append(StringUtil.enclose(column)); + eval.append(enclose(column)); eval.append(", "); - eval.append(StringUtil.enclose(StringUtils.join(refSplit, '.'))); + eval.append(enclose(StringUtils.join(refSplit, '.'))); eval.append(", "); - eval.append(StringUtil.enclose("v0")); + eval.append(enclose("v0")); eval.append(", "); eval.append(STATIC_MAP_NAME); eval.append(".get("); - eval.append(StringUtil.enclose(ref)); + eval.append(enclose(ref)); eval.append("))"); - setter.append(TAB2 + subListVariable.getName() + ".add(" + eval.toString() + ");" + EOL); + setter.append(TAB2 + subListVariable.getName() + ".add(" + eval + ");" + EOL); action.addChildAction(column, subAction); @@ -460,7 +456,7 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl if (subAction == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '"+column+"'" + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Column '" + column + "'" +": Reference '"+reference+"' not defined in matrix.")); continue; } @@ -488,7 +484,7 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl if (type == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot find submessage "+column+" in message '"+action.getActionInfo().getMessageType().getCanonicalName()+"'.")); + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Cannot find submessage " + column + " in message '" + action.getActionInfo().getMessageType().getCanonicalName() + "'.")); continue; } @@ -496,14 +492,14 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl subAction.getActionInfo().setReturnType(type); if (subAction.getMessageTypeColumn() != null - && false == subAction.getMessageTypeColumn().equals("")) + && !"".equals(subAction.getMessageTypeColumn())) { - if (false == type.equals(List.class) - && false == type.equals(IMessage.class) - && false == type.getCanonicalName().equals(subAction.getMessageTypeColumn()) - && false == type.getSimpleName().equals(subAction.getMessageTypeColumn())) + if(!type.equals(List.class) + && !type.equals(IMessage.class) + && !type.getCanonicalName().equals(subAction.getMessageTypeColumn()) + && !type.getSimpleName().equals(subAction.getMessageTypeColumn())) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Message type ["+subAction.getMessageTypeColumn()+"] for submessage ["+subAction.getReference() + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Message type [" + subAction.getMessageTypeColumn() + "] for submessage [" + subAction.getReference() +"] does not match calculated submessage type '"+type.getCanonicalName()+"'." +" Possible that reference placed in wrong column or specified submessage type is incorrect." +" Make sure that value in "+Column.MessageType.getName()+" column for message in line " @@ -513,7 +509,7 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl } } codeGenerator.addDefinedReferences(reference); - String subMessage = writeFillMessage(tc, subAction, this.variables); + String subMessage = writeFillMessage(tc, subAction, variables); if (subMessage != null) { subMessages.add(subMessage); subAction.addGenerationSteps(action.getGenerationPath(), action.getReference()); @@ -525,39 +521,39 @@ private void expandSubmessage(AMLTestCase tc, AMLAction action, Variable variabl eval.append("eval("); eval.append(action.getLine()); eval.append(", "); - eval.append(StringUtil.enclose(column)); + eval.append(enclose(column)); eval.append(", "); - eval.append(StringUtil.enclose(StringUtils.join(refSplit, '.'))); + eval.append(enclose(StringUtils.join(refSplit, '.'))); eval.append(", "); - eval.append(StringUtil.enclose("v0")); + eval.append(enclose("v0")); eval.append(", "); eval.append(MAP_NAME); eval.append(".get("); - eval.append(StringUtil.enclose(reference)); + eval.append(enclose(reference)); eval.append("))"); - setter.append(TAB2 + subListVariable.getName() + ".add(" + eval.toString() + ");" + EOL); + setter.append(TAB2 + subListVariable.getName() + ".add(" + eval + ");" + EOL); action.addChildAction(column, subAction); } if(setter.length() > 0) { - sb.append(EOL + setter.toString() + EOL); + sb.append(EOL + setter + EOL); sb.append(TAB2 + variable.getName() + ".put(\"" + column + "\", " + subListVariable.getName() + ");" + EOL); if (v.isCheck()) { - action.getSetters().add(new Pair<>(column, subListVariable.getType().getCanonicalName() + " " + setter.toString())); + action.getSetters().add(new Pair<>(column, subListVariable.getType().getCanonicalName() + " " + setter)); } } } void addReferenceToFilter(StringBuilder sb, AMLAction action, Variable inputVariable) { - if (false == "".equals(action.getReferenceToFilter())) + if(!"".equals(action.getReferenceToFilter())) { if ((action.getActionInfo() == null) || (action.getActionInfo() != null - && false == void.class.equals(action.getActionInfo().getReturnType()))) + && !void.class.equals(action.getActionInfo().getReturnType()))) { if (inputVariable != null) { @@ -575,13 +571,13 @@ private void writeActionCall(AMLTestCase tc, AMLAction action, Variable inputVar IGetterSetterGenerator factory = null; if(inputVariable != null) { - factory = (IGetterSetterGenerator)this.adapterManager.getAdapter(action.getActionInfo().getMessageType(), IGetterSetterGenerator.class); + factory = (IGetterSetterGenerator)adapterManager.getAdapter(action.getActionInfo().getMessageType(), IGetterSetterGenerator.class); if (factory == null) { - this.alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Cannot find getter&setter generator instance for type '" + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), "Cannot find getter&setter generator instance for type '" +action.getActionInfo().getMessageType().getCanonicalName())); - throw new AMLException("Cannot find getter&setter generator", this.alertCollector); + throw new AMLException("Cannot find getter&setter generator", alertCollector); } } @@ -599,7 +595,7 @@ private void writeActionCall(AMLTestCase tc, AMLAction action, Variable inputVar } } - String description = StringUtil.toJavaString(action.getDescrption()); + String description = toJavaString(action.getDescrption()); if (action.getOutcome() != null) { description = action.getOutcome()+" "+description; } @@ -623,11 +619,7 @@ private void writeActionCall(AMLTestCase tc, AMLAction action, Variable inputVar sb.append(settings.getName()); sb.append(".getCheckPoint(), "); - if(action.hasTag()) { - sb.append(StringUtil.enclose(StringUtil.toJavaString(action.getTag()), '"')); - } else { - sb.append("null"); - } + sb.append(action.hasTag() ? enclose(toJavaString(action.getTag()), '"') : "null"); sb.append(","); sb.append(action.getHash()); @@ -703,7 +695,7 @@ private void closeTryClause(AMLTestCase tc, AMLAction action, StringBuilder sb, String id = (action.getId() == null) ? "" : action.getId() + " "; String serviceName = action.hasServiceName() ? action.getServiceName() + " " : ""; - String description = StringUtil.toJavaString(action.getDescrption()); + String description = toJavaString(action.getDescrption()); if(action.getOutcome() != null) { description = action.getOutcome() + " " + description; @@ -735,7 +727,7 @@ private void closeTryClause(AMLTestCase tc, AMLAction action, StringBuilder sb, private void writeCreateAction(AMLAction action, StringBuilder sb) { String id = (action.getId() == null) ? "" : action.getId() + " "; String serviceName = action.hasServiceName() ? action.getServiceName() + " " : ""; - String description = StringUtil.toJavaString(action.getDescrption()); + String description = toJavaString(action.getDescrption()); writeCreateAction(action, sb, id, serviceName, description); } @@ -751,7 +743,7 @@ private void writeCreateAction(AMLAction action, StringBuilder sb, String id, St + "\"" + getReturnTypeName(action) + "\", " + "\"" + description + "\" , null, null, " - + (action.hasTag() ? StringUtil.enclose( StringUtil.toJavaString(action.getTag()), '"') : "null") + ", " + + (action.hasTag() ? enclose(toJavaString(action.getTag()), '"') : "null") + ", " + action.getHash() + ", " + "Arrays.asList( " + verificationsOrder + ")" + ");" + EOL); diff --git a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImplHelper.java b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImplHelper.java index 206a4afd..7d706211 100644 --- a/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImplHelper.java +++ b/BackEnd/Extension/extension-aml-3/src/main/java/com/exactpro/sf/aml/generator/OldImplHelper.java @@ -139,7 +139,7 @@ private static int expandReferenceValue(AMLTestCase tc, AMLAction action, String var = value.getValue().substring(index+BEGIN_REFERENCE.length(), index2); - if (var.length() == 0) + if (var.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference is empty in column '"+column+"'.")); return -1; @@ -160,7 +160,7 @@ private static int expandReferenceValue(AMLTestCase tc, AMLAction action, String lineRef = arr[0].trim(); // reference to message - if (lineRef.length() == 0) + if (lineRef.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to row is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); return -1; @@ -217,16 +217,15 @@ private static int expandReferenceValue(AMLTestCase tc, AMLAction action, targ.append(".").append(columnRef); } value.addParameter(new RefParameter(paramName, CodeGenerator_new.MAP_NAME + ".get(\"" + lineRef + "\")")); - String v = value.getValue().replaceFirst(Pattern.quote(src), " " + targ.toString() + " "); + String v = value.getValue().replaceFirst(Pattern.quote(src), " " + targ + " "); value.setValue(v); value.setReference(true); // search for the next reference - index = value.getValue().indexOf(BEGIN_REFERENCE); + return value.getValue().indexOf(BEGIN_REFERENCE); - return index; - } + } private static boolean verifyMessageColumns( @@ -256,27 +255,25 @@ private static boolean verifyMessageColumns( for (int i = 0; i < columns.length; i++) { String columnRef = columns[i]; - boolean itLastField = (i + 1 == columns.length); + boolean itLastField = i + 1 == columns.length; boolean collectionRequired = false; - { - int idx = columnRef.indexOf('['); - if (idx != -1) { - //FIXME: need gramma parser - String dimensions = columnRef.substring(idx+1); - if (dimensions.charAt(dimensions.length()-1) != ']') { - alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "No trailing ']' in the column " + - "reference " + columnRef + - "column '"+column+"': '"+value.getOrigValue()+"'." - )); - } - dimensions = dimensions.substring(0, dimensions.length()-1); - columnRef = columnRef.substring(0, idx); - collectionRequired = true; - - } - } + int idx = columnRef.indexOf('['); + if (idx != -1) { + //FIXME: need gramma parser + String dimensions = columnRef.substring(idx+1); + if (dimensions.charAt(dimensions.length()-1) != ']') { + alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "No trailing ']' in the column " + + "reference " + columnRef + + "column '"+column+"': '"+value.getOrigValue()+"'." + )); + } + dimensions = dimensions.substring(0, dimensions.length()-1); + columnRef = columnRef.substring(0, idx); + collectionRequired = true; - IFieldStructure fld = null; + } + + IFieldStructure fld = null; if (!fldType.isComplex()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Type " + fldType.getName() + " is not complex in the column " + "reference " + columnRef + @@ -325,7 +322,7 @@ private static boolean verifyMessageColumns( for (String columnRef : columns) { - if (columnRef.length() == 0) + if (columnRef.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to column is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); return false; @@ -373,7 +370,7 @@ private static int expandStaticValue(AMLTestCase tc, AMLAction action, // get reference to previous message and field name String val = value.getValue().substring(index+2, index2); - if (val.length() == 0) + if (val.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference is empty in column '"+column+"'.")); return -1; @@ -389,7 +386,7 @@ private static int expandStaticValue(AMLTestCase tc, AMLAction action, String lineRef = arr[0].trim(); // reference to message - if (lineRef.length() == 0) + if (lineRef.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Reference to row is missed in column '"+column+"': '"+value.getOrigValue()+"'.")); return -1; @@ -453,10 +450,9 @@ private static int expandStaticValue(AMLTestCase tc, AMLAction action, // search for the next reference - index = value.getValue().indexOf(BEGIN_STATIC); + return value.getValue().indexOf(BEGIN_STATIC); - return index; - } + } private static int expandUtilityFunction(AMLAction action, String column, Value value, int index, AlertCollector alertCollector, IDictionaryManager dictionaryManager, IActionManager actionManager, IUtilityManager utilityManager) @@ -474,7 +470,7 @@ private static int expandUtilityFunction(AMLAction action, String var = stringValue.substring(index+2, index2); - if (var.length() == 0) + if (var.isEmpty()) { alertCollector.add(new Alert(action.getLine(), action.getUID(), action.getReference(), column, "Utility function name is empty in column '"+column+"'.")); return -1; @@ -541,8 +537,7 @@ private static int expandUtilityFunction(AMLAction action, // search next function - index = value.getValue().indexOf(BEGIN_FUNCTION); + return value.getValue().indexOf(BEGIN_FUNCTION); - return index; - } + } } diff --git a/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3Base.java b/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3Base.java index 562da19c..080f7857 100644 --- a/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3Base.java +++ b/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3Base.java @@ -38,7 +38,7 @@ */ public abstract class TestAML3Base extends AML3PluginTest { - private final static Logger logger = LoggerFactory.getLogger(TestAML3Base.class); + private static final Logger logger = LoggerFactory.getLogger(TestAML3Base.class); protected abstract AMLSettings createSettings(); diff --git a/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3_0.java b/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3_0.java index 7252907e..d5f8f140 100644 --- a/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3_0.java +++ b/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/aml/TestAML3_0.java @@ -35,8 +35,8 @@ public class TestAML3_0 extends TestAML3Base { - private static String VALID_TEST_PATH = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "aml3_0" + File.separator + "validTest" + File.separator; - private static String INVALID_TEST_PATH = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "aml3_0" + File.separator + "invalidTest" + File.separator; + private static final String VALID_TEST_PATH = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "aml3_0" + File.separator + "validTest" + File.separator; + private static final String INVALID_TEST_PATH = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "aml3_0" + File.separator + "invalidTest" + File.separator; @Before public void initTestAML3_0() throws InterruptedException, ExecutionException { @@ -92,8 +92,7 @@ public void test_valid_all() throws Exception Collection source = aml.getAlertCollector().getAlerts(); Assert.assertEquals("List errors size", 3, source.size()); - Alert alert = null; - alert = new Alert(141, "", "#check_point", "Unable to check checkpoint at compile time", AlertType.WARNING); + Alert alert = new Alert(141, "", "#check_point", "Unable to check checkpoint at compile time", AlertType.WARNING); Assert.assertTrue(alert.toString(), source.remove(alert)); alert = new Alert(292, "", "FInteger", "Reference to unknown column 'idleTimeout' is found in column 'FInteger': '${settings.idleTimeout}'.", AlertType.WARNING); Assert.assertTrue(alert.toString(), source.remove(alert)); @@ -110,8 +109,9 @@ public void test_valid_maxSendOrders() throws Exception AML aml = executeTest(VALID_TEST_PATH + "03_test_maxSendOrders.csv"); Assert.assertEquals(0, aml.getAlertCollector().getCount(AlertType.ERROR)); System.gc(); - if (aml != null) - aml.cleanup(); + if(aml != null) { + aml.cleanup(); + } System.gc(); } @@ -158,8 +158,7 @@ public void testIncludeBlock() throws AMLException, IOException, InterruptedExce Assert.assertEquals(17, aml.getTestCases().get(0).getActions().size()); Assert.assertEquals(11, aml.getTestCases().get(1).getActions().size()); - Alert alert = null; - alert = new Alert(24, "m3", "MarketDepthLevel_2_4", "Reference to unknown column 'm2' is found in column 'MarketDepthLevel_2_4': '[include1.m2.MarketDepthLevel_2_4]'.", AlertType.WARNING); + Alert alert = new Alert(24, "m3", "MarketDepthLevel_2_4", "Reference to unknown column 'm2' is found in column 'MarketDepthLevel_2_4': '[include1.m2.MarketDepthLevel_2_4]'.", AlertType.WARNING); Assert.assertTrue(alert.toString(), source.remove(alert)); alert = new Alert(24, "m3", "MarketDepthLevel_2_4" ,"Reference to unknown column 'MarketDepthLevel_2_4' is found in column 'MarketDepthLevel_2_4': '[include1.m2.MarketDepthLevel_2_4]'.", AlertType.WARNING); Assert.assertTrue(alert.toString(), source.remove(alert)); @@ -188,9 +187,7 @@ public void test_invalid_all() throws Exception } catch (AMLException e) { Collection source = e.getAlertCollector().getAlerts(); - Alert alert = null; - - alert = new Alert(36, "", "#check_point", "Unable to check checkpoint at compile time", AlertType.WARNING); + Alert alert = new Alert(36, "", "#check_point", "Unable to check checkpoint at compile time", AlertType.WARNING); Assert.assertTrue(alert.toString(), source.remove(alert)); alert = new Alert(37, "", "#check_point", "Unable to check checkpoint at compile time", AlertType.WARNING); Assert.assertTrue(alert.toString(), source.remove(alert)); diff --git a/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/util/AML3PluginTest.java b/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/util/AML3PluginTest.java index 78908395..d2d34508 100644 --- a/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/util/AML3PluginTest.java +++ b/BackEnd/Extension/extension-aml-3/src/test/java/com/exactpro/sf/util/AML3PluginTest.java @@ -53,8 +53,8 @@ public class AML3PluginTest { protected static ISFContext context; - private static boolean isLoggingAlreadyConfigured = false; - private static boolean isAlreadyConfigured = false; + private static boolean isLoggingAlreadyConfigured; + private static boolean isAlreadyConfigured; private static final String DEFAULT_CFG_FILENAME = "sf.cfg.xml"; @@ -72,13 +72,13 @@ public String getPath(File root, FolderType folderType) { case ROOT: return new StringBuilder(BASE_DIR.getAbsolutePath()) .append(File.separator).append("src") - .append(File.separator).append(this.rootFolder) + .append(File.separator).append(rootFolder) .append(File.separator).append("plugin") .toString(); case CFG: return new StringBuilder(BASE_DIR.getAbsolutePath()) .append(File.separator).append("src") - .append(File.separator).append(this.rootFolder) + .append(File.separator).append(rootFolder) .append(File.separator).append("plugin") .append(File.separator).append("cfg") .toString(); diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/actions/FastMatrixActions.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/actions/FastMatrixActions.java index 5a61d573..528309a2 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/actions/FastMatrixActions.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/actions/FastMatrixActions.java @@ -15,6 +15,8 @@ ******************************************************************************/ package com.exactpro.sf.actions; +import org.apache.commons.lang3.StringUtils; + import com.exactpro.sf.aml.CommonColumn; import com.exactpro.sf.aml.CommonColumns; import com.exactpro.sf.aml.generator.matrix.Column; @@ -30,7 +32,7 @@ import com.exactpro.sf.services.fast.FASTAbstractTCPClient; @MatrixActions -@ResourceAliases({"FastMatrixActions"}) +@ResourceAliases("FastMatrixActions") public class FastMatrixActions extends AbstractCaller { @CommonColumns({ @CommonColumn(Column.CheckPoint), @@ -51,9 +53,7 @@ public void FAST_Connect(IActionContext actionContext) fClient.connect(); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void FAST_Disconnect(IActionContext actionContext) throws Exception { @@ -65,9 +65,7 @@ public void FAST_Disconnect(IActionContext actionContext) fClient.disconnect(); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void FAST_isDisconnected(IActionContext actionContext) throws Exception { @@ -77,7 +75,9 @@ public void FAST_isDisconnected(IActionContext actionContext) } FASTAbstractTCPClient fClient = (FASTAbstractTCPClient) client; String actionId = actionContext.getId(); - if (actionId != null && !actionId.equals("")) actionId += " "; + if(StringUtils.isNotEmpty(actionId)) { + actionId += " "; + } IActionReport report = actionContext.getReport(); String verificationName = actionId + String.format("Checking whether the service [%s] is disconnected", client.getName()); ComparisonResult cr = new ComparisonResult("FAST_isDisconnected"); @@ -102,9 +102,7 @@ public void FAST_isDisconnected(IActionContext actionContext) } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void FAST_isConnected(IActionContext actionContext) throws Exception { @@ -114,7 +112,9 @@ public void FAST_isConnected(IActionContext actionContext) } FASTAbstractTCPClient fClient = (FASTAbstractTCPClient) client; String actionId = actionContext.getId(); - if (actionId != null && !actionId.equals("")) actionId += " "; + if(StringUtils.isNotEmpty(actionId)) { + actionId += " "; + } IActionReport report = actionContext.getReport(); String verificationName = actionId + String.format("Checking whether the session [%s] is connected", client.getName()); ComparisonResult cr = new ComparisonResult("FAST_isConnected"); diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/configuration/factory/FASTMessageFactory.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/configuration/factory/FASTMessageFactory.java index 65ba82f0..893c769d 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/configuration/factory/FASTMessageFactory.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/configuration/factory/FASTMessageFactory.java @@ -22,7 +22,7 @@ import com.google.common.collect.ImmutableSet; public class FASTMessageFactory extends AbstractMessageFactory { - public final static Set UNCHECKED_FIELDS = ImmutableSet.of( + public static final Set UNCHECKED_FIELDS = ImmutableSet.of( "SendingTime", FASTMessageHelper.TEMPLATE_ID_FIELD, FASTMessageHelper.MESSAGE_TYPE_FIELD diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractClient.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractClient.java index 7fabfa85..9e53d879 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractClient.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractClient.java @@ -69,11 +69,11 @@ public abstract class FASTAbstractClient implements IInitiatorService { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private volatile ServiceStatus curStatus; - private ISession session = null; + private ISession session; private final AtomicBoolean sessionClosed = new AtomicBoolean(true); @@ -91,15 +91,15 @@ public abstract class FASTAbstractClient implements IInitiatorService { protected MessageHelper messageHelper; protected IFastMessageFilter messageFilter; - private TemplateRegistry registry = null; + private TemplateRegistry registry; private FastToIMessageConverter converter; - protected Connection connection = null; + protected Connection connection; protected FASTMessageInputStream msgInStream; - private Thread thread = null; + private Thread thread; private RecordingInputStream recordingInputStream; @@ -110,15 +110,15 @@ public abstract class FASTAbstractClient implements IInitiatorService { @Override public void init( IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName name) { + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName name) { logger.debug("Initializing AbstractFastClient {}", this); try { - this.changeStatus(ServiceStatus.INITIALIZING, "Service initializing", null); + changeStatus(ServiceStatus.INITIALIZING, "Service initializing", null); logger.info("Initializing service {} ...", this); this.serviceName = Objects.requireNonNull(name, "'Service name' parameter"); @@ -127,21 +127,21 @@ public void init( internalInit(name, handler, settings, serviceMonitor, serviceContext); - this.changeStatus(ServiceStatus.INITIALIZED, "Service initialized", null); + changeStatus(ServiceStatus.INITIALIZED, "Service initialized", null); logger.debug("Abstract client initialized"); } catch ( RuntimeException e ) { - logger.error("Exception during service [{}] initializing", this.serviceName, e); - this.changeStatus(ServiceStatus.ERROR, "", e); + logger.error("Exception during service [{}] initializing", serviceName, e); + changeStatus(ServiceStatus.ERROR, "", e); throw new ServiceException(e); } } protected void internalInit( - final ServiceName name, - final IServiceHandler handler, - final IServiceSettings settings, - final IServiceMonitor serviceMonitor, + ServiceName name, + IServiceHandler handler, + IServiceSettings settings, + IServiceMonitor serviceMonitor, IServiceContext serviceContext) { this.monitor = Objects.requireNonNull(serviceMonitor, "'Service monitor' parameter"); @@ -151,13 +151,13 @@ protected void internalInit( if (settings == null) { throw new NullPointerException("'settings' parameter"); } - this.setSettings((FASTClientSettings) settings); + setSettings((FASTClientSettings)settings); this.handler = Objects.requireNonNull(handler, "'Service handler' parameter"); this.dictionaryManager = Objects.requireNonNull(serviceContext.getDictionaryManager(), "'Dictionary manager' parameter"); - if (this.getSettings().getDictionaryName() == null) { + if(getSettings().getDictionaryName() == null) { throw new NullPointerException("settings.dictionaryName is null"); } @@ -166,7 +166,7 @@ protected void internalInit( this.logConfigurator = Objects.requireNonNull(this.serviceContext.getLoggingConfigurator(), "'Logging configurator' parameter"); this.serviceInfo = serviceContext.lookupService(serviceName); - logger.info("Initializing service [{}] ... done", this.serviceName); + logger.info("Initializing service [{}] ... done", serviceName); this.messageFilter = configureMessageFilter(); SailfishURI dictionaryName = getSettings().getDictionaryName(); @@ -176,21 +176,18 @@ protected void internalInit( loadFastTemplates(serviceContext.getDataManager(), dictionaryName.getPluginAlias(), templateName); this.messageHelper = new FASTMessageHelper(); - this.messageHelper.init(this.dictionaryManager.getMessageFactory(dictionaryName), this.dictionary); + messageHelper.init(dictionaryManager.getMessageFactory(dictionaryName), dictionary); } private IFastMessageFilter configureMessageFilter() { FASTClientSettings settigns = getSettings(); String requiredValues = settigns.getMessageFilterExpression(); - if (requiredValues == null) { - return new SimpleMessageFilter(); - } - return new SimpleMessageFilter(requiredValues); - } + return requiredValues == null ? new SimpleMessageFilter() : new SimpleMessageFilter(requiredValues); + } protected FastToIMessageConverter createConverter() { - if (this.converter == null) { + if(converter == null) { FastToIMessageConverter converter = new FastToIMessageConverter( dictionaryManager.getMessageFactory(getSettings().getDictionaryName()), dictionary.getNamespace() @@ -200,7 +197,7 @@ protected FastToIMessageConverter createConverter() { return converter; } - private void loadFastTemplates(final IDataManager dataManager, String pluginAlias, String templateName) { + private void loadFastTemplates(IDataManager dataManager, String pluginAlias, String templateName) { XMLMessageTemplateLoader loader = new XMLMessageTemplateLoader(); loader.setLoadTemplateIdFromAuxId(true); @@ -221,17 +218,17 @@ protected void changeStatus(ServiceStatus status, String message, Throwable e) { @Override public IServiceHandler getServiceHandler() { - return this.handler; + return handler; } @Override public void dispose() { - this.changeStatus(ServiceStatus.DISPOSING, "Service is disposing", null); + changeStatus(ServiceStatus.DISPOSING, "Service is disposing", null); doDispose(); - this.changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); + changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); if(logConfigurator != null) { - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } } @@ -252,11 +249,11 @@ public ServiceName getServiceName() { @Override public void start() { - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); - this.changeStatus(ServiceStatus.STARTING, "Service is starting", null); + changeStatus(ServiceStatus.STARTING, "Service is starting", null); doStart(); - this.changeStatus(ServiceStatus.STARTED, "Service is started", null); + changeStatus(ServiceStatus.STARTED, "Service is started", null); } protected abstract void doStart(); @@ -276,7 +273,7 @@ public ISession getSession() { } protected ISession createSession() { - return new FASTSession(this, this.messageHelper); + return new FASTSession(this, messageHelper); } protected Context createFastContext() { @@ -324,7 +321,7 @@ protected void initConnection() { try { this.connection = getConnection(remoteAddr, port, interfaceAddress); - this.sessionClosed.set(false); + sessionClosed.set(false); } catch (FastConnectionException e) { closeSession(); logger.error("Failed to connect to {}:{}", remoteAddr, port, e); @@ -471,7 +468,7 @@ protected void handleIMessage(IMessage iMessage){ } protected synchronized void closeSession() { - if (this.sessionClosed.compareAndSet(false, true)) { + if(sessionClosed.compareAndSet(false, true)) { logger.debug("Closing session"); if (thread != null) { thread.interrupt(); @@ -518,12 +515,12 @@ protected Context getFastContext() { } public boolean isSessionClosed() { - return this.sessionClosed.get(); + return sessionClosed.get(); } @Override public IMessage receive(IActionContext actionContext, IMessage msg) throws InterruptedException { - msg = this.messageHelper.prepareMessageToEncode(msg, null); + msg = messageHelper.prepareMessageToEncode(msg, null); return WaitAction.waitForMessage(actionContext, msg, !msg.getMetaData().isAdmin()); } } \ No newline at end of file diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractTCPClient.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractTCPClient.java index a04b3ef5..0b5071d9 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractTCPClient.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTAbstractTCPClient.java @@ -19,7 +19,7 @@ import org.slf4j.LoggerFactory; public abstract class FASTAbstractTCPClient extends FASTAbstractClient{ - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); @Override public synchronized void connect(){ diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodec.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodec.java index adca84ff..31f3e70c 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodec.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodec.java @@ -99,7 +99,7 @@ public void init( private void createConverter() { - if (this.converter == null) { + if(converter == null) { FastToIMessageConverter converter = new FastToIMessageConverter( msgFactory, msgDictionary.getNamespace() @@ -108,7 +108,7 @@ private void createConverter() { } } - private void loadFastTemplates(final IDataManager dataManager, String pluginAlias, String templateName) { + private void loadFastTemplates(IDataManager dataManager, String pluginAlias, String templateName) { XMLMessageTemplateLoader loader = new XMLMessageTemplateLoader(); loader.setLoadTemplateIdFromAuxId(true); @@ -169,8 +169,9 @@ protected boolean doDecode( public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (!session.getTransportMetadata().hasFragmentation()) { - if (settings.isResetContextAfterEachUdpPacket()) - getInputContext(session).reset(); + if(settings.isResetContextAfterEachUdpPacket()) { + getInputContext(session).reset(); + } } super.decode(session, in, out); } @@ -180,11 +181,11 @@ private boolean doRealDecode( IoBuffer in, ProtocolDecoderOutput out) throws IOException, ConverterException { int position = in.position(); - byte data [] = new byte[in.remaining()]; + byte[] data = new byte[in.remaining()]; in.get(data); try(InputStream is = new EofCheckedStream(new ByteArrayInputStream(data))) { - int msgLen = (TypeCodec.UINT.decode(is)).toInt(); + int msgLen = TypeCodec.UINT.decode(is).toInt(); if(is.available() < msgLen) { return false; } @@ -223,14 +224,9 @@ private void fillMessageMetadata( metaData.setAdmin(isAdmin); //metaData.setToService(this.serviceName); - String packetAddress; - if (in instanceof IoBufferWithAddress) { - packetAddress = ((IoBufferWithAddress)in).getAddress(); - } else { - packetAddress = session.getRemoteAddress().toString(); - } + String packetAddress = in instanceof IoBufferWithAddress ? ((IoBufferWithAddress)in).getAddress() : session.getRemoteAddress().toString(); - metaData.setFromService(packetAddress); + metaData.setFromService(packetAddress); metaData.setRawMessage(rawMessage); } @@ -262,9 +258,8 @@ public void encode( IMessageToFastConverter converter = getIMessageToFastConverter(); IMessage iMsg = (IMessage) message; - Message fastMsg; - fastMsg = converter.convert(iMsg); + Message fastMsg = converter.convert(iMsg); ByteArrayOutputStream os = new ByteArrayOutputStream(); Context oc = getOutputContext(session); MessageOutputStream msgOutStream = new MessageOutputStream(os, oc); @@ -283,7 +278,7 @@ public void encode( private IMessageToFastConverter getIMessageToFastConverter() { if (iMsgToFastConverter == null) { - IDictionaryStructure dictionary = this.msgDictionary; + IDictionaryStructure dictionary = msgDictionary; iMsgToFastConverter = new IMessageToFastConverter(dictionary, getRegistry()); } return iMsgToFastConverter; diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodecSettings.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodecSettings.java index 1694d740..f925469b 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodecSettings.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTCodecSettings.java @@ -26,19 +26,15 @@ public class FASTCodecSettings extends AbstractServiceSettings { private static final long serialVersionUID = 3426549826737983629L; - private int skipInitialByteAmount = 0; + private int skipInitialByteAmount; private boolean streamBlockEncoded = true; private boolean resetContextAfterEachUdpPacket = true; @RequiredParam @Description("Dictionary title") private SailfishURI dictionaryName; - public FASTCodecSettings() { - super(); - } - - public boolean isStreamBlockEncoded() { - return this.streamBlockEncoded; + public boolean isStreamBlockEncoded() { + return streamBlockEncoded; } public void setStreamBlockEncoded(boolean streamBlockEncoded) { diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTInvalidSession.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTInvalidSession.java index 939a4088..182453d6 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTInvalidSession.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTInvalidSession.java @@ -21,7 +21,7 @@ class FASTInvalidSession implements ISession { - private String name; + private final String name; FASTInvalidSession(String name) { this.name = name; diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageHelper.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageHelper.java index 673154e2..b40dccb9 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageHelper.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageHelper.java @@ -64,8 +64,8 @@ public void init(IMessageFactory messageFactory, IDictionaryStructure dictionary @Override public IMessage prepareMessageToEncode(IMessage message, Map params) { - addCachedValue(message, MESSAGE_TYPE_FIELD, this.messageTypes); - addCachedValue(message, TEMPLATE_ID_FIELD, this.templateIds); + addCachedValue(message, MESSAGE_TYPE_FIELD, messageTypes); + addCachedValue(message, TEMPLATE_ID_FIELD, templateIds); return message; } diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageInputStream.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageInputStream.java index 842cc007..0785ba4f 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageInputStream.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMessageInputStream.java @@ -16,6 +16,7 @@ package com.exactpro.sf.services.fast; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -35,9 +36,9 @@ import org.openfast.template.TemplateRegistry; public class FASTMessageInputStream implements MessageStream { - private InputStream in; - private FastDecoder decoder; - private Context context; + private final InputStream in; + private final FastDecoder decoder; + private final Context context; private Map templateHandlers = Collections.emptyMap(); private List handlers = Collections.emptyList(); private MessageBlockReader blockReader = MessageBlockReader.NULL; @@ -53,15 +54,17 @@ public FASTMessageInputStream(InputStream inputStream, Context context) { } /** - * @throws java.io.EOFException + * @throws EOFException * @return the next message in the stream */ public Message readMessage(int skipInitialByteAmount) { - if (context.isTraceEnabled()) + if(context.isTraceEnabled()) { context.startTrace(); + } boolean keepReading = blockReader.readBlock(in); - if (!keepReading) + if(!keepReading) { return null; + } skipInitialByte(in, skipInitialByteAmount); Message message = decoder.readMessage(); if (message == null) { diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMulticastProxyClient.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMulticastProxyClient.java index 039be79d..c1711d31 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMulticastProxyClient.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTMulticastProxyClient.java @@ -16,8 +16,6 @@ package com.exactpro.sf.services.fast; -import com.exactpro.sf.services.fast.blockstream.IPacketHandler; -import com.exactpro.sf.services.fast.blockstream.MulticastProxyConnection; import org.openfast.Context; import org.openfast.MessageBlockReader; import org.openfast.session.Connection; @@ -25,8 +23,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.exactpro.sf.services.fast.blockstream.IPacketHandler; +import com.exactpro.sf.services.fast.blockstream.MulticastProxyConnection; + public class FASTMulticastProxyClient extends FASTTcpClient { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private MulticastProxyConnection connection; @@ -50,10 +51,7 @@ public void handlePacket(byte[] packetData) { @Override protected MessageBlockReader getBlockReader() { - if (getSettings().isStreamBlockEncoded()) { - return connection.getBlockReader(); - } - return MessageBlockReader.NULL; + return getSettings().isStreamBlockEncoded() ? connection.getBlockReader() : MessageBlockReader.NULL; } private Context getReceiveContext() { diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTSession.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTSession.java index 78466221..ee203c3b 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTSession.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTSession.java @@ -61,12 +61,12 @@ public IMessage sendDirty(Object message) throws InterruptedException { @Override public void close() { - this.fastClient.closeSession(); + fastClient.closeSession(); } @Override public boolean isClosed() { - return this.fastClient.isSessionClosed(); + return fastClient.isSessionClosed(); } @Override @@ -80,8 +80,8 @@ public String toString() { } protected void internalSend(Object msg) throws InterruptedException { - synchronized (this.fastClient) { - this.fastClient.send(msg); + synchronized(fastClient) { + fastClient.send(msg); } } } \ No newline at end of file diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTTcpClient.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTTcpClient.java index e2a4d095..f4cfca1e 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTTcpClient.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTTcpClient.java @@ -15,6 +15,9 @@ ******************************************************************************/ package com.exactpro.sf.services.fast; +import static com.exactpro.sf.services.ServiceHandlerRoute.TO_ADMIN; +import static com.exactpro.sf.services.ServiceHandlerRoute.TO_APP; + import java.io.IOException; import java.io.OutputStream; @@ -36,7 +39,6 @@ import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.common.util.SendMessageFailedException; -import com.exactpro.sf.services.ServiceHandlerRoute; import com.exactpro.sf.services.ServiceStatus; import com.exactpro.sf.services.fast.blockstream.BlockEncodedOutputStream; import com.exactpro.sf.services.fast.blockstream.StreamBlockLengthReader; @@ -45,13 +47,12 @@ public class FASTTcpClient extends FASTAbstractTCPClient { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private MessageOutputStream msgOutStream; private volatile IMessageToFastConverter iMsgToFastConverter; public FASTTcpClient() { - super(); - changeStatus(ServiceStatus.CREATED, "Service created", null); + changeStatus(ServiceStatus.CREATED, "Service created", null); } @Override @@ -116,11 +117,7 @@ protected void send(Object message) throws InterruptedException { } try { - if (iMsg.getMetaData().isAdmin()) { - getServiceHandler().putMessage(getSession(), ServiceHandlerRoute.TO_ADMIN, iMsg); - } else { - getServiceHandler().putMessage(getSession(), ServiceHandlerRoute.TO_APP, iMsg); - } + getServiceHandler().putMessage(getSession(), iMsg.getMetaData().isAdmin() ? TO_ADMIN : TO_APP, iMsg); } catch (Exception e) { if(e instanceof InterruptedException){ throw (InterruptedException)e; @@ -145,11 +142,8 @@ private IMessageToFastConverter getIMessageToFastConverter() { @Override protected MessageBlockReader getBlockReader() { - if (getSettings().isStreamBlockEncoded()) { - return new StreamBlockLengthReader(); - } - return MessageBlockReader.NULL; - } + return getSettings().isStreamBlockEncoded() ? new StreamBlockLengthReader() : MessageBlockReader.NULL; + } @Override public String toString() { diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTUdpClient.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTUdpClient.java index 33bbb49b..f9c555a2 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTUdpClient.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/FASTUdpClient.java @@ -22,6 +22,7 @@ import java.net.MulticastSocket; import java.net.NetworkInterface; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.openfast.Context; import org.openfast.Message; @@ -48,10 +49,10 @@ public class FASTUdpClient extends FASTAbstractClient { @Override public void init( IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName name) { + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName name) { super.init(serviceContext, serviceMonitor, handler, settings, name); this.resetContext = getSettings().isResetContextAfterEachUdpPacket(); } @@ -67,7 +68,7 @@ protected DatagramConnection getConnection(String remoteAddr, int port, try { NetworkInterface netIface = null; - if (interfaceAddress != null && !interfaceAddress.equals("")){ + if(StringUtils.isNotEmpty(interfaceAddress)) { if (interfaceAddress.matches("([0-9]{1,3}\\.){3}[0-9]{1,3}")) { netIface = NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceAddress)); } else { @@ -75,14 +76,7 @@ protected DatagramConnection getConnection(String remoteAddr, int port, } } - MulticastSocket socket; -// if (interfaceAddress == null || interfaceAddress.equals("")) { - socket = new MulticastSocket(port); -// } else { -// SocketAddress saddr = new InetSocketAddress(interfaceAddress, port); -// socket = new MulticastSocket(saddr); -// } - + MulticastSocket socket = new MulticastSocket(port); InetAddress groupAddress = InetAddress.getByName(remoteAddr); if (netIface == null){ @@ -108,7 +102,7 @@ public void handlePacket(byte[] packetData) { } } ); - return this.datagramConnection; + return datagramConnection; } catch (IOException e) { FastConnectionException expt = new FastConnectionException( "Failed to create connection" @@ -134,8 +128,9 @@ protected void doStart() { @Override protected synchronized void closeSession() { - if (connection != null) - connection.close(); + if(connection != null) { + connection.close(); + } connection = null; } @@ -147,7 +142,7 @@ protected MessageBlockReader getBlockReader() { @Override protected boolean recoverFromInputError(InputStream underlyingStream) { - this.datagramConnection.getInputStream().clearBuffer(); + datagramConnection.getInputStream().clearBuffer(); return true; } diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/BlockEncodedUdpInputStream.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/BlockEncodedUdpInputStream.java index 3489cb02..e7552cc1 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/BlockEncodedUdpInputStream.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/BlockEncodedUdpInputStream.java @@ -19,17 +19,17 @@ import java.io.InputStream; import java.net.DatagramSocket; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.openfast.IntegerValue; import org.openfast.ScalarValue; import org.openfast.template.LongValue; import org.openfast.template.type.codec.TypeCodec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class BlockEncodedUdpInputStream extends UdpInputStream { - private final static Logger logger = LoggerFactory.getLogger(BlockEncodedUdpInputStream.class); + private static final Logger logger = LoggerFactory.getLogger(BlockEncodedUdpInputStream.class); - private long remainingBlockLen = 0; + private long remainingBlockLen; public BlockEncodedUdpInputStream(DatagramSocket socket) { this(socket, null); diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/DatagramConnection.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/DatagramConnection.java index 9b0fc064..45218b91 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/DatagramConnection.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/DatagramConnection.java @@ -20,24 +20,20 @@ import java.net.InetAddress; import java.net.MulticastSocket; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.openfast.MessageBlockReader; import org.openfast.session.Connection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class DatagramConnection implements Connection { - private final static Logger logger = LoggerFactory.getLogger(DatagramConnection.class); - private MulticastSocket socket; - private InetAddress group; - private UdpInputStream inputStream; + private static final Logger logger = LoggerFactory.getLogger(DatagramConnection.class); + private final MulticastSocket socket; + private final InetAddress group; + private final UdpInputStream inputStream; public DatagramConnection(MulticastSocket socket, InetAddress group, boolean isBlockEncoded, IPacketHandler packetHandler) { - if (isBlockEncoded) { - this.inputStream = new BlockEncodedUdpInputStream(socket, packetHandler); - } else { - this.inputStream = new UdpInputStream(socket, packetHandler); - } + this.inputStream = isBlockEncoded ? new BlockEncodedUdpInputStream(socket, packetHandler) : new UdpInputStream(socket, packetHandler); this.socket = socket; this.group = group; } diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/IPacketHandler.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/IPacketHandler.java index 3ce5b03a..71612dfb 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/IPacketHandler.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/IPacketHandler.java @@ -17,6 +17,6 @@ public interface IPacketHandler { - public void handlePacket(byte[] packetData); + void handlePacket(byte[] packetData); } diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyConnection.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyConnection.java index 07eef31a..5931a73f 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyConnection.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyConnection.java @@ -16,19 +16,19 @@ package com.exactpro.sf.services.fast.blockstream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; + import org.openfast.MessageBlockReader; import org.openfast.session.Connection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; - public class MulticastProxyConnection implements Connection { - private final static Logger logger = LoggerFactory.getLogger(DatagramConnection.class); + private static final Logger logger = LoggerFactory.getLogger(DatagramConnection.class); private final int port; - private String host; + private final String host; private Socket socket; private MulticastProxyInputStream inputStream; diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyInputStream.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyInputStream.java index 6e42f7d4..7fccf399 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyInputStream.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/MulticastProxyInputStream.java @@ -16,26 +16,26 @@ package com.exactpro.sf.services.fast.blockstream; -import org.openfast.Message; -import org.openfast.MessageBlockReader; -import org.openfast.template.type.codec.TypeCodec; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.nio.ByteBuffer; +import org.openfast.Message; +import org.openfast.MessageBlockReader; +import org.openfast.template.type.codec.TypeCodec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class MulticastProxyInputStream extends InputStream implements MessageBlockReader { - private final static Logger logger = LoggerFactory.getLogger(UdpInputStream.class); + private static final Logger logger = LoggerFactory.getLogger(UdpInputStream.class); protected static final int BUFFER_SIZE = 64 * 1024; private ByteBuffer buffer; - private Socket socket; - private IPacketHandler packetHandler; - private DataInputStream inputStream; + private final Socket socket; + private final IPacketHandler packetHandler; + private final DataInputStream inputStream; public MulticastProxyInputStream(Socket socket, IPacketHandler packetHandler) throws IOException { @@ -52,8 +52,9 @@ public MulticastProxyInputStream(Socket socket, int bufferSize, IPacketHandler p @Override public int read() throws IOException { - if (socket.isClosed()) + if(socket.isClosed()) { return -1; + } if (!buffer.hasRemaining()) { if (logger.isDebugEnabled()) { logger.debug("reading new packet"); @@ -64,11 +65,12 @@ public int read() throws IOException { inputStream.read(msg); buffer = ByteBuffer.wrap(msg); buffer.flip(); - if (packetHandler != null) + if(packetHandler != null) { packetHandler.handlePacket(buffer.array()); //Reset context + } buffer.limit(msgSize); } - return (buffer.get() & 0xFF); + return buffer.get() & 0xFF; } @Override @@ -77,7 +79,7 @@ public void messageRead(InputStream arg0, Message arg1) { @Override public boolean readBlock(InputStream stream) { - int n = (TypeCodec.UINT.decode(stream)).toInt(); + int n = TypeCodec.UINT.decode(stream).toInt(); if (logger.isDebugEnabled()) { logger.debug("new block length:{}", n); diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/StreamBlockLengthReader.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/StreamBlockLengthReader.java index c5f725dc..7ff0cf13 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/StreamBlockLengthReader.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/StreamBlockLengthReader.java @@ -17,14 +17,14 @@ import java.io.InputStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.openfast.Message; import org.openfast.MessageBlockReader; import org.openfast.template.type.codec.TypeCodec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class StreamBlockLengthReader implements MessageBlockReader { - private final static Logger logger = LoggerFactory.getLogger(StreamBlockLengthReader.class); + private static final Logger logger = LoggerFactory.getLogger(StreamBlockLengthReader.class); @Override public void messageRead(InputStream arg0, Message arg1) { @@ -32,7 +32,7 @@ public void messageRead(InputStream arg0, Message arg1) { @Override public boolean readBlock(InputStream stream) { - int n = (TypeCodec.UINT.decode(stream)).toInt(); + int n = TypeCodec.UINT.decode(stream).toInt(); logger.trace("Read message length:{}", n); return true; } diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/UdpInputStream.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/UdpInputStream.java index a43f0629..1063a40c 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/UdpInputStream.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/blockstream/UdpInputStream.java @@ -21,20 +21,20 @@ import java.net.DatagramSocket; import java.nio.ByteBuffer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.openfast.Message; import org.openfast.MessageBlockReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class UdpInputStream extends InputStream implements MessageBlockReader { - private final static Logger logger = LoggerFactory.getLogger(UdpInputStream.class); + private static final Logger logger = LoggerFactory.getLogger(UdpInputStream.class); protected static final int BUFFER_SIZE = 64 * 1024; - private DatagramSocket socket; - private ByteBuffer buffer; + private final DatagramSocket socket; + private final ByteBuffer buffer; private boolean canReceivePacket; - private IPacketHandler packetHandler; + private final IPacketHandler packetHandler; public UdpInputStream(DatagramSocket socket) { this(socket, BUFFER_SIZE, null); @@ -53,8 +53,9 @@ public UdpInputStream(DatagramSocket socket, int bufferSize, IPacketHandler pack @Override public int read() throws IOException { - if (socket.isClosed()) - return -1; + if(socket.isClosed()) { + return -1; + } if (!buffer.hasRemaining()) { if (!canReceivePacket) { logger.debug("no data left in the buffer."); @@ -66,12 +67,13 @@ public int read() throws IOException { buffer.capacity()); socket.receive(packet); buffer.flip(); - if (packetHandler != null) - packetHandler.handlePacket(buffer.array()); //Reset context + if(packetHandler != null) { + packetHandler.handlePacket(buffer.array()); //Reset context + } buffer.limit(packet.getLength()); } canReceivePacket = false; - return (buffer.get() & 0xFF); + return buffer.get() & 0xFF; } public void clearBuffer() { diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/ConverterException.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/ConverterException.java index 0edec7cd..a2cf2860 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/ConverterException.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/ConverterException.java @@ -18,8 +18,7 @@ public class ConverterException extends Exception { public ConverterException() { - super(); - } + } public ConverterException(String message, Throwable cause) { super(message, cause); diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FASTException.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FASTException.java index e27b240d..c74c86bf 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FASTException.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FASTException.java @@ -23,8 +23,7 @@ public class FASTException extends RuntimeException * */ public FASTException() { - super(); - } + } /** * @param message diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FastToIMessageConverter.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FastToIMessageConverter.java index aa1f6e5a..3d4b908e 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FastToIMessageConverter.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FastToIMessageConverter.java @@ -17,8 +17,10 @@ import java.io.UnsupportedEncodingException; import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import org.apache.commons.lang3.StringUtils; import org.openfast.FieldValue; import org.openfast.GroupValue; import org.openfast.Message; @@ -36,7 +38,7 @@ import com.exactpro.sf.common.messages.IMessageFactory; public class FastToIMessageConverter { - private final static Logger logger = LoggerFactory.getLogger(FastToIMessageConverter.class); + private static final Logger logger = LoggerFactory.getLogger(FastToIMessageConverter.class); private final IMessageFactory messageFactory; private final String namespace; @@ -94,15 +96,15 @@ private void convertField( return; } - if (fastFld.getTypeName().equals("scalar")) { + if("scalar".equals(fastFld.getTypeName())) { setScalarValue((Scalar) fastFld, fastMsg, message, iMessageFieldName ); - } else if (fastFld.getTypeName().equals("sequence")) { + } else if("sequence".equals(fastFld.getTypeName())) { SequenceValue sqsValue = fastMsg.getSequence(index); convertSequence(sqsValue, iMessageFieldName, message, msgName); - } else if (fastFld.getTypeName().equals("group")) { + } else if("group".equals(fastFld.getTypeName())) { GroupValue grpValue = fastMsg.getGroup(index); convertGroup(grpValue, iMessageFieldName, message, msgName); - } else if (fastFld.getTypeName().equals("decimal")) { + } else if("decimal".equals(fastFld.getTypeName())) { BigDecimal bdVal = fastMsg.getBigDecimal(index); message.addField(iMessageFieldName, bdVal); } else { @@ -134,7 +136,7 @@ private void convertSequence(SequenceValue sqsValue, Sequence sqs = sqsValue.getSequence(); String lengthName = sqs.getLength().getName(); - if (lengthName == null || lengthName.equals("")) { + if(StringUtils.isEmpty(lengthName)) { lengthName = "length"; } lengthName = getIMessageName(lengthName); @@ -142,7 +144,7 @@ private void convertSequence(SequenceValue sqsValue, message.addField(lengthName, sqsValue.getLength()); String msgType = msgName + "_" + iMessageFieldName; - java.util.ArrayList collectionMessages = new ArrayList(); + ArrayList collectionMessages = new ArrayList(); for(GroupValue groupVal:sqsValue.getValues()) { IMessage innerMessage; try { @@ -164,27 +166,27 @@ private void setScalarValue(Scalar fastFld, GroupValue fastMsg, Group grp = fastMsg.getGroup(); int index = grp.getFieldIndex(fastFld); - if (fastFld.getType().getName().equals("int8")) { + if("int8".equals(fastFld.getType().getName())) { Byte byteVal = fastMsg.getByte(index); if (byteVal != null) { message.addField(iMessageFieldName, byteVal); } - } else if (fastFld.getType().getName().equals("int32")) { + } else if("int32".equals(fastFld.getType().getName())) { Integer intVal = fastMsg.getInt(index); if (intVal != null) { message.addField(iMessageFieldName, intVal); } - } else if (fastFld.getType().getName().equals("uInt32")) { + } else if("uInt32".equals(fastFld.getType().getName())) { Long longVal = fastMsg.getLong(index); if (longVal != null) { message.addField(iMessageFieldName, longVal); } - } else if (fastFld.getType().getName().equals("int64")) { + } else if("int64".equals(fastFld.getType().getName())) { Long longVal = fastMsg.getLong(index); if (longVal != null) { message.addField(iMessageFieldName, longVal); } - } else if (fastFld.getType().getName().equals("uInt64")) { + } else if("uInt64".equals(fastFld.getType().getName())) { BigDecimal bdVal = fastMsg.getBigDecimal(index); if (bdVal != null) { message.addField(iMessageFieldName, bdVal); @@ -194,24 +196,20 @@ private void setScalarValue(Scalar fastFld, GroupValue fastMsg, if (sVal != null) { message.addField(iMessageFieldName, sVal); } - } else if (fastFld.getType().getName().equals("decimal")) { + } else if("decimal".equals(fastFld.getType().getName())) { BigDecimal bdVal = fastMsg.getBigDecimal(index); if (bdVal != null) { message.addField(iMessageFieldName, bdVal); } - } else if (fastFld.getType().getName().equals("byteVector")) { + } else if("byteVector".equals(fastFld.getType().getName())) { byte[] bvVal = fastMsg.getBytes(index); if (bvVal != null) { //FIXME: in most cases a separate field contains encoding of the message // message.addField(iMessageFieldName, bvVal); - try { - message.addField(iMessageFieldName, new String(bvVal, "ascii")); - } catch (UnsupportedEncodingException e) { - logger.debug("can not convert bytearray to string with ascii encoding", e); - } - } + message.addField(iMessageFieldName, new String(bvVal, StandardCharsets.US_ASCII)); + } } else { throw new ConverterException("Can not convert field of type: " + fastFld.getType().getName()); diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/IMessageToFastConverter.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/IMessageToFastConverter.java index f243e194..a5f7c1de 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/IMessageToFastConverter.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/IMessageToFastConverter.java @@ -39,7 +39,7 @@ import com.exactpro.sf.common.util.EPSCommonException; public class IMessageToFastConverter { - private final static Logger logger = LoggerFactory.getLogger(IMessageToFastConverter.class); + private static final Logger logger = LoggerFactory.getLogger(IMessageToFastConverter.class); private final IDictionaryStructure dictionary; private final TemplateRegistry templateRegistry; @@ -94,9 +94,8 @@ private void convertFields(GroupValue fastMsg, IMessage message) private void convertField(Group template, GroupValue fastMsg, IMessage message, String fieldName, IMessageStructure structure) throws ConverterException { - String fastFieldName = null; - IFieldStructure messageFieldDescr = msgFielsMap.get(structure).get(fieldName); - fastFieldName = getAttributeValue(messageFieldDescr, "fastName"); + IFieldStructure messageFieldDescr = msgFielsMap.get(structure).get(fieldName); + String fastFieldName = getAttributeValue(messageFieldDescr, "fastName"); if (fastFieldName == null) { Boolean isLength = getAttributeValue(messageFieldDescr, "isLength"); @@ -115,7 +114,7 @@ private void setFastField(Group template, GroupValue fastMsg, String fastFieldNa throws ConverterException { if (value instanceof Byte) { - byte[] byteValue = new byte[] { (Byte) value }; + byte[] byteValue = { (Byte)value }; fastMsg.setByteVector(fastFieldName, byteValue); } else if (value instanceof Integer) { Integer intValue = (Integer) value; diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/IFastMessageFilter.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/IFastMessageFilter.java index 1b2ed08c..5ee9524d 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/IFastMessageFilter.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/IFastMessageFilter.java @@ -19,6 +19,6 @@ public interface IFastMessageFilter { - public abstract boolean isMessageAcceptable(Message fastMsg); + boolean isMessageAcceptable(Message fastMsg); } \ No newline at end of file diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/SimpleMessageFilter.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/SimpleMessageFilter.java index fe32a544..a90c1594 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/SimpleMessageFilter.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/filter/SimpleMessageFilter.java @@ -15,14 +15,14 @@ ******************************************************************************/ package com.exactpro.sf.services.fast.filter; +import java.util.HashMap; +import java.util.HashSet; + import org.openfast.GroupValue; import org.openfast.Message; import org.openfast.template.Field; import org.openfast.template.Group; -import java.util.HashMap; -import java.util.HashSet; - public class SimpleMessageFilter implements IFastMessageFilter { //ignore messages that do not have required fields, @@ -37,14 +37,12 @@ public class SimpleMessageFilter implements IFastMessageFilter { //it must have the value not equal to the value in ignoreFieldValues to be accepted by filter private HashMap ignoreValues = new HashMap(); - public SimpleMessageFilter() {}; - - + public SimpleMessageFilter() {} - public SimpleMessageFilter(String filterString) { + public SimpleMessageFilter(String filterString) { HashMap requiredValuesMap = new HashMap(); HashMap ignoreValuesMap = new HashMap(); - if (filterString == null || filterString.equals("")) { + if(filterString == null || "".equals(filterString)) { setRequiredValues(requiredValuesMap); setIgnoreValues(ignoreValuesMap); return; @@ -101,7 +99,7 @@ private boolean checkFieldValues(GroupValue fastMsg) { } Field field = group.getField(fieldName); - if (field.getTypeName().equals("scalar")) { + if("scalar".equals(field.getTypeName())) { String value = fastMsg.getString(field.getName()); String requiredValue = getRequiredValues().get(fieldName); if (!requiredValue.equals(value)) { @@ -120,7 +118,7 @@ private boolean checkFieldValues(GroupValue fastMsg) { } Field field = group.getField(fieldName); - if (field.getTypeName().equals("scalar")) { + if("scalar".equals(field.getTypeName())) { String value = fastMsg.getString(field.getName()); String ignoreValue = getIgnoreValues().get(fieldName); if (ignoreValue.equals(value)) { diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofCheckedStream.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofCheckedStream.java index debe767c..7215a867 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofCheckedStream.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofCheckedStream.java @@ -24,7 +24,7 @@ public class EofCheckedStream extends InputStream { private final Logger logger = LoggerFactory.getLogger(EofCheckedStream.class); - private InputStream is; + private final InputStream is; public EofCheckedStream(InputStream is) { this.is = is; diff --git a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofIOException.java b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofIOException.java index 7c3f02b6..641d48fc 100644 --- a/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofIOException.java +++ b/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/fixup/EofIOException.java @@ -22,8 +22,7 @@ public class EofIOException extends IOException { private static final long serialVersionUID = 1514243615429864025L; public EofIOException() { - super(); - } + } public EofIOException(String message, Throwable cause) { super(message, cause); diff --git a/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/TestFastCodec.java b/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/TestFastCodec.java index cdb08ac6..4aecbc72 100644 --- a/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/TestFastCodec.java +++ b/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/TestFastCodec.java @@ -89,7 +89,7 @@ public void testEncodeMessage() throws Exception public void testDecodeMessage() throws Exception { FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE); - int[] array = new int[]{ + int[] array = { 0xA8, 0xC0, 0x81, 0xB0, 0x32, 0x30, 0x31, 0x32, 0x30, 0x31, 0X30, 0X31, 0x2D, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x2E, 0x33, 0x33, @@ -122,7 +122,7 @@ public void testDecodeFastMessage() throws Exception { SailfishURI dictUri = SailfishURI.unsafeParse(CORE_ALIAS + ":" + dictName); FASTCodec codec = getCodec(dictUri, dictName); - byte[] sourceArray = new byte[] { (byte) 0xab, (byte) 0xc0, (byte) 0x83, 0x42, (byte) 0xd7, 0x32, 0x30, 0x31, 0x36, 0x30, 0x32, 0x31, 0x30, + byte[] sourceArray = { (byte) 0xab, (byte) 0xc0, (byte) 0x83, 0x42, (byte) 0xd7, 0x32, 0x30, 0x31, 0x36, 0x30, 0x32, 0x31, 0x30, 0x2d, 0x30, 0x37, 0x3a, 0x31, 0x30, 0x3a, 0x30, 0x36, 0x2e, 0x31, 0x39, (byte) 0xb3, 0x36, 0x30, 0x36, 0x36, 0x36, (byte) 0xb0, (byte) 0x80, (byte) 0x82, (byte) 0x82, (byte) 0xc0, (byte) 0x87, 0x54, 0x4d, (byte) 0xd0, 0x21, (byte) 0xe9, 0x21, (byte) 0xee}; @@ -170,7 +170,7 @@ public void testDecodeFastMessage() throws Exception { public void testDecodeSeveralMessages() throws Exception { FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE); - int[] array = new int[]{ + int[] array = { 0xA8, 0xC0, 0x81, 0xB0, 0x32, 0x30, 0x31, 0x32, 0x30, 0x31, 0X30, 0X31, 0x2D, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x2E, 0x33, 0x33, @@ -237,13 +237,13 @@ public void testEncodeDecodeMessage() throws Exception public void testRecoveryFromBadMessage() throws Exception { FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE); - int[] array1 = new int[]{ + int[] array1 = { 0xA8, 0xC0, 0x81, 0xB0, 0x32, 0x30, 0x31, 0x32, 0x30, 0x31, 0X30, 0X31, 0x2D, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x2E, 0x33, 0x33, }; - int[] array2 = new int[]{ + int[] array2 = { 0xA8, 0xC0, 0x81, 0xB0, 0x32, 0x30, 0x31, 0x32, 0x30, 0x31, 0X30, 0X31, 0x2D, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x3A, 0x30, 0x31, 0x2E, 0x33, 0x33, diff --git a/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/converter/TestFastConverterPositive.java b/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/converter/TestFastConverterPositive.java index 2a3752f7..4bbf0637 100644 --- a/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/converter/TestFastConverterPositive.java +++ b/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/services/fast/converter/TestFastConverterPositive.java @@ -100,7 +100,7 @@ public void testDecimal(){ @Test public void testByteVector(){ Assert.assertTrue("Fix fastMessage.bv != fastBackConvertMessage.bv", - this.isEqual(fastMessage.getBytes("bv"),fastBackConvertMessage.getBytes("bv"))); + isEqual(fastMessage.getBytes("bv"),fastBackConvertMessage.getBytes("bv"))); } @Test diff --git a/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/util/FastConverterTest.java b/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/util/FastConverterTest.java index a3b1e7fc..a19d3aa2 100644 --- a/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/util/FastConverterTest.java +++ b/BackEnd/Service/service-fast/src/test/java/com/exactpro/sf/util/FastConverterTest.java @@ -93,11 +93,14 @@ protected static Message initMessage(BasicTemplateRegistry registry, String temp } protected boolean isEqual(byte[] firstArray, byte[] secondArray){ - if(firstArray.length!=secondArray.length) - return false; - for(int i=0;i inputData, Message messag admDict = appDict; } - - for (Map.Entry entry : inputData.entrySet()) { - final String tagName = entry.getKey().toString(); - final Object tagValue = entry.getValue(); + for(Entry entry : inputData.entrySet()) { + String tagName = entry.getKey().toString(); + Object tagValue = entry.getValue(); int tagInt = appDict.getFieldTag(tagName); String tagValueString = tagValue.toString(); @@ -208,7 +217,7 @@ static void enrichMessage(Logger logger, HashMap inputData, Message messag if (isComponent(tagValue)) { logger.debug(" -> HashMap have - do it!"); - message = DirtyFixUtil.getFromGroup(appDict, tagName, (List) tagValue, message, msgType, null, null, null); + message = getFromGroup(appDict, tagName, (List)tagValue, message, msgType, null, null, null); } else { if (tagInt == -1) { // if field not found by key, it should be tag number or a reference (HashMap) try { @@ -323,10 +332,9 @@ protected static Message getFromGroup(DataDictionary appDict, String tagName, Li // work with inner hashmap (check for have other hashmaps) for (Object map : tagValue) { - int tempftag = 0; Group localGroup = null; MessageComponent localComponent = null; - tempftag = appDict.getFieldTag(tagName); + int tempftag = appDict.getFieldTag(tagName); GroupInfo inf = null; if (tempftag != -1) { FieldType fieldType = appDict.getFieldTypeEnum(tempftag); @@ -352,17 +360,14 @@ protected static Message getFromGroup(DataDictionary appDict, String tagName, Li for (Object tag : ((HashMap) map).keySet()) { // have hashmap in - Object tempGetObject = null; - int iTagNum = -1; - String iTagName = null; - iTagName = tag.toString(); + String iTagName = tag.toString(); /* * if (iTagName.contains(":")) { iTagName = iTagName.split(":", * 2)[0]; } */ - iTagNum = appDict.getFieldTag(iTagName); - tempGetObject = ((Map) map).get(tag); + int iTagNum = appDict.getFieldTag(iTagName); + Object tempGetObject = ((Map)map).get(tag); if (isComponent(tempGetObject)) { // go recursive newMessage = getFromGroup(appDict, iTagName, (List) tempGetObject, newMessage, mtype, localGroup, diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/ExtendedConvertUtil.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/ExtendedConvertUtil.java index d7c55837..0ba86220 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/ExtendedConvertUtil.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/ExtendedConvertUtil.java @@ -19,7 +19,7 @@ import quickfix.Field; -@ResourceAliases({"ExtendedConvertUtil"}) +@ResourceAliases("ExtendedConvertUtil") public class ExtendedConvertUtil extends ConvertUtil { @Override diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java index 6e5da1cc..736aa7c2 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXMatrixUtil.java @@ -16,6 +16,8 @@ package com.exactpro.sf.actions; import java.text.DecimalFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -27,8 +29,6 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; import com.exactpro.sf.aml.Description; import com.exactpro.sf.aml.script.MetaContainer; @@ -52,6 +52,8 @@ import com.exactpro.sf.util.DateTimeUtility; import quickfix.FixVersions; +import quickfix.Message; +import quickfix.field.MsgSeqNum; /** * Collection of matrix utilities for FIX protocol. @@ -59,10 +61,10 @@ * */ @MatrixUtils -@ResourceAliases({"FIXMatrixUtil"}) +@ResourceAliases("FIXMatrixUtil") public class FIXMatrixUtil extends AbstractCaller { - private static Logger logger = LoggerFactory.getLogger(FIXMatrixUtil.class); + private static final Logger logger = LoggerFactory.getLogger(FIXMatrixUtil.class); private static final String FIX_DATE_FORMAT = "yyyyMMdd"; private static final String FIX_DATE_TIME_FORMAT = FIX_DATE_FORMAT + "-HH:mm:ss"; @@ -318,16 +320,14 @@ public Object ExcludeField() { @UtilityMethod public char ITCHSideToFIXSide(Short side) { - char fixSide; - if(side == 66) { - fixSide = '1'; + if(side == 66) { + return '1'; } else if(side == 83) { - fixSide = '2'; + return '2'; } else { - fixSide = '3'; - } - return fixSide; - } + return '3'; + } + } @Description("Wraps SeqNum to prepare it for writing to a file") @UtilityMethod @@ -481,10 +481,10 @@ protected static MetaContainer convert(MetaContainer sourceNode, IMessage messag /* * Common send method */ - static quickfix.Message send(IActionContext actionContext, - quickfix.Message message) throws Exception { + static Message send(IActionContext actionContext, + Message message) throws Exception { String serviceName = actionContext.getServiceName(); - IInitiatorService service = FIXMatrixUtil.getClient(actionContext); + IInitiatorService service = getClient(actionContext); boolean performance = false; if (service instanceof FIXClient) { @@ -497,10 +497,10 @@ static quickfix.Message send(IActionContext actionContext, logger.info("[{}] {}", serviceName, FixUtil.toString(message, FixUtil.getDictionary(message))); } - if (message.getHeader().isSetField(quickfix.field.MsgSeqNum.FIELD)) { + if (message.getHeader().isSetField(MsgSeqNum.FIELD)) { int seqnum = message.getHeader().getInt( - quickfix.field.MsgSeqNum.FIELD); - ((FIXSession) (service.getSession())).addExpectedSenderNum(seqnum); + MsgSeqNum.FIELD); + ((FIXSession)service.getSession()).addExpectedSenderNum(seqnum); } Thread.sleep(actionContext.getTimeout()); @@ -514,10 +514,10 @@ static quickfix.Message send(IActionContext actionContext, return message; } - static quickfix.Message receive(IActionContext actionContext, quickfix.Message messageFilter) throws Exception + static Message receive(IActionContext actionContext, Message messageFilter) throws Exception { boolean isApp = messageFilter.isApp(); - FIXClient service = FIXMatrixUtil.getClient(actionContext); + FIXClient service = getClient(actionContext); IServiceSettings serviceSettings = service.getSettings(); if(serviceSettings instanceof FIXClientSettings) { FIXClientSettings fixClientSettings = (FIXClientSettings) serviceSettings; @@ -537,9 +537,9 @@ static quickfix.Message receive(IActionContext actionContext, quickfix.Message m } } - static void countMessages(IActionContext actionContext, quickfix.Message message) throws Exception { + static void countMessages(IActionContext actionContext, Message message) throws Exception { boolean isApp = message.isApp(); - FIXClient service = FIXMatrixUtil.getClient(actionContext); + FIXClient service = getClient(actionContext); QFJIMessageConverter converter = service.getConverter(); IMessage newMessageFilter = converter.convert(message, null, Boolean.TRUE);// convert to AML3 format ActionContextWrapper actionContextWrapper = new ActionContextWrapper(actionContext); diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXPacket.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXPacket.java index 0982e5e1..2a7dec99 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXPacket.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FIXPacket.java @@ -15,6 +15,7 @@ ******************************************************************************/ package com.exactpro.sf.actions; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import com.exactpro.sf.scriptrunner.ScriptRunException; @@ -25,16 +26,16 @@ public class FIXPacket { * @param args */ public int RealLen; // count of real byte - private ArrayList elements; + private final ArrayList elements; - private byte[] messInBytes; + private final byte[] messInBytes; public FIXPacket( String mVer, String mType ) { this.elements = new ArrayList(); - this.elements.add( "8=" + mVer ); - this.elements.add( "9=?" ); - this.elements.add( "35=" + mType ); + elements.add("8=" + mVer); + elements.add("9=?"); + elements.add("35=" + mType); this.messInBytes = new byte[65536]; } @@ -52,9 +53,8 @@ public String getItemByIndex(int ind) private int getFIXLength() { int allmesslen = 0; - for (int a = 2; a < this.elements.size(); a++) - { - allmesslen += this.elements.get(a).toString().length(); + for(int a = 2; a < elements.size(); a++) { + allmesslen += elements.get(a).toString().length(); allmesslen += 1; } return allmesslen; @@ -63,15 +63,17 @@ private int getFIXLength() private static String getFIXCheckSum(byte[] messarray, int countbytes) { int chksum = 0; - for (int a = 0; a < countbytes; a++) - chksum += messarray[ a ]; + for(int a = 0; a < countbytes; a++) { + chksum += messarray[a]; + } chksum = chksum % 256; - String spriv; - spriv = "" + chksum; - if ( spriv.length() == 1 ) - spriv = "00" + spriv; - if ( spriv.length() == 2 ) - spriv = "0" + spriv; + String spriv = "" + chksum; + if(spriv.length() == 1) { + spriv = "00" + spriv; + } + if(spriv.length() == 2) { + return "0" + spriv; + } return spriv; } @@ -79,8 +81,9 @@ private static String getFIXCheckSum(byte[] messarray, int countbytes) public String getInText() { String tmpString = ""; - for (int i = 0; i < elements.size(); i++ ) - tmpString += elements.get(i) + "|"; + for(int i = 0; i < elements.size(); i++) { + tmpString += elements.get(i) + "|"; + } return tmpString; } @@ -110,8 +113,8 @@ public void setNewTag( String tagname, String value ) { elements.add( i+1, tagname + "=" + value ); } else*/ - { elements.add( tagname + "=" + value ); } - return; + elements.add(tagname + "=" + value); + return; } } elements.add( tagname + "=" + value ); @@ -149,8 +152,7 @@ public String getTag( String tagname ) public void fillPacketFromString( String stringFIXmessage ) { elements.clear(); - String stringmessage[] = null; - stringmessage = stringFIXmessage.split("\001"); + String[] stringmessage = stringFIXmessage.split("\001"); for (int i = 0; i < stringmessage.length; i++) { elements.add( stringmessage[i] ); @@ -160,8 +162,7 @@ public void fillPacketFromString( String stringFIXmessage ) public void fillPacketFromString2( String stringFIXmessage ) { elements.clear(); - String stringmessage[] = null; - stringmessage = stringFIXmessage.split("!"); + String[] stringmessage = stringFIXmessage.split("!"); for (int i = 0; i < stringmessage.length; i++) { elements.add( stringmessage[i] ); @@ -173,34 +174,33 @@ public byte[] getInBytes() { try { - this.delTag("10"); - this.setTag( "9", "" + getFIXLength()); + delTag("10"); + setTag("9", "" + getFIXLength()); String[] messarray = elements.toArray(new String[elements.size()]); int a = 0; for (int i = 0; i < messarray.length; i++) { - byte[] tmp = messarray[ i ].getBytes("US-ASCII"); + byte[] tmp = messarray[i].getBytes(StandardCharsets.US_ASCII); for (int j = 0; j < messarray[ i ].length(); j++) { - this.messInBytes[ a ] = tmp[ j ]; + messInBytes[a] = tmp[j]; a++; } - this.messInBytes[ a ] = 1; + messInBytes[a] = 1; a++; } - this.setTag("10", getFIXCheckSum( this.messInBytes, a )); - String tmpString; - tmpString = "10=" + getFIXCheckSum( this.messInBytes, a ); + setTag("10", getFIXCheckSum(messInBytes, a)); + String tmpString = "10=" + getFIXCheckSum(messInBytes, a); - byte[] tmp = tmpString.getBytes("US-ASCII"); + byte[] tmp = tmpString.getBytes(StandardCharsets.US_ASCII); for (int j = 0; j < tmpString.length(); j++) { - this.messInBytes[ a ] = tmp[ j ]; + messInBytes[a] = tmp[j]; a++; } - this.messInBytes[ a ] = 1; + messInBytes[a] = 1; this.RealLen = a + 1; } catch (Exception e) @@ -214,52 +214,46 @@ public byte[] getInDirtyBytes( String dirtyLen, String dirtyChkSum ) { try { - this.delTag("10"); - if ( dirtyLen != null ) - { - this.setTag( "9", dirtyLen ); - } else - { - this.setTag( "9", "" + getFIXLength()); - } + delTag("10"); + setTag("9", dirtyLen != null ? dirtyLen : "" + getFIXLength()); String[] messarray = elements.toArray(new String[elements.size()]); int a = 0; for (int i = 0; i < messarray.length; i++) { - byte[] tmp = messarray[ i ].getBytes("US-ASCII"); + byte[] tmp = messarray[i].getBytes(StandardCharsets.US_ASCII); for (int j = 0; j < messarray[ i ].length(); j++) { - this.messInBytes[ a ] = tmp[ j ]; + messInBytes[a] = tmp[j]; a++; } - this.messInBytes[ a ] = 1; + messInBytes[a] = 1; a++; } String tmpString = ""; if ( dirtyChkSum != null ) { // DG: do not set ChkSum(10) to message if DirtyCheckSum=no - if (false == "no".equalsIgnoreCase(dirtyChkSum)) + if(!"no".equalsIgnoreCase(dirtyChkSum)) { - this.setTag("10", dirtyChkSum ); + setTag("10", dirtyChkSum); tmpString = "10=" + dirtyChkSum; } } else { - this.setTag("10", getFIXCheckSum( this.messInBytes, a )); - tmpString = "10=" + getFIXCheckSum( this.messInBytes, a ); + setTag("10", getFIXCheckSum(messInBytes, a)); + tmpString = "10=" + getFIXCheckSum(messInBytes, a); } - byte[] tmp = tmpString.getBytes("US-ASCII"); + byte[] tmp = tmpString.getBytes(StandardCharsets.US_ASCII); for (int j = 0; j < tmpString.length(); j++) { - this.messInBytes[ a ] = tmp[ j ]; + messInBytes[a] = tmp[j]; a++; } - this.messInBytes[ a ] = 1; + messInBytes[a] = 1; this.RealLen = a + 1; } catch (Exception e) diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixCommonActions.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixCommonActions.java index c9614151..f05ebd55 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixCommonActions.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixCommonActions.java @@ -26,19 +26,17 @@ import com.exactpro.sf.services.fix.FixMessageHelper; @MatrixActions -@ResourceAliases({"FixCommonActions"}) +@ResourceAliases("FixCommonActions") public class FixCommonActions extends AbstractCaller { public static final String BEGIN = "begin"; public static final String END = "end"; @Description("Retrieve messages from begin and to end seq numbers from internal storage.") - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @CustomColumns({ @CustomColumn(value = BEGIN, required = true), - @CustomColumn(value = END) + @CustomColumn(END) }) @ActionMethod public void retrieveMessages(IActionContext actionContext, HashMap hashMap) { diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityActions.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityActions.java index a3270d89..9e578d11 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityActions.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityActions.java @@ -17,6 +17,7 @@ import static com.exactpro.sf.services.fix.FixUtil.convertToNumber; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; @@ -56,11 +57,13 @@ import com.exactpro.sf.services.tcpip.TCPIPClient; import com.exactpro.sf.services.tcpip.TCPIPMessageHelper; +import quickfix.Message; + @MatrixActions -@ResourceAliases({"FixConnectivityActions"}) +@ResourceAliases("FixConnectivityActions") public class FixConnectivityActions extends AbstractCaller { - private static Logger logger = LoggerFactory.getLogger(FixConnectivityActions.class); + private static final Logger logger = LoggerFactory.getLogger(FixConnectivityActions.class); private static final Character SOH = '\001'; private static final Character SEP = '|'; @@ -108,7 +111,7 @@ public class FixConnectivityActions extends AbstractCaller private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS"); - private ConnectivityActions connectivityActions; + private final ConnectivityActions connectivityActions; public FixConnectivityActions() { connectivityActions = new ConnectivityActions(); @@ -137,13 +140,13 @@ public HashMap SendSomeCountOrders(IActionContext actionContext, HashMap SendSomeCountOrders(IActionContext actionContext, HashMap SendRawMessage(IActionContext actionContext, HashMap inputData) throws Exception @@ -213,8 +214,9 @@ public HashMap SendRawMessage(IActionContext actionContext, HashMap in tcpipClient.connect(); } - if (!inputData.containsKey("RawMessage")) - throw new Exception("RawMessage column hasn't been specified in your matrix"); + if(!inputData.containsKey("RawMessage")) { + throw new Exception("RawMessage column hasn't been specified in your matrix"); + } String messageString = inputData.get("RawMessage").toString(); @@ -280,18 +282,14 @@ public void CountMessages(IActionContext actionContext, HashMap mapFilter) @CommonColumn(value = Column.ServiceName, required = true), @CommonColumn(value = Column.Timeout, required = true) }) - @CustomColumns({ - @CustomColumn("MsgType") - }) + @CustomColumns(@CustomColumn("MsgType")) @ActionMethod public void CountMessagesWithoutBeginString(IActionContext actionContext, HashMap mapFilter) throws Exception { CountMessages(actionContext, mapFilter); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void Connect(IActionContext actionContext) throws Exception { String serviceName = actionContext.getServiceName(); @@ -306,9 +304,7 @@ public void Connect(IActionContext actionContext) throws Exception { } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void Disconnect(IActionContext actionContext) throws Exception @@ -330,9 +326,7 @@ public void Disconnect(IActionContext actionContext) } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CheckConnect (IActionContext actionContext) { @@ -348,9 +342,7 @@ public void CheckConnect (IActionContext actionContext) throw new EPSCommonException("Service '" + serviceName + "' is not connected."); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void CheckDisconnect (IActionContext actionContext) { @@ -358,7 +350,7 @@ public void CheckDisconnect (IActionContext actionContext) actionContext.getLogger().info("[{}] disconnect.", serviceName); for (ISession session : getAllSessions(getService(actionContext))) { - if (false == session.isClosed()) { + if(!session.isClosed()) { throw new EPSCommonException("Service '" + serviceName + "' is connected."); } } @@ -400,9 +392,7 @@ public void WaitDisconnect(IActionContext actionContext) @CommonColumn(value = Column.ServiceName, required = true), @CommonColumn(Column.Reference) }) - @CustomColumns({ - @CustomColumn(IS_RECEIVE_FIELD) - }) + @CustomColumns(@CustomColumn(IS_RECEIVE_FIELD)) @ActionMethod public int GetSeqNum(IActionContext actionContext, HashMap hashMap) { boolean isReceive = YES.equalsIgnoreCase(String.valueOf(hashMap.get(IS_RECEIVE_FIELD))); @@ -412,9 +402,7 @@ public int GetSeqNum(IActionContext actionContext, HashMap hashMap) { } @Description("Sets sequence number for a specified service to a value.
" + IS_RECEIVE_DESCRIPTION) - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @CustomColumns({ @CustomColumn(value = FixMessageHelper.MSG_SEQ_NUM_FIELD, required = true), @CustomColumn(IS_RECEIVE_FIELD) @@ -431,9 +419,7 @@ public void SetSeqNum(IActionContext actionContext, HashMap hashMap) { } @Description("Adds value to a sequence number of a specified service.
" + IS_RECEIVE_DESCRIPTION) - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @CustomColumns({ @CustomColumn(value = FixMessageHelper.MSG_SEQ_NUM_FIELD, required = true), @CustomColumn(IS_RECEIVE_FIELD) @@ -450,9 +436,7 @@ public void AddSeqNum(IActionContext actionContext, HashMap hashMap) { } @Description("Sets message header for a specified service.
" + IS_RECEIVE_DESCRIPTION) - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @CustomColumns({ @CustomColumn(IS_RECEIVE_FIELD), @CustomColumn(FixMessageHelper.BEGIN_STRING_FIELD), @@ -478,9 +462,7 @@ public void SetHeader(IActionContext actionContext, HashMap hashMap) { } @Description("Sets message trailer for a specified service.
" + IS_RECEIVE_DESCRIPTION) - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @CustomColumns({ @CustomColumn(IS_RECEIVE_FIELD), @CustomColumn(CHECK_SUM_FIELD) @@ -498,15 +480,8 @@ private Map getMap(String fieldName, Map sourceM Object fieldObject = sourceMap.get(fieldName); if(fieldObject == null) { - Map map = defaultMaps.get(serviceName); - - if(map == null) { - map = new HashMap<>(); - } else { - map = new HashMap<>(map); - } - - sourceMap.put(fieldName, fieldObject = map); + Map map = defaultMaps.getOrDefault(serviceName, new HashMap<>()); + sourceMap.put(fieldName, fieldObject = new HashMap<>(map)); } else if(!(fieldObject instanceof Map)) { throw new EPSCommonException(fieldName + " is not a map"); } @@ -518,7 +493,7 @@ private Map extractMap(List fieldNames, Map source Map resultMap = new HashMap<>(); for(String fieldName : fieldNames) { - Object fieldValue = sourceMap.remove(prefix != null ? prefix.concat(fieldName) : fieldName); + Object fieldValue = sourceMap.remove(prefix != null ? prefix + fieldName : fieldName); if(fieldValue != null) { resultMap.put(fieldName, fieldValue); @@ -564,7 +539,7 @@ private static List getAllSessions(IService service) { /* wait for message with tags */ @ActionMethod - public quickfix.Message UNI_WaitMessageWithTags(IActionContext actionContext, HashMap messageFilter) throws Exception + public Message UNI_WaitMessageWithTags(IActionContext actionContext, HashMap messageFilter) throws Exception { ArrayList masWaitingTags = new ArrayList<>(); @@ -609,12 +584,11 @@ public quickfix.Message UNI_WaitMessageWithTags(IActionContext actionContext, Ha if (list != null) { for (; index < list.size(); index++) { - Object message; - message = list.get(index); + Object message = list.get(index); String printString = "

ScriptStatusPassedConditionally PassedFailedCause
Script listExecuted onStatusPassedConditionally PassedFailed
Script listExecuted onStatusPassedConditionally PassedFailed
0 ) + if (!groupTags.isEmpty()) { // remove part before start of Group htmlMsg = htmlMsg.replaceAll( "
", "" ); - if (( htmlMsg.indexOf( groupHeader + "=" )) <= 0 ) continue; + if(htmlMsg.indexOf(groupHeader + "=") <= 0) { + continue; + } htmlMsg = htmlMsg.substring( htmlMsg.indexOf( groupHeader + "="), htmlMsg.length() ); htmlMsg = htmlMsg.substring( htmlMsg.indexOf( "|")+1, htmlMsg.length() ); @@ -700,7 +677,7 @@ public quickfix.Message UNI_WaitMessageWithTags(IActionContext actionContext, Ha { try (IGroupReport groupReport = report .createActionGroup("GROUP: " + passedCountForGroup + " passed from " + groupTags.size(), "#" + i)) { - printString = "
group:" + msgGroups.get(i).toString() + "
"; + printString = "
group:" + msgGroups.get(i) + "
"; groupReport.createMessage(StatusType.PASSED, MessageLevel.INFO, printString); groupReport.createVerification(StatusType.PASSED, "GROUP: " + passedCountForGroup + " passed from " + groupTags.size(), "#" + i, "", null, null); @@ -710,7 +687,7 @@ public quickfix.Message UNI_WaitMessageWithTags(IActionContext actionContext, Ha { try (IGroupReport groupReport = report .createActionGroup("GROUP: " + passedCountForGroup + " passed from " + groupTags.size(), "#" + i)) { - printString = "
group:" + msgGroups.get(i).toString() + printString = "
group:" + msgGroups.get(i) + "
"; groupReport.createMessage(StatusType.FAILED, MessageLevel.INFO, printString); groupReport.createVerification(StatusType.FAILED, @@ -725,7 +702,7 @@ public quickfix.Message UNI_WaitMessageWithTags(IActionContext actionContext, Ha } } // **** WaitingTags **** - if ( masWaitingTags.size() > 0 ) + if (!masWaitingTags.isEmpty()) { int passedCount = 0; for ( int i = 0; i < masWaitingTags.size(); i++ ) diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityUtil.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityUtil.java index f4fd7e8f..9a816a88 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityUtil.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/actions/FixConnectivityUtil.java @@ -67,7 +67,7 @@ public final String Date(String modifyPattern) { public final int addMsgSeqNum(int corr) { messageSeqNumber = messageSeqNumber + corr; - return ( messageSeqNumber ); + return messageSeqNumber; } @Description("Set current MsgSeqNum to specified integer value.
" @@ -78,7 +78,7 @@ public final int addMsgSeqNum(int corr) public final int setMsgSeqNum(int corr) { messageSeqNumber = corr; - return ( messageSeqNumber ); + return messageSeqNumber; } @Description("Formats current date time in UTC time zone modified by pattern into string using yyyyMMdd-HH:mm:ss.SSS format pattern" + DateUtil.MODIFY_HELP + "Usage: #{DateMS(modifyPattern)}") diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/converter/SailfishDictionaryToQuckfixjConverter.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/converter/SailfishDictionaryToQuckfixjConverter.java index a05214fd..28737613 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/converter/SailfishDictionaryToQuckfixjConverter.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/converter/SailfishDictionaryToQuckfixjConverter.java @@ -82,12 +82,13 @@ public class SailfishDictionaryToQuckfixjConverter { private final String NUMBER = "number"; // variable - private Set componentNames; - private Set fieldNames; + private final Set componentNames; + private final Set fieldNames; private IDictionaryStructure sailfishDictionary; - private List accumulateList; - private List accumulateValueList; - private int minor, major; + private final List accumulateList; + private final List accumulateValueList; + private int minor; + private int major; public SailfishDictionaryToQuckfixjConverter() throws ParserConfigurationException, TransformerConfigurationException { @@ -275,7 +276,8 @@ private Document createQuickFixJDictionaryStructure(Document doc, Mode mode) componentNames.clear(); fieldNames.clear(); - Element header, trailer; + Element header; + Element trailer; if (mode != Mode.APP) { header = (Element)createHeader(sailfishDictionary.getMessages().get(FixMessageHelper.HEADER), doc); @@ -465,11 +467,7 @@ private Node createMessageElement(IMessageStructure messageStructure, Document d tempElement.setAttribute(NAME, messageStructure.getName()); tempElement.setAttribute("msgtype", getAttributeValue(messageStructure, FixMessageHelper.MESSAGE_TYPE_ATTR_NAME).toString()); - if(StructureUtils.getAttributeValue(messageStructure, IS_ADMIN)) { - tempElement.setAttribute("msgcat", "admin"); - } else { - tempElement.setAttribute("msgcat", "app"); - } + tempElement.setAttribute("msgcat", getAttributeValue(messageStructure, IS_ADMIN) ? "admin" : "app"); boolean isEmpty = true; for(IFieldStructure field : messageStructure.getFields().values()) { @@ -616,6 +614,6 @@ private Node createGroupElement(IFieldStructure group, Document doc, boolean add } private enum Mode { - ALL, APP, ADMIN; + ALL, APP, ADMIN } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/FIXDictionaryValidator.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/FIXDictionaryValidator.java index 51e637fd..ce44f809 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/FIXDictionaryValidator.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/FIXDictionaryValidator.java @@ -147,7 +147,6 @@ public class FIXDictionaryValidator extends AbstractDictionaryValidator { } public FIXDictionaryValidator() { - super(); } public FIXDictionaryValidator(IDictionaryValidator parentValidator) { @@ -257,7 +256,7 @@ private void checkMessageTypes(List errors, IDictiona for(IMessageStructure message : dictionary.getMessages().values()) { String entity_type = getAttributeValue(message, ATTRIBUTE_ENTITY_TYPE); - if(entity_type != null && entity_type.equals(MESSAGE_ENTITY)) { + if(MESSAGE_ENTITY.equals(entity_type)) { Object messageTypeAttribute = getAttributeValue(message, MESSAGE_TYPE_ATTR_NAME); if(messageTypeAttribute != null) { @@ -380,8 +379,8 @@ private void checkJavaType(List errors, IMessageStruc } private static class FieldHolder { - private String messageName; - private String fieldName; + private final String messageName; + private final String fieldName; public FieldHolder(String messageName, String fieldName) { this.messageName = messageName; diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/MessageEntityValidator.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/MessageEntityValidator.java index 917918f3..399472dc 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/MessageEntityValidator.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/dictionary/impl/MessageEntityValidator.java @@ -63,11 +63,9 @@ private void checkUniqueness(List errors, IMessageStr String.format("Field [%s] in [%s] message duplicated in ", fieldName, message.getName())); for (Iterator i = duplicates.get(fieldName).iterator(); i.hasNext();) { - String name = i.next(); + error.append(String.format("[%s]", i.next())); if (i.hasNext()) { - error.append(String.format("[%s], ", name)); - } else { - error.append(String.format("[%s]", name)); + error.append(", "); } } errors.add(new DictionaryValidationError(message.getName(), fieldName, error.toString(), diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/factory/FixMessageFactory.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/factory/FixMessageFactory.java index 05cc110f..27840b92 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/factory/FixMessageFactory.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/configuration/factory/FixMessageFactory.java @@ -23,10 +23,7 @@ import com.google.common.collect.ImmutableSet; public class FixMessageFactory extends AbstractMessageFactory { - public final static Set UNCHECKED_FIELDS; - - static { - UNCHECKED_FIELDS = ImmutableSet.of( + public static final Set UNCHECKED_FIELDS = ImmutableSet.of( "header", "BeginString", "BodyLength", @@ -43,8 +40,7 @@ public class FixMessageFactory extends AbstractMessageFactory { "SenderSubID", "PossResend", "trailer" - ); - } + ); @Override public IHumanMessage createHumanMessage(String name) { diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXApplication.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXApplication.java index e3186771..a327eb7b 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXApplication.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXApplication.java @@ -45,6 +45,7 @@ import com.exactpro.sf.services.ISession; import com.exactpro.sf.services.MessageHelper; import com.exactpro.sf.services.ServiceEvent; +import com.exactpro.sf.services.ServiceEvent.Type; import com.exactpro.sf.services.ServiceEventFactory; import com.exactpro.sf.services.ServiceHandlerException; import com.exactpro.sf.services.ServiceHandlerRoute; @@ -69,12 +70,13 @@ import quickfix.field.EndSeqNo; import quickfix.field.MsgSeqNum; import quickfix.field.MsgType; +import quickfix.field.NextExpectedMsgSeqNum; import quickfix.field.ResetSeqNumFlag; import quickfix.field.Text; public class FIXApplication implements FIXClientApplication { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); public static final String ENCRYPT_PASSWORD = "EncryptPassword"; public static final String ADD_NEXT_EXPECTED_SEQ_NUM = "AddNextExpectedMsgSeqNum"; @@ -107,12 +109,12 @@ public class FIXApplication implements FIXClientApplication { private Integer seqNumSender; private Integer seqNumTarget; - private boolean incorrectSenderMsgSeqNum = false; // update seqnum on logon - private boolean incorrectTargetMsgSeqNum = false; // update seqnum on logon + private boolean incorrectSenderMsgSeqNum; // update seqnum on logon + private boolean incorrectTargetMsgSeqNum; // update seqnum on logon - private boolean useDefaultApplVerID = false; + private boolean useDefaultApplVerID; - private boolean isPerformance = false; + private boolean isPerformance; private boolean autorelogin = true; @@ -136,16 +138,16 @@ public void init(IServiceContext serviceContext, ApplicationContext applicationC this.storage = serviceContext.getMessageStorage(); this.serviceInfo = serviceContext.lookupService(serviceName); this.settings = this.applicationContext.getSessionSettings(); - if (this.settings.isSetting(SEND_APP_REJECT)) { + if(settings.isSetting(SEND_APP_REJECT)) { try { - this.sendAppReject = this.settings.getBool(SEND_APP_REJECT); + this.sendAppReject = settings.getBool(SEND_APP_REJECT); } catch (Exception e) { logger.error(e.getMessage(), e); } } - if (this.settings.isSetting(SEND_ADMIN_REJECT)) { + if(settings.isSetting(SEND_ADMIN_REJECT)) { try { - this.sendAdminReject = this.settings.getBool(SEND_ADMIN_REJECT); + this.sendAdminReject = settings.getBool(SEND_ADMIN_REJECT); } catch (Exception e) { logger.error(e.getMessage(), e); } @@ -165,7 +167,7 @@ public void init(IServiceContext serviceContext, ApplicationContext applicationC this.useDefaultApplVerID = fixSettings.isUseDefaultApplVerID(); this.isPerformance = fixSettings.isPerformanceMode(); - this.latencyCalculator = new FIXLatencyCalculator(this.messageHelper); + this.latencyCalculator = new FIXLatencyCalculator(messageHelper); } @Override @@ -243,15 +245,17 @@ else if (text.startsWith("Error ! Expecting : ")) targSeq = message.getHeader().getInt(MsgSeqNum.FIELD); // TODO: +1 ? } - if (seqNum != -1) - this.seqNumSender = new Integer(seqNum); + if(seqNum != -1) { + this.seqNumSender = new Integer(seqNum); + } - if (targSeq != -1) - this.seqNumTarget = new Integer(targSeq); + if(targSeq != -1) { + this.seqNumTarget = new Integer(targSeq); + } } if (serviceMonitor != null) { ServiceEvent event = ServiceEventFactory.createEventInfo(serviceName, - ServiceEvent.Type.INFO, textMessage, null); + Type.INFO, textMessage, null); serviceMonitor.onEvent(event); } } else if (MsgType.RESEND_REQUEST.equals(msgType)) { @@ -301,12 +305,8 @@ public void fromApp(Message message, SessionID sessionID) public void onMessageRejected(Message message, SessionID sessionID) { logger.debug("onMessageRejected: {}", message); try { - IMessage iMsg = convert(message, sessionID.getTargetCompID(), this.serviceStringName, message.isAdmin(), false, true); - if (message.getException() != null) { - iMsg.getMetaData().setRejectReason(message.getException().getMessage()); - } else { - iMsg.getMetaData().setRejectReason("Unknown"); - } + IMessage iMsg = convert(message, sessionID.getTargetCompID(), serviceStringName, message.isAdmin(), false, true); + iMsg.getMetaData().setRejectReason(message.getException() != null ? message.getException().getMessage() : "Unknown"); if (!isPerformance) { storeMessage(sessionID, iMsg); @@ -326,23 +326,23 @@ public void onCreate(SessionID sessionID) Session session = Session.lookupSession(sessionID); try { - if (this.seqNumSender != null) { - session.setNextSenderMsgSeqNum(this.seqNumSender); + if(seqNumSender != null) { + session.setNextSenderMsgSeqNum(seqNumSender); logger.info("Set session.setNextSenderMsgSeqNum = {}", seqNumSender); } } catch (IOException e) { logger.error("Could not set specified both seqNumSender={} for the session {}.", - this.seqNumSender, iSession.getName(), e); + seqNumSender, iSession.getName(), e); } try { - if (this.seqNumTarget != null) { - session.setNextTargetMsgSeqNum(this.seqNumTarget); + if(seqNumTarget != null) { + session.setNextTargetMsgSeqNum(seqNumTarget); logger.info("Set session.setNextTargetMsgSeqNum = {}", seqNumTarget); } } catch (IOException e) { logger.error("Could not set specified both seqNumTarget={} for the session {}.", - this.seqNumTarget, iSession.getName(), e); + seqNumTarget, iSession.getName(), e); } if (handler == null) { @@ -374,7 +374,7 @@ public void onLogout(SessionID sessionID) handler.exceptionCaught(iSession, e); logger.error("onLogout: can not do handler.sessionClosed({}) ", iSession, e); } - if (!this.autorelogin) + if(!autorelogin) { Session session = Session.lookupSession(sessionID); session.logout("Logon After Server Logout"); @@ -402,7 +402,7 @@ public void toAdmin(Message message, SessionID sessionID) throws DoNotSend { String encryptStr = settings.getSessionProperties(sessionID).get(ENCRYPT_PASSWORD).toString(); String password = null; String newPassword = null; - if(encryptStr.equalsIgnoreCase("Y")) { + if("Y".equalsIgnoreCase(encryptStr)) { PublicKey publicKey = null; ObjectInputStream inputStream = null; try { @@ -415,12 +415,10 @@ public void toAdmin(Message message, SessionID sessionID) throws DoNotSend { } Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); - byte[] encryptedPasswordBytes = null; - encryptedPasswordBytes = cipher.doFinal(settingsPassword.getBytes()); + byte[] encryptedPasswordBytes = cipher.doFinal(settingsPassword.getBytes()); password = new String(Base64.encodeBase64(encryptedPasswordBytes)); if(settingsNewPassword != null) { - byte[] encryptedNewPasswordBytes = null; - encryptedNewPasswordBytes = cipher.doFinal(settingsNewPassword.getBytes()); + byte[] encryptedNewPasswordBytes = cipher.doFinal(settingsNewPassword.getBytes()); newPassword = new String(Base64.encodeBase64(encryptedNewPasswordBytes)); } } else { @@ -444,31 +442,38 @@ public void toAdmin(Message message, SessionID sessionID) throws DoNotSend { String addNextExpectedSeqNum = (String) settings.getSessionProperties(sessionID).get(ADD_NEXT_EXPECTED_SEQ_NUM); int nextExpectedSeqNum = Session.lookupSession(sessionID).getSessionState().getNextTargetMsgSeqNum(); - if (userName != null) - message.setString(quickfix.field.Username.FIELD, userName); - if (password != null) - message.setString(quickfix.field.Password.FIELD, password); - if (newPassword != null) - message.setString(quickfix.field.NewPassword.FIELD, newPassword); - if (defaultCstmApplVerID != null) + if(userName != null) { + message.setString(quickfix.field.Username.FIELD, userName); + } + if(password != null) { + message.setString(quickfix.field.Password.FIELD, password); + } + if(newPassword != null) { + message.setString(quickfix.field.NewPassword.FIELD, newPassword); + } + if(defaultCstmApplVerID != null) { message.setString(1408, defaultCstmApplVerID); - if (extExecInst != null) + } + if(extExecInst != null) { message.setString(8718, extExecInst); + } if (resetSeqNumFlag != null) { String sResetSeqNumFlag = ((String)resetSeqNumFlag).toLowerCase(); - if (sResetSeqNumFlag.equals("true") || sResetSeqNumFlag.equals("y")) - message.setBoolean(ResetSeqNumFlag.FIELD, true); - if (sResetSeqNumFlag.equals("false") || sResetSeqNumFlag.equals("n")) - message.setBoolean(ResetSeqNumFlag.FIELD, false); - } - if(addNextExpectedSeqNum.equalsIgnoreCase("Y")) { - message.setInt(quickfix.field.NextExpectedMsgSeqNum.FIELD, nextExpectedSeqNum); + if("true".equals(sResetSeqNumFlag) || "y".equals(sResetSeqNumFlag)) { + message.setBoolean(ResetSeqNumFlag.FIELD, true); + } + if("false".equals(sResetSeqNumFlag) || "n".equals(sResetSeqNumFlag)) { + message.setBoolean(ResetSeqNumFlag.FIELD, false); + } + } + if("Y".equalsIgnoreCase(addNextExpectedSeqNum)) { + message.setInt(NextExpectedMsgSeqNum.FIELD, nextExpectedSeqNum); } - if (this.incorrectSenderMsgSeqNum) + if(incorrectSenderMsgSeqNum) { - message.getHeader().setInt(MsgSeqNum.FIELD, this.seqNumSender); + message.getHeader().setInt(MsgSeqNum.FIELD, seqNumSender); try { logger.info("set next sender MsgSeqNum after logout to: {}", seqNumSender); @@ -479,7 +484,7 @@ public void toAdmin(Message message, SessionID sessionID) throws DoNotSend { } this.incorrectSenderMsgSeqNum = false; } - if (this.incorrectTargetMsgSeqNum) + if(incorrectTargetMsgSeqNum) { try { @@ -525,7 +530,7 @@ public void toAdmin(Message message, SessionID sessionID) throws DoNotSend { } if (serviceMonitor != null) { ServiceEvent event = ServiceEventFactory.createEventInfo(serviceName, - ServiceEvent.Type.INFO, textMessage, null); + Type.INFO, textMessage, null); serviceMonitor.onEvent(event); } } @@ -541,7 +546,7 @@ public void toApp(Message message, SessionID sessionID) throws DoNotSend { String type = getMessageType(message); - if (this.sendAppReject == false) { + if(sendAppReject == false) { if (MsgType.REJECT.equals(type)) { logger.info("Block appliction sending Reject message : {}", message); @@ -570,14 +575,14 @@ public ServiceInfo getServiceInfo() { public void addSessionId(SessionID sessionID, ISession iSession) { logger.info("add session: {} -> {} = {}", sessionID.getSenderCompID(), sessionID.getTargetCompID(), iSession.getName()); - this.sessionMap.put(sessionID, iSession); + sessionMap.put(sessionID, iSession); Session session = Session.lookupSession(sessionID); session.logon(); } @Override public List getSessions() { - return new ArrayList<>(this.sessionMap.values()); + return new ArrayList<>(sessionMap.values()); } public Integer getSeqNumSender() { @@ -607,7 +612,7 @@ public boolean isAutorelogin() { @Override public void startLogging() { if (logConfigurator != null) { - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } } @@ -615,7 +620,7 @@ public void startLogging() { @Override public void stopLogging() { if (logConfigurator != null) { - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } } @@ -667,8 +672,8 @@ private IMessage convert(Message message, String from, String to, boolean isAdmi String messageData = message.getMessageData(); byte[] rawMessage = messageData != null ? messageData.getBytes(CharsetSupport.getCharsetInstance()) : message.toString().getBytes(CharsetSupport.getCharsetInstance()); IMessage msg = isRejected - ? this.converter.convertDirty(message, verifyTags, false, false, true) - : this.converter.convert(message, verifyTags, null); + ? converter.convertDirty(message, verifyTags, false, false, true) + : converter.convert(message, verifyTags, null); MsgMetaData meta = msg.getMetaData(); meta.setFromService(from); diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClient.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClient.java index 6830ff31..0c726552 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClient.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClient.java @@ -28,8 +28,6 @@ import java.util.Objects; import java.util.TimeZone; -import com.exactpro.sf.common.messages.IMessageFactory; -import com.exactpro.sf.configuration.IDictionaryManager; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -40,17 +38,18 @@ import com.exactpro.sf.aml.script.actions.WaitAction; import com.exactpro.sf.common.messages.IMessage; +import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.messages.structures.IMessageStructure; import com.exactpro.sf.common.services.ServiceInfo; import com.exactpro.sf.common.services.ServiceName; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.configuration.IDataManager; +import com.exactpro.sf.configuration.IDictionaryManager; import com.exactpro.sf.configuration.ILoggingConfigurator; import com.exactpro.sf.configuration.suri.SailfishURI; import com.exactpro.sf.configuration.workspace.FolderType; import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher; -import com.exactpro.sf.configuration.workspace.WorkspaceStructureException; import com.exactpro.sf.scriptrunner.actionmanager.actioncontext.IActionContext; import com.exactpro.sf.services.IInitiatorService; import com.exactpro.sf.services.IServiceContext; @@ -96,7 +95,7 @@ */ public class FIXClient implements IInitiatorService { - protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + protected final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); protected volatile ServiceStatus curStatus; protected IServiceMonitor monitor; @@ -123,13 +122,13 @@ public class FIXClient implements IInitiatorService { protected ServiceInfo serviceInfo; private IMessageStorage msgStorage; - private MessageFactory messageFactory = null; + private MessageFactory messageFactory; protected FixDataDictionaryProvider dictionaryProvider; protected ILoggingConfigurator logConfigurator; - private boolean isPerformance = false; + private boolean isPerformance; protected ITaskExecutor taskExecutor; protected IWorkspaceDispatcher workspaceDispatcher; @@ -154,14 +153,14 @@ public FIXClient() public void dispose() { logger.info("dispose service {}", this); - this.changeStatus(ServiceStatus.DISPOSING, "Service disposing.", null ); - this.closeResources(); - this.changeStatus(ServiceStatus.DISPOSED, "Service disposed.", null ); + changeStatus(ServiceStatus.DISPOSING, "Service disposing.", null); + closeResources(); + changeStatus(ServiceStatus.DISPOSED, "Service disposed.", null); } private void closeResources() { try { - FIXSession currentSession = this.session; + FIXSession currentSession = session; Session qfjSession = null; if (currentSession != null) { if(!currentSession.isClosed()){ @@ -170,8 +169,8 @@ private void closeResources() { } } - if (this.initiator != null) { - this.initiator.stop(); + if(initiator != null) { + initiator.stop(); } if (qfjSession != null) { @@ -185,16 +184,16 @@ private void closeResources() { } } - if (this.application != null) { + if(application != null) { application.stopLogging(); } } catch (Throwable e) { - this.changeStatus(ServiceStatus.ERROR, "Service failed upon closing the resources: " + e.getMessage(), e ); + changeStatus(ServiceStatus.ERROR, "Service failed upon closing the resources: " + e.getMessage(), e); logger.error("Service failed upon closing the resources", e); } finally { if(logConfigurator != null) { - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } } @@ -203,25 +202,25 @@ private void closeResources() { @Override public void init( - final IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName serviceName) { + IServiceContext serviceContext, + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName serviceName) { logger.info("init Service {}", this); try { - this.changeStatus(ServiceStatus.INITIALIZING, "Service initializing", null); + changeStatus(ServiceStatus.INITIALIZING, "Service initializing", null); baseInit(serviceContext, serviceMonitor, handler, settings, serviceName); initFixApplication(); - this.changeStatus(ServiceStatus.INITIALIZED, "Service initialized", null); + changeStatus(ServiceStatus.INITIALIZED, "Service initialized", null); } catch (Exception e) { - this.changeStatus(ServiceStatus.ERROR, "Service initializing error", e); + changeStatus(ServiceStatus.ERROR, "Service initializing error", e); throw new ServiceException(e); } @@ -229,69 +228,78 @@ public void init( } - protected void configureSessionSettings(final FIXClientApplication application, SessionID sessionID, final SessionSettings sessionSettings, final ServiceName serviceName, IDataManager dataManager) + protected void configureSessionSettings(FIXClientApplication application, SessionID sessionID, SessionSettings sessionSettings, ServiceName serviceName, IDataManager dataManager) throws IOException { - configureCommonSettings(this.fixSettings, sessionID, sessionSettings, serviceName); + configureCommonSettings(fixSettings, sessionID, sessionSettings, serviceName); - if ( this.serviceName != null) - sessionSettings.setString( sessionID, "SessionName", this.serviceName.toString() ); - else - throw new ServiceException("Service name is not set"); + if(this.serviceName != null) { + sessionSettings.setString(sessionID, "SessionName", this.serviceName.toString()); + } else { + throw new ServiceException("Service name is not set"); + } sessionSettings.setString( sessionID, SessionFactory.SETTING_CONNECTION_TYPE, "initiator" ); - if ( this.fixSettings.getUsername() != null && !this.fixSettings.getUsername().equals("") ) - sessionSettings.setString( sessionID, "Username", this.fixSettings.getUsername() ); + if(fixSettings.getUsername() != null && !"".equals(fixSettings.getUsername())) { + sessionSettings.setString(sessionID, "Username", fixSettings.getUsername()); + } - if ( this.fixSettings.getPassword() != null && !this.fixSettings.getPassword().equals("") ) - sessionSettings.setString( sessionID, "Password", this.fixSettings.getPassword() ); + if(fixSettings.getPassword() != null && !"".equals(fixSettings.getPassword())) { + sessionSettings.setString(sessionID, "Password", fixSettings.getPassword()); + } - if ( this.fixSettings.getNewPassword() != null && !this.fixSettings.getNewPassword().equals("")) - sessionSettings.setString( sessionID, "NewPassword", this.fixSettings.getNewPassword() ); + if(fixSettings.getNewPassword() != null && !"".equals(fixSettings.getNewPassword())) { + sessionSettings.setString(sessionID, "NewPassword", fixSettings.getNewPassword()); + } - if ( this.fixSettings.getEncryptionKeyFilePath() != null && !this.fixSettings.getEncryptionKeyFilePath().equals("")) - sessionSettings.setString( sessionID, "EncryptionKeyFilePath", this.fixSettings.getEncryptionKeyFilePath() ); + if(fixSettings.getEncryptionKeyFilePath() != null && !"".equals(fixSettings.getEncryptionKeyFilePath())) { + sessionSettings.setString(sessionID, "EncryptionKeyFilePath", fixSettings.getEncryptionKeyFilePath()); + } - if ( this.fixSettings.getDefaultCstmApplVerID() != null && !this.fixSettings.getDefaultCstmApplVerID().equals("")) - sessionSettings.setString( sessionID, FIXApplication.DefaultCstmApplVerID, this.fixSettings.getDefaultCstmApplVerID() ); + if(fixSettings.getDefaultCstmApplVerID() != null && !"".equals(fixSettings.getDefaultCstmApplVerID())) { + sessionSettings.setString(sessionID, FIXApplication.DefaultCstmApplVerID, fixSettings.getDefaultCstmApplVerID()); + } - if ( this.fixSettings.getExtExecInst() != null && !this.fixSettings.getExtExecInst().equals("")) - sessionSettings.setString( sessionID, "ExtExecInst", this.fixSettings.getExtExecInst() ); + if(fixSettings.getExtExecInst() != null && !"".equals(fixSettings.getExtExecInst())) { + sessionSettings.setString(sessionID, "ExtExecInst", fixSettings.getExtExecInst()); + } - if( this.fixSettings.isUseDefaultApplVerID() ){ - if ( this.fixSettings.getDefaultApplVerID() != null && !this.fixSettings.getDefaultApplVerID().equals("") ) - sessionSettings.setString( sessionID, Session.SETTING_DEFAULT_APPL_VER_ID, this.fixSettings.getDefaultApplVerID() ); - else - throw new ServiceException("'"+Session.SETTING_DEFAULT_APPL_VER_ID+"' parameter is not set in " + serviceName); + if(fixSettings.isUseDefaultApplVerID()) { + if(fixSettings.getDefaultApplVerID() != null && !"".equals(fixSettings.getDefaultApplVerID())) { + sessionSettings.setString(sessionID, Session.SETTING_DEFAULT_APPL_VER_ID, fixSettings.getDefaultApplVerID()); + } else { + throw new ServiceException("'" + Session.SETTING_DEFAULT_APPL_VER_ID + "' parameter is not set in " + serviceName); + } } - if ( this.fixSettings.getSocketConnectHost() != null && !this.fixSettings.getSocketConnectHost().equals("") ) - sessionSettings.setString( sessionID, Initiator.SETTING_SOCKET_CONNECT_HOST, this.fixSettings.getSocketConnectHost() ); - else - throw new ServiceException("'"+Initiator.SETTING_SOCKET_CONNECT_HOST+"' parameter is not set in " + serviceName); + if(fixSettings.getSocketConnectHost() != null && !"".equals(fixSettings.getSocketConnectHost())) { + sessionSettings.setString(sessionID, Initiator.SETTING_SOCKET_CONNECT_HOST, fixSettings.getSocketConnectHost()); + } else { + throw new ServiceException("'" + Initiator.SETTING_SOCKET_CONNECT_HOST + "' parameter is not set in " + serviceName); + } - sessionSettings.setLong( sessionID, Initiator.SETTING_SOCKET_CONNECT_PORT, this.fixSettings.getSocketConnectPort() ); - sessionSettings.setLong( sessionID, Session.SETTING_HEARTBTINT, this.fixSettings.getHeartBtInt() ); - sessionSettings.setLong( sessionID, Session.SETTING_LOGON_TIMEOUT, this.fixSettings.getLogonTimeout() ); - sessionSettings.setLong( sessionID, Session.SETTING_LOGOUT_TIMEOUT, this.fixSettings.getLogoutTimeout() ); - sessionSettings.setLong(sessionID, Initiator.SETTING_RECONNECT_INTERVAL, this.fixSettings.getReconnectInterval()); + sessionSettings.setLong(sessionID, Initiator.SETTING_SOCKET_CONNECT_PORT, fixSettings.getSocketConnectPort()); + sessionSettings.setLong(sessionID, Session.SETTING_HEARTBTINT, fixSettings.getHeartBtInt()); + sessionSettings.setLong(sessionID, Session.SETTING_LOGON_TIMEOUT, fixSettings.getLogonTimeout()); + sessionSettings.setLong(sessionID, Session.SETTING_LOGOUT_TIMEOUT, fixSettings.getLogoutTimeout()); + sessionSettings.setLong(sessionID, Initiator.SETTING_RECONNECT_INTERVAL, fixSettings.getReconnectInterval()); - if ( this.fixSettings.getStartDate() != null && !this.fixSettings.getStartDate().equals("") ) { - sessionSettings.setString(sessionID, Session.SETTING_START_DAY, this.fixSettings.getStartDate()); + if(fixSettings.getStartDate() != null && !"".equals(fixSettings.getStartDate())) { + sessionSettings.setString(sessionID, Session.SETTING_START_DAY, fixSettings.getStartDate()); } - if ( this.fixSettings.getEndDate() != null && !this.fixSettings.getEndDate().equals("") ) { - sessionSettings.setString(sessionID, Session.SETTING_END_DAY, this.fixSettings.getEndDate()); + if(fixSettings.getEndDate() != null && !"".equals(fixSettings.getEndDate())) { + sessionSettings.setString(sessionID, Session.SETTING_END_DAY, fixSettings.getEndDate()); } - sessionSettings.setString(sessionID, ResetSeqNumFlag, this.fixSettings.getResetSeqNumFlag()); // Determines if sequence numbers should be reset when recieving a logon request. Acceptors only. + sessionSettings.setString(sessionID, ResetSeqNumFlag, fixSettings.getResetSeqNumFlag()); // Determines if sequence numbers should be reset when recieving a logon request. Acceptors only. - sessionSettings.setBool(sessionID, Session.IGNORE_ABSENCE_OF_141_TAG, this.fixSettings.isIgnoreAbsenceOf141tag()); - sessionSettings.setBool( sessionID, Session.SETTING_REQUIRES_ORIG_SENDING_TIME, this.fixSettings.isRequiresOrigSendingTime()); + sessionSettings.setBool(sessionID, Session.IGNORE_ABSENCE_OF_141_TAG, fixSettings.isIgnoreAbsenceOf141tag()); + sessionSettings.setBool(sessionID, Session.SETTING_REQUIRES_ORIG_SENDING_TIME, fixSettings.isRequiresOrigSendingTime()); - sessionSettings.setBool( sessionID, FIXApplication.ENCRYPT_PASSWORD, this.fixSettings.isEncryptPassword()); - sessionSettings.setBool( sessionID, FIXApplication.ADD_NEXT_EXPECTED_SEQ_NUM, this.fixSettings.isAddNextExpectedMsgSeqNum()); + sessionSettings.setBool(sessionID, FIXApplication.ENCRYPT_PASSWORD, fixSettings.isEncryptPassword()); + sessionSettings.setBool(sessionID, FIXApplication.ADD_NEXT_EXPECTED_SEQ_NUM, fixSettings.isAddNextExpectedMsgSeqNum()); sessionSettings.setBool(sessionID, Session.SETTING_REJECT_MESSAGE_ON_UNHANDLED_EXCEPTION, true); @@ -358,11 +366,11 @@ protected void configureCommonSettings(FIXCommonSettings commonSettings, Session } protected void baseInit( - final IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings serviceSettings, - final ServiceName serviceName) { + IServiceContext serviceContext, + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings serviceSettings, + ServiceName serviceName) { this.serviceName = serviceName; this.serviceContext = Objects.requireNonNull(serviceContext, "'Service context' parameter"); @@ -376,7 +384,7 @@ protected void baseInit( this.msgStorage = Objects.requireNonNull(this.serviceContext.getMessageStorage(), "'Message storage' parameter"); this.serviceInfo = serviceContext.lookupService(serviceName); - if (this.serviceInfo == null) { + if(serviceInfo == null) { logger.debug("A service named {} was not found.", serviceName); } this.handler = Objects.requireNonNull(handler, "'Service handler' parameter"); @@ -397,31 +405,31 @@ protected void baseInit( false, commonSettings.isOrderingFields()); this.messageHelper = new FixMessageHelper(); - this.messageHelper.init(messageFactory, dictionary); + messageHelper.init(messageFactory, dictionary); } protected void initFixApplication() throws IOException { this.messageFactory = new CommonMessageFactory(dictionaryProvider); - if(this.fixSettings.isPerformanceMode()) { + if(fixSettings.isPerformanceMode()) { this.isPerformance = true; } - SessionID sessionID = new SessionID( this.fixSettings.getBeginString(), - this.fixSettings.getSenderCompID(), this.fixSettings.getTargetCompID(), serviceName.toString().replace(':', '-')); + SessionID sessionID = new SessionID(fixSettings.getBeginString(), + fixSettings.getSenderCompID(), fixSettings.getTargetCompID(), serviceName.toString().replace(':', '-')); - this.messagesLogFile = workspaceDispatcher.createFolder(FolderType.LOGS, this.logConfigurator.getLogsPath(this.serviceName)).getCanonicalPath(); - this.settings.setString( sessionID, FileLogFactory.SETTING_FILE_LOG_PATH, this.messagesLogFile); + this.messagesLogFile = workspaceDispatcher.createFolder(FolderType.LOGS, logConfigurator.getLogsPath(serviceName)).getCanonicalPath(); + settings.setString(sessionID, FileLogFactory.SETTING_FILE_LOG_PATH, messagesLogFile); - this.settings.setBool( sessionID, Session.SETTING_USE_SENDER_DEFAULT_APPL_VER_ID_AS_INITIAL_TARGET, true); - this.settings.setBool(sessionID, Session.SETTING_VALIDATE_SEQUENCE_NUMBERS, this.fixSettings.isValidateSequenceNumbers()); + settings.setBool(sessionID, Session.SETTING_USE_SENDER_DEFAULT_APPL_VER_ID_AS_INITIAL_TARGET, true); + settings.setBool(sessionID, Session.SETTING_VALIDATE_SEQUENCE_NUMBERS, fixSettings.isValidateSequenceNumbers()); - configureSessionSettings(this.application, sessionID, this.settings, serviceName, this.serviceContext.getDataManager()); + configureSessionSettings(application, sessionID, settings, serviceName, serviceContext.getDataManager()); this.application = createFixApplication(); - this.application.init(serviceContext, - new ApplicationContext(this.monitor, this.handler, this.fixSettings, this.settings, this.messageHelper, this.converter, - this.dictionaryProvider, this::connectionProblem), + application.init(serviceContext, + new ApplicationContext(monitor, handler, fixSettings, settings, messageHelper, converter, + dictionaryProvider, this::connectionProblem), serviceName); } @@ -444,47 +452,42 @@ protected void setSenderTargetIDs(SessionID sessionID, FIXCommonSettings commonS @Override public void start() { - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); application.startLogging(); logger.info("start service {}", this); try{ - this.changeStatus(ServiceStatus.STARTING, "Service starting", null); + changeStatus(ServiceStatus.STARTING, "Service starting", null); - MessageStoreFactory messageStoreFactory = new FileStoreFactory(this.settings); + MessageStoreFactory messageStoreFactory = new FileStoreFactory(settings); - LogFactory logFactory = new FIXLogFactory(new FileLogFactory(this.settings), this.fixSettings.isLogHeartbeats(), this, monitor, this.logger); + LogFactory logFactory = new FIXLogFactory(new FileLogFactory(settings), fixSettings.isLogHeartbeats(), this, monitor, logger); FixSessionFactory sessionFactory = new FixSessionFactory(application, messageStoreFactory, logFactory, messageFactory, dictionaryProvider); - this.initiator = new SocketInitiator(sessionFactory, this.settings, SessionConnector.DEFAULT_QUEUE_CAPACITY, + this.initiator = new SocketInitiator(sessionFactory, settings, SessionConnector.DEFAULT_QUEUE_CAPACITY, taskExecutor.getThreadPool()); - if (this.initiator == null) { + if(initiator == null) { throw new ServiceException("'initiator' is not set"); } - if (this.fixSettings.isDoLogonOnStart()) { + if(fixSettings.isDoLogonOnStart()) { logon(); } - this.changeStatus(ServiceStatus.STARTED, "Service started", null); + changeStatus(ServiceStatus.STARTED, "Service started", null); } catch ( QFJException e ) { logger.error("Service {} not started", this, e); - String cause = null; - - if ( e.getCause() != null ) - cause = e.getCause().getMessage(); - else - cause = e.getMessage(); + String cause = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); - this.changeStatus(ServiceStatus.ERROR, cause, e, true); + changeStatus(ServiceStatus.ERROR, cause, e, true); throw new ServiceException("Exception during service starting", e); } catch (SessionConfigError e ) { @@ -504,7 +507,7 @@ public void start() { } catch (Exception e) { logger.error("not started", e); - this.changeStatus(ServiceStatus.ERROR, "Service start error", e, true); + changeStatus(ServiceStatus.ERROR, "Service start error", e, true); throw new ServiceException("Exception during service starting", e); } @@ -516,49 +519,44 @@ private void configErrorHandler(String message, ConfigError e){ logger.error("not started", e); - String cause = null; - - if ( e.getCause() != null ) - cause = e.getCause().getMessage(); - else - cause = e.getMessage(); + String cause = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); - this.changeStatus(ServiceStatus.ERROR, cause, e, true); + changeStatus(ServiceStatus.ERROR, cause, e, true); throw new ServiceException(message, e); } public synchronized void logon() throws ConfigError, FieldConvertError { - SessionSettings settings = this.initiator.getSettings(); + SessionSettings settings = initiator.getSettings(); logger.debug("settings = {}", settings); logger.info("initiator.start"); - this.initiator.start(); - int size = this.initiator.getSessions().size(); + initiator.start(); + int size = initiator.getSessions().size(); if (size != 1) { throw new EPSCommonException("Config file should contain only one session, but "+size); } - Iterator iter = this.initiator.getSessions().iterator(); + Iterator iter = initiator.getSessions().iterator(); while (iter.hasNext()) { SessionID sessionID = iter.next(); - FIXSession iSession = new FIXSession(this.serviceName.toString(), sessionID, msgStorage, this.converter, this.messageHelper); + FIXSession iSession = new FIXSession(serviceName.toString(), sessionID, msgStorage, converter, messageHelper); String sessionName = settings.getString(sessionID, SessionName); iSession.setServiceInfo(serviceInfo); logger.info("register session: {}", sessionName); this.session = iSession; - this.application.addSessionId(sessionID, iSession); + application.addSessionId(sessionID, iSession); } } @Override public IServiceHandler getServiceHandler() { - return this.handler; + return handler; } @Override public ISession getSession() { - return this.session; + return session; } @Override @@ -585,20 +583,20 @@ protected void changeStatus(ServiceStatus status, String message, Throwable e, b @Override public ServiceStatus getStatus() { - return this.curStatus; + return curStatus; } public void disconnect() { - if ( this.initiator != null ) { + if(initiator != null) { logger.info("disconnect"); - this.initiator.stop(); + initiator.stop(); } } public void forcedDisconnect() { - if ( this.initiator != null ) { + if(initiator != null) { logger.info("forced.disconnect"); - this.initiator.stop(true); + initiator.stop(true); } } @@ -613,12 +611,8 @@ public void setServiceHandler(IServiceHandler handler) { public IServiceSettings getSettings() { try { - if (this.fixSettings != null) { - //return copy of the settings to prevent it's change - return (IServiceSettings) BeanUtils.cloneBean(this.fixSettings); - } else { - return null; - } + //return copy of the settings to prevent it's change + return fixSettings != null ? (IServiceSettings)BeanUtils.cloneBean(fixSettings) : null; } catch (Exception e) { logger.error("Could not copy settings object", e); throw new EPSCommonException("Could not copy settings object", e); @@ -645,7 +639,7 @@ public void connect() throws Exception { @Override public IMessage receive(IActionContext actionContext, IMessage msg) throws InterruptedException { - return WaitAction.waitForMessage(actionContext, this.messageHelper.prepareMessageToEncode(msg, null), !msg.getMetaData().isAdmin()); + return WaitAction.waitForMessage(actionContext, messageHelper.prepareMessageToEncode(msg, null), !msg.getMetaData().isAdmin()); } public DirtyQFJIMessageConverter getConverter() { @@ -661,8 +655,8 @@ public List retrieve(long beginSeq, long endSeq) throws Exception { List messages = new ArrayList<>(); try(FileInputStream fis = new FileInputStream(logPath); - InputStreamReader isr = new InputStreamReader(fis, CharsetSupport.getCharset()); - BufferedReader reader = new BufferedReader(isr)) { + InputStreamReader isr = new InputStreamReader(fis, CharsetSupport.getCharset()); + BufferedReader reader = new BufferedReader(isr)) { DataDictionary dictionary = dictionaryProvider.getSessionDataDictionary(sessionID.getBeginString()); String line = null; @@ -686,13 +680,13 @@ public List retrieve(long beginSeq, long endSeq) throws Exception { logger.warn("Problem during conversion fix message [{}] to IMessage", line, e); } } + return messages; } - return messages; } - protected MessageHelper getMessageHelper() { - return this.messageHelper; + protected MessageHelper getMessageHelper() { + return messageHelper; } protected void setMessageHelper (MessageHelper messageHelper) { @@ -700,13 +694,13 @@ protected void setMessageHelper (MessageHelper messageHelper) { } private void connectionProblem(boolean isPresent, String reason) { - if (this.curStatus == ServiceStatus.ERROR) { + if(curStatus == ServiceStatus.ERROR) { return; } - if (isPresent && this.curStatus != ServiceStatus.WARNING) { + if(isPresent && curStatus != ServiceStatus.WARNING) { changeStatus(ServiceStatus.WARNING, reason, null); - } else if (!isPresent && this.curStatus == ServiceStatus.WARNING) { + } else if(!isPresent && curStatus == ServiceStatus.WARNING) { changeStatus(ServiceStatus.STARTED, reason, null); } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClientSettings.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClientSettings.java index 0968667c..fe96fe9e 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClientSettings.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXClientSettings.java @@ -74,7 +74,7 @@ public class FIXClientSettings extends FIXCommonSettings { @Description("Value of NewPassword(925) tag used in Logon(A) message") private String NewPassword; - private boolean EncryptPassword = false; + private boolean EncryptPassword; private String EncryptionKeyFilePath; @@ -108,13 +108,13 @@ public class FIXClientSettings extends FIXCommonSettings { private Integer SeqNumTarget; @Description("Add NextExpectedMsgSeqNum(789) tag into Logon(A) message") - private boolean addNextExpectedMsgSeqNum = false; + private boolean addNextExpectedMsgSeqNum; @Description("Ignore if tag ResetSeqNumFlag(141) is not present in the received Logon(A) message") - private boolean ignoreAbsenceOf141tag = false; + private boolean ignoreAbsenceOf141tag; @Description("If set to checked, service does not store messages") - private boolean performanceMode = false; + private boolean performanceMode; @Description("Create new session after disconnecting on the server side") private boolean autorelogin = true; diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCodec.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCodec.java index 81083807..1d86bcbc 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCodec.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCodec.java @@ -103,7 +103,7 @@ public void init(IServiceContext serviceContext, ICommonSettings settings, this.msgFactory = msgFactory; this.dictionary = Objects.requireNonNull(dictionary, "dictionary cannot be null"); this.fieldConverter = new FixFieldConverter(); - this.fieldConverter.init(dictionary, dictionary.getNamespace()); + fieldConverter.init(dictionary, dictionary.getNamespace()); this.qfjConverter = new DirtyQFJIMessageConverter(dictionary, msgFactory, false, false, false); this.msgStructures = new HashMap<>(); @@ -116,12 +116,12 @@ public void init(IServiceContext serviceContext, ICommonSettings settings, Boolean hasXmlFields = getAttributeValue(messageStructure, FixMessageHelper.HAS_XML_FIELDS_ATTR_NAME); if (Boolean.TRUE.equals(hasXmlFields)) { - this.messagesWithXmlField.add(msgType); + messagesWithXmlField.add(msgType); } } } this.dataDict = new QFJDictionaryAdapter(dictionary); - this.dataDict.setAllowUnknownMessageFields(true); + dataDict.setAllowUnknownMessageFields(true); String filterValues = this.settings.getFilterMessages(); messageFilter = StringUtils.isNotEmpty(filterValues) ? new TagValueFilter(filterValues) : new FakeFilter(); @@ -219,12 +219,11 @@ protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput message.getMetaData().setRawMessage(raw); out.write(message); - decoded = true; - break; + return true; } if (fixString == null) { - break; + return decoded; } logger.debug("doDecode: FixString = {}", fixString); @@ -236,11 +235,7 @@ protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput } try { - if (settings.isDecodeByDictionary()) { - message = convertToIMessageByIDictionaryStructure(fixString); - } else { - message = convertToIMessage(fixString); - } + message = settings.isDecodeByDictionary() ? convertToIMessageByIDictionaryStructure(fixString) : convertToIMessage(fixString); } catch (Exception e) { logger.error(e.getMessage(), e); @@ -257,13 +252,12 @@ protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput decoded = true; } - return decoded; } @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { if (message instanceof IMessage) { - IMessage originIMessage = ((IMessage) message); + IMessage originIMessage = (IMessage)message; MsgMetaData metaData = originIMessage.getMetaData(); IMessage encoded = originIMessage.cloneMessage(); @@ -298,11 +292,7 @@ protected IMessage convertToIMessageByIDictionaryStructure(String fixMessage) th MsgMetaData metaData = iMessage.getMetaData(); String unexpectedMessages = settings.getUnexpectedMessages(); - if (unexpectedMessages != null && !unexpectedMessages.trim().isEmpty()) { - metaData.setAdmin(isUnexpectedMessage(fixMessage, unexpectedMessages)); - } else { - metaData.setAdmin(false); - } + metaData.setAdmin(unexpectedMessages != null && !unexpectedMessages.trim().isEmpty() && isUnexpectedMessage(fixMessage, unexpectedMessages)); } return iMessage; @@ -316,7 +306,7 @@ protected IMessage convertToIMessage(String fixMessage) throws Exception { int separatorIndex = tagValueArray[i].indexOf("="); String key = tagValueArray[i].substring(0, separatorIndex); String value = tagValueArray[i].substring(separatorIndex + 1); - String convertedKey = (String) this.fieldConverter.convertValue(key, true); + String convertedKey = (String)fieldConverter.convertValue(key, true); if (convertedKey == null) { logger.warn("Tag [{}] does not present in the [{}] dictionary, " + "but exists in the [{}] incoming message", key, dictionary.getNamespace(), fixMessage); @@ -327,7 +317,7 @@ protected IMessage convertToIMessage(String fixMessage) throws Exception { } String msgType = fields.get(FixMessageHelper.MSG_TYPE_FIELD); - IMessageStructure messageStructure = this.msgStructures.get(msgType); + IMessageStructure messageStructure = msgStructures.get(msgType); String messageName; if(messageStructure == null) { @@ -338,7 +328,7 @@ protected IMessage convertToIMessage(String fixMessage) throws Exception { } IMessage iMessage = - MessageUtil.convertToIMessage(fields, this.msgFactory, this.dictionary.getNamespace(), messageName); + MessageUtil.convertToIMessage(fields, msgFactory, dictionary.getNamespace(), messageName); parseXmlFields(iMessage, new IMessageFieldExtractor(iMessage), iMessage.getField(FixMessageHelper.MSG_TYPE_FIELD)); @@ -346,11 +336,7 @@ protected IMessage convertToIMessage(String fixMessage) throws Exception { metaData.setRawMessage(fixMessage.getBytes()); metaData.setRejected(rejected); String unexpectedMessages = settings.getUnexpectedMessages(); - if (unexpectedMessages != null && !unexpectedMessages.trim().isEmpty()) { - metaData.setAdmin(isUnexpectedMessage(fixMessage, unexpectedMessages)); - } else { - metaData.setAdmin(false); - } + metaData.setAdmin(unexpectedMessages != null && !unexpectedMessages.trim().isEmpty() && isUnexpectedMessage(fixMessage, unexpectedMessages)); return iMessage; } @@ -402,7 +388,7 @@ protected IMessageStructure getMessageStructure(String msgTypeValue) { } private IMessage convertMessageToIMessage(Message message, String namespace) throws Exception { String msgType = message.getHeader().getString(MsgType.FIELD); - String messageName = this.msgStructures.get(msgType).getName(); + String messageName = msgStructures.get(msgType).getName(); IMessage iMessage = msgFactory.createMessage(messageName, namespace); // create header / trailer if not exist @@ -444,10 +430,10 @@ private void copyFields(FieldMap message, IMessage iMessageTo, IFieldStructure m Integer groupTag = getAttributeValue(fieldStructure, FixMessageHelper.ATTRIBUTE_TAG); List groups = message.getGroups(groupTag); - if(groups.size() != 0) { + if(!groups.isEmpty()) { List groupList = new ArrayList<>(); addGroup(groups, groupList, fieldStructure); - if(groupList.size() != 0) { + if(!groupList.isEmpty()) { iMessageTo.addField(fieldStructure.getName(), groupList); } } @@ -458,7 +444,7 @@ private void copyFields(FieldMap message, IMessage iMessageTo, IFieldStructure m IMessageStructure componentStructure = dictionary.getMessages().get(fieldStructure.getReferenceName()); copyFields(message, iMessageComponent, componentStructure); - if(iMessageComponent.getFieldNames().size() != 0) { + if(!iMessageComponent.getFieldNames().isEmpty()) { iMessageTo.addField(fieldStructure.getName(), Arrays.asList(iMessageComponent)); } @@ -466,12 +452,12 @@ private void copyFields(FieldMap message, IMessage iMessageTo, IFieldStructure m } else { Integer tag = getAttributeValue(fieldStructure, FixMessageHelper.ATTRIBUTE_TAG); if(tag != null && message.isSetField(tag)) { - if(this.settings.isRemoveTrailingZeros()) { + if(settings.isRemoveTrailingZeros()) { try { - if (JavaType.JAVA_LANG_DOUBLE.equals(fieldStructure.getJavaType())) { + if(fieldStructure.getJavaType() == JavaType.JAVA_LANG_DOUBLE) { String value = new BigDecimal(message.getString(tag)).stripTrailingZeros().toPlainString(); iMessageTo.addField(fieldStructure.getName(), value); - } else if (JavaType.JAVA_MATH_BIG_DECIMAL.equals(fieldStructure.getJavaType())) { + } else if(fieldStructure.getJavaType() == JavaType.JAVA_MATH_BIG_DECIMAL) { String value = message.getDecimal(tag).stripTrailingZeros().toPlainString(); iMessageTo.addField(fieldStructure.getName(), value); } else { @@ -499,7 +485,7 @@ private void addGroup(List groups, List groupList, IFieldStruct private IMessage parseXmlFields(IMessage targetMessage, IFieldExtractor fieldExtractor, String msgType) throws Exception { if (msgType != null && messagesWithXmlField.contains(msgType)) { - IMessageStructure msgStructure = this.msgStructures.get(msgType); + IMessageStructure msgStructure = msgStructures.get(msgType); if (msgStructure != null) { for(IFieldStructure fieldStructure : msgStructure.getFields().values()) { String entityType = getAttributeValue(fieldStructure, FixMessageHelper.ATTRIBUTE_ENTITY_TYPE); diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCommonSettings.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCommonSettings.java index e96ffb77..cf0e94ce 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCommonSettings.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXCommonSettings.java @@ -92,16 +92,16 @@ public class FIXCommonSettings extends AbstractServiceSettings { @Description("If set to checked, allow unknown fields in messages. This is intended for unknown fields with tags < 5000\n" + "(not user defined fields)") - protected boolean allowUnknownMsgFields = false; + protected boolean allowUnknownMsgFields; @Description("Determines if milliseconds should be added to timestamp fields. Only available for AML 3") protected boolean millisecondsInTimeStampFields = true; @Description("Determines if microseconds should be added to timestamp fields. Only available for AML 3. This value is more priority than 'Milliseconds In Time Stamp Fields'") - protected boolean microsecondsInTimeStampFields = false; + protected boolean microsecondsInTimeStampFields; @Description("Receive limit in bytes to emulate Slow Consumer") - protected int receiveLimit = 0; + protected int receiveLimit; @Description("Client send reject if message is invalid") protected boolean RejectInvalidMessage = true; @@ -119,13 +119,13 @@ public class FIXCommonSettings extends AbstractServiceSettings { protected boolean ValidateFieldsHaveValues = true; @Description("If set to checked, no reject sent on incoming message with duplicate tags Allow duplicated tags.") - protected boolean duplicateTagsAllowed = false; + protected boolean duplicateTagsAllowed; @Description("If specified, the session start and end will be converted from default zone to UTC") - protected boolean useLocalTime = false; + protected boolean useLocalTime; @Description("Enables SSL usage for QFJ acceptor or initiator") - protected boolean useSSL = false; + protected boolean useSSL; @Description("KeyStore to use with SSL") protected String sslKeyStore;//TODO: Use Alias for DataManager @@ -140,7 +140,7 @@ public class FIXCommonSettings extends AbstractServiceSettings { protected String sslCipherSuites; @Description("Enables fields ordering in raw message by dictionary") - protected boolean orderingFields = false; + protected boolean orderingFields; public String getBeginString() { return BeginString; diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLog.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLog.java index 1ca43aa2..774408bf 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLog.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLog.java @@ -24,6 +24,7 @@ import com.exactpro.sf.services.IService; import com.exactpro.sf.services.IServiceMonitor; import com.exactpro.sf.services.ServiceEvent; +import com.exactpro.sf.services.ServiceEvent.Type; import com.exactpro.sf.services.ServiceEventFactory; import quickfix.Log; @@ -35,10 +36,10 @@ public class FIXLog implements Log, Closeable { private final Logger logger; private final Log nativeLog; - private boolean INFO_ENABLE; - private boolean ERROR_ENABLE; + private final boolean INFO_ENABLE; + private final boolean ERROR_ENABLE; - public FIXLog(Log nativeLog, boolean logHeartbeats, final IService service, final IServiceMonitor monitor, final Logger logger) { + public FIXLog(Log nativeLog, boolean logHeartbeats, IService service, IServiceMonitor monitor, Logger logger) { this.nativeLog = Objects.requireNonNull(nativeLog, "'Native log' can't be null"); this.service = Objects.requireNonNull(service, "'Service' can't be null"); this.servMonitor = Objects.requireNonNull(monitor, "'Service monitor' can't be null"); @@ -54,7 +55,7 @@ public void clear() { @Override public void onEvent(String text) { - ServiceEvent event = ServiceEventFactory.createEventInfo(service.getServiceName(), ServiceEvent.Type.INFO, text, null); + ServiceEvent event = ServiceEventFactory.createEventInfo(service.getServiceName(), Type.INFO, text, null); if(INFO_ENABLE) { logger.info(text); } @@ -64,7 +65,7 @@ public void onEvent(String text) { @Override public void onErrorEvent(String text) { - ServiceEvent event = ServiceEventFactory.createEventError(service.getServiceName(), ServiceEvent.Type.ERROR, text, null); + ServiceEvent event = ServiceEventFactory.createEventError(service.getServiceName(), Type.ERROR, text, null); if(ERROR_ENABLE) { logger.error(text); } @@ -84,8 +85,8 @@ public void onOutgoing(String message) { @Override public void close() throws IOException { - if (this.nativeLog instanceof Closeable) { - ((Closeable)this.nativeLog).close(); + if(nativeLog instanceof Closeable) { + ((Closeable)nativeLog).close(); } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLogFactory.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLogFactory.java index 232a0677..fefea959 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLogFactory.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXLogFactory.java @@ -34,7 +34,7 @@ public class FIXLogFactory implements LogFactory private final LogFactory nativeLogFactory; private final Logger logger; - public FIXLogFactory(LogFactory nativeLogFactory, boolean logHeartbeats, final IService service, final IServiceMonitor monitor, final Logger logger) + public FIXLogFactory(LogFactory nativeLogFactory, boolean logHeartbeats, IService service, IServiceMonitor monitor, Logger logger) { this.service = Objects.requireNonNull(service, "'Service' can't be null"); @@ -56,7 +56,7 @@ public Log create() { @Override public Log create(SessionID sessionID) { - return new FIXLog(this.nativeLogFactory.create(sessionID), this.logHeartbeats, this.service, this.servMonitor, this.logger); + return new FIXLog(nativeLogFactory.create(sessionID), logHeartbeats, service, servMonitor, logger); } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXSession.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXSession.java index 632c77a6..c47e2b85 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXSession.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FIXSession.java @@ -65,7 +65,7 @@ public FIXSession(String sessionName, SessionID sessionId, IMessageStorage stora this.storage = storage; this.converter = converter; this.messageHelper = messageHelper; - this.logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + this.logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); } @Override @@ -78,18 +78,14 @@ public void forceClose() { try { lookupSession().disconnect("Disconnect without logout", true); } catch (IOException e) { - throw new ServiceException("Can not force close session for service " + this.name, e); + throw new ServiceException("Can not force close session for service " + name, e); } } @Override public boolean isClosed() { Session session = Session.lookupSession(sessionId); - if(session != null){ - return !session.isLoggedOn(); - } else { - return true; - } + return session == null || !session.isLoggedOn(); } @Override @@ -102,28 +98,27 @@ public IMessage send(Object message) { } else if (message instanceof IMessage) { Session session = lookupSession(); IMessage imsg = (IMessage) message; - if (this.messageHelper != null) { - imsg = this.messageHelper.prepareMessageToEncode(imsg, null); + if(messageHelper != null) { + imsg = messageHelper.prepareMessageToEncode(imsg, null); } else { - throw new ServiceException("Service '" + this.name + "' is configured incorrectly"); + throw new ServiceException("Service '" + name + "' is configured incorrectly"); } try { - if (this.converter != null) { - Message fmsg = this.converter.convert(imsg, session.getSessionID().isFIXT()); + if(converter != null) { + Message fmsg = converter.convert(imsg, session.getSessionID().isFIXT()); isSendSuccess = session.send(fmsg); if (!isSendSuccess) { throw new SendMessageFailedException("Send message " + imsg.getName() + " failed"); } - imsg = this.converter.convert(fmsg); + return converter.convert(fmsg); } else { - throw new ServiceException("Service '" + this.name + "' is configured incorrectly"); + throw new ServiceException("Service '" + name + "' is configured incorrectly"); } } catch (MessageConvertException e) { throw new ServiceException(new StringBuilder("Send message ").append(imsg.getName()).append(" failed").toString(), e); } - return imsg; - } else { + } else { throw new EPSCommonException("Unknown type of message: " + message.getClass().getCanonicalName()); } if (!isSendSuccess) { @@ -146,7 +141,7 @@ public IMessage sendDirty(Object message) throws InterruptedException { lockSenderMsgSeqNum(); try { - RawMessage convertedMessage = this.converter.convertDirty(iMessage, iMessage.getName(), true, getBeginString(), getExpectedSenderNum(), getSenderCompID(), getTargetCompID()); + RawMessage convertedMessage = converter.convertDirty(iMessage, iMessage.getName(), true, getBeginString(), getExpectedSenderNum(), getSenderCompID(), getTargetCompID()); String messageString = convertedMessage.toString(); sendRawMessage(getExpectedSenderNum(), messageString); @@ -166,7 +161,7 @@ public IMessage sendDirty(Object message) throws InterruptedException { @Override public String getName() { - return this.name; + return name; } @Override @@ -221,8 +216,8 @@ private void storeMessage(IMessage message, String messageString) { MsgMetaData metaData = message.getMetaData(); metaData.setAdmin(false); - metaData.setFromService(this.getSenderCompID()); - metaData.setToService(this.getTargetCompID()); + metaData.setFromService(getSenderCompID()); + metaData.setToService(getTargetCompID()); metaData.setRawMessage(messageString.getBytes(CharsetSupport.getCharsetInstance())); metaData.setServiceInfo(serviceInfo); @@ -252,13 +247,13 @@ public int setExpectedSenderNum(int seq) { try { state.getMessageStore().setNextSenderMsgSeqNum(seq); - } catch (IOException e) { + return seq; + } catch(IOException e) { session.getLog().onEvent( "setNextSenderMsgSeqNum failed: " + e.getMessage()); return -1; } - return seq; - } + } public int addExpectedSenderNum(int seq) { int oldSeq = getExpectedSenderNum(); @@ -286,7 +281,7 @@ public String getTargetCompID() { } public SessionID getSessionID() { - return this.sessionId; + return sessionId; } public ServiceInfo getServiceInfo() { @@ -309,8 +304,6 @@ public int hashCode() @Override public boolean equals(Object o) { - if (o == null) return false; - if (!(o instanceof FIXSession)) return false; - return getName().equals(((ISession)o).getName()); - } + return o instanceof FIXSession && getName().equals(((ISession)o).getName()); + } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixDataDictionaryProvider.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixDataDictionaryProvider.java index 90e1c5d6..0137fbee 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixDataDictionaryProvider.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixDataDictionaryProvider.java @@ -50,16 +50,16 @@ public FixDataDictionaryProvider(IDictionaryManager dictionaryManager, SailfishU } public void configure(SessionSettings settings, SessionID sessionID) throws ConfigError, FieldConvertError { - synchronized (this.configureLock) { - if (this.settingMap != null) { - logger.warn("Data dictionary provider already configured {}", this.settingMap); + synchronized(configureLock) { + if(settingMap != null) { + logger.warn("Data dictionary provider already configured {}", settingMap); } this.settingMap = new EnumMap<>(DataDictionarySetting.class); for (DataDictionarySetting setting : DataDictionarySetting.values()) { if (settings.isSetting(sessionID, setting.settingName)) { - this.settingMap.put(setting, settings.getBool(sessionID, setting.settingName)); + settingMap.put(setting, settings.getBool(sessionID, setting.settingName)); } } } @@ -80,15 +80,15 @@ public IDictionaryStructure getDictionaryStructure() { } private DataDictionary getDictionary() { - DataDictionary localDataDictionary = this.dataDictionary; + DataDictionary localDataDictionary = dataDictionary; if (localDataDictionary == null) { - synchronized (this.configureLock) { - localDataDictionary = this.dataDictionary; + synchronized(configureLock) { + localDataDictionary = dataDictionary; if (localDataDictionary == null) { - this.dataDictionary = localDataDictionary = new QFJDictionaryAdapter(this.dictionaryStructure); + this.dataDictionary = localDataDictionary = new QFJDictionaryAdapter(dictionaryStructure); - if (this.settingMap != null) { - for (Entry entry : this.settingMap.entrySet()) { + if(settingMap != null) { + for(Entry entry : settingMap.entrySet()) { DataDictionarySetting setting = entry.getKey(); boolean flag = entry.getValue(); setting.set(localDataDictionary, flag); @@ -102,8 +102,8 @@ private DataDictionary getDictionary() { return localDataDictionary; } - - private static enum DataDictionarySetting { + + private enum DataDictionarySetting { ALLOW_UNKNOWN_MSG_FIELDS(Session.SETTING_ALLOW_UNKNOWN_MSG_FIELDS) { @Override public void set(DataDictionary dataDictionary, boolean flag) { @@ -136,8 +136,8 @@ public void set(DataDictionary dataDictionary, boolean flag) { }; private final String settingName; - - private DataDictionarySetting(String settingName) { + + DataDictionarySetting(String settingName) { this.settingName = settingName; } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixFieldConverter.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixFieldConverter.java index d67622eb..02cd5b9a 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixFieldConverter.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixFieldConverter.java @@ -46,9 +46,9 @@ public IMessage convertFields(IMessage message, IMessageFactory messageFactory, Object targetValue = null; for (String fieldName : message.getFieldNames()) { if (fieldName.matches("\\d+") && toHumanReadable) { - targetName = this.tagToField.get(fieldName); + targetName = tagToField.get(fieldName); } else if (!fieldName.matches("\\d+") && !toHumanReadable) { - targetName = this.fieldToTag.get(fieldName); + targetName = fieldToTag.get(fieldName); } else { targetName = fieldName; } @@ -61,11 +61,7 @@ public IMessage convertFields(IMessage message, IMessageFactory messageFactory, List list = new ArrayList<>(); for (Object element : (List) targetValue) { - if (element instanceof IMessage) { - list.add(convertFields((IMessage) element, messageFactory, toHumanReadable)); - } else { - list.add(element); - } + list.add(element instanceof IMessage ? convertFields((IMessage)element, messageFactory, toHumanReadable) : element); } targetValue = list; @@ -86,30 +82,22 @@ public Object convertValue(Object value, boolean toHumanReadable) { @Override public void init(IDictionaryStructure dictionary, String namespace) { - this.fieldToTag.clear(); - this.tagToField.clear(); + fieldToTag.clear(); + tagToField.clear(); for(IFieldStructure fieldType : dictionary.getFields().values()) { String tag = getAttributeValue(fieldType, FixMessageHelper.ATTRIBUTE_TAG).toString(); - this.tagToField.put(tag, fieldType.getName()); - this.fieldToTag.put(fieldType.getName(), tag); + tagToField.put(tag, fieldType.getName()); + fieldToTag.put(fieldType.getName(), tag); } } public String convertToTag(String value) { - if(value.matches("\\d+")) { - return value; - } - - return fieldToTag.get(value); + return value.matches("\\d+") ? value : fieldToTag.get(value); } public String convertToName(String value) { - if(value.matches("\\d+")) { - return tagToField.get(value); - } - - return value; + return value.matches("\\d+") ? tagToField.get(value) : value; } } \ No newline at end of file diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixSessionFactory.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixSessionFactory.java index d98b2736..404a371a 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixSessionFactory.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixSessionFactory.java @@ -155,31 +155,31 @@ public Session create(SessionID sessionID, SessionSettings settings) throws Conf int logonTimeout = getSetting(settings, sessionID, Session.SETTING_LOGON_TIMEOUT, 10); int logoutTimeout = getSetting(settings, sessionID, Session.SETTING_LOGOUT_TIMEOUT, 2); - final boolean validateSequenceNumbers = getSetting(settings, sessionID, Session.SETTING_VALIDATE_SEQUENCE_NUMBERS, true); - final boolean validateIncomingMessage = getSetting(settings, sessionID, Session.SETTING_VALIDATE_INCOMING_MESSAGE, true); - final boolean resetOnError = getSetting(settings, sessionID, Session.SETTING_RESET_ON_ERROR, false); - final boolean disconnectOnError = getSetting(settings, sessionID, Session.SETTING_DISCONNECT_ON_ERROR, false); - final boolean disableHeartBeatCheck = getSetting(settings, sessionID, Session.SETTING_DISABLE_HEART_BEAT_CHECK, false); - final boolean forceResendWhenCorruptedStore = getSetting(settings, sessionID, Session.SETTING_FORCE_RESEND_WHEN_CORRUPTED_STORE, false); - final boolean enableNextExpectedMsgSeqNum = getSetting(settings, sessionID, Session.SETTING_ENABLE_NEXT_EXPECTED_MSG_SEQ_NUM, false); - final boolean enableLastMsgSeqNumProcessed = getSetting(settings, sessionID, Session.SETTING_ENABLE_LAST_MSG_SEQ_NUM_PROCESSED, false); - final int resendRequestChunkSize = getSetting(settings, sessionID, Session.SETTING_RESEND_REQUEST_CHUNK_SIZE, Session.DEFAULT_RESEND_RANGE_CHUNK_SIZE); - - final boolean rejectInvalidMessage = getSetting(settings, sessionID, + boolean validateSequenceNumbers = getSetting(settings, sessionID, Session.SETTING_VALIDATE_SEQUENCE_NUMBERS, true); + boolean validateIncomingMessage = getSetting(settings, sessionID, Session.SETTING_VALIDATE_INCOMING_MESSAGE, true); + boolean resetOnError = getSetting(settings, sessionID, Session.SETTING_RESET_ON_ERROR, false); + boolean disconnectOnError = getSetting(settings, sessionID, Session.SETTING_DISCONNECT_ON_ERROR, false); + boolean disableHeartBeatCheck = getSetting(settings, sessionID, Session.SETTING_DISABLE_HEART_BEAT_CHECK, false); + boolean forceResendWhenCorruptedStore = getSetting(settings, sessionID, Session.SETTING_FORCE_RESEND_WHEN_CORRUPTED_STORE, false); + boolean enableNextExpectedMsgSeqNum = getSetting(settings, sessionID, Session.SETTING_ENABLE_NEXT_EXPECTED_MSG_SEQ_NUM, false); + boolean enableLastMsgSeqNumProcessed = getSetting(settings, sessionID, Session.SETTING_ENABLE_LAST_MSG_SEQ_NUM_PROCESSED, false); + int resendRequestChunkSize = getSetting(settings, sessionID, Session.SETTING_RESEND_REQUEST_CHUNK_SIZE, Session.DEFAULT_RESEND_RANGE_CHUNK_SIZE); + + boolean rejectInvalidMessage = getSetting(settings, sessionID, Session.SETTING_REJECT_INVALID_MESSAGE, true); - final boolean rejectMessageOnUnhandledException = getSetting(settings, sessionID, + boolean rejectMessageOnUnhandledException = getSetting(settings, sessionID, Session.SETTING_REJECT_MESSAGE_ON_UNHANDLED_EXCEPTION, false); - final boolean requiresOrigSendingTime = getSetting(settings, sessionID, + boolean requiresOrigSendingTime = getSetting(settings, sessionID, Session.SETTING_REQUIRES_ORIG_SENDING_TIME, true); - final int[] logonIntervals = getLogonIntervalsInSeconds(settings, sessionID); - final Set allowedRemoteAddresses = getInetAddresses(settings, sessionID); + int[] logonIntervals = getLogonIntervalsInSeconds(settings, sessionID); + Set allowedRemoteAddresses = getInetAddresses(settings, sessionID); int receiveLimit = getSetting(settings, sessionID, Session.RECEIVE_LIMIT, 0); - final Session session = new Session(application, messageStoreFactory, sessionID, + Session session = new Session(application, messageStoreFactory, sessionID, dataDictionaryProvider, new SessionSchedule(settings, sessionID), logFactory, messageFactory, heartbeatInterval, checkLatency, maxLatency, millisInTimestamp, microsInTimestamp, resetOnLogon, resetOnLogout, resetOnDisconnect, refreshAtLogon, checkCompID, @@ -211,12 +211,7 @@ dataDictionaryProvider, new SessionSchedule(settings, sessionID), logFactory, } private ApplVerID toApplVerID(String value) { - if (isApplVerIdEnum(value)) { - return new ApplVerID(value); - } else { - // value should be a beginString - return MessageUtils.toApplVerID(value); - } + return isApplVerIdEnum(value) ? new ApplVerID(value) : MessageUtils.toApplVerID(value); // value should be a beginString } private boolean isApplVerIdEnum(String value) { @@ -245,10 +240,12 @@ private double getSetting(SessionSettings settings, SessionID sessionID, String private int[] getLogonIntervalsInSeconds(SessionSettings settings, SessionID sessionID) throws ConfigError { if (settings.isSetting(sessionID, Initiator.SETTING_RECONNECT_INTERVAL)) { try { - final String raw = settings.getString(sessionID, Initiator.SETTING_RECONNECT_INTERVAL); - final int[] ret = SessionSettings.parseSettingReconnectInterval(raw); - if (ret != null) return ret; - } catch (final Throwable e) { + String raw = settings.getString(sessionID, Initiator.SETTING_RECONNECT_INTERVAL); + int[] ret = SessionSettings.parseSettingReconnectInterval(raw); + if(ret != null) { + return ret; + } + } catch (Throwable e) { throw new ConfigError(e); } } @@ -259,10 +256,10 @@ private Set getInetAddresses(SessionSettings settings, SessionID se throws ConfigError { if (settings.isSetting(sessionID, Session.SETTING_ALLOWED_REMOTE_ADDRESSES)) { try { - final String raw = settings.getString(sessionID, + String raw = settings.getString(sessionID, Session.SETTING_ALLOWED_REMOTE_ADDRESSES); return SessionSettings.parseRemoteAddresses(raw); - } catch (final Throwable e) { + } catch (Throwable e) { throw new ConfigError(e); } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixUtil.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixUtil.java index a4fe690e..e9721478 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixUtil.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/FixUtil.java @@ -46,9 +46,12 @@ import com.exactpro.sf.services.fix.converter.MessageConvertException; import com.exactpro.sf.util.DateTimeUtility; +import quickfix.BooleanField; +import quickfix.CharField; import quickfix.DataDictionary; import quickfix.DataDictionaryProvider; import quickfix.DefaultDataDictionaryProvider; +import quickfix.DoubleField; import quickfix.Field; import quickfix.FieldConvertError; import quickfix.FieldException; @@ -56,8 +59,10 @@ import quickfix.FieldNotFound; import quickfix.FixVersions; import quickfix.Group; +import quickfix.IntField; import quickfix.InvalidMessage; import quickfix.Message; +import quickfix.StringField; import quickfix.field.BeginString; import quickfix.field.converter.BooleanConverter; import quickfix.field.converter.UtcDateOnlyConverter; @@ -72,8 +77,7 @@ */ public class FixUtil { - - private static DefaultDataDictionaryProvider provider = new DefaultDataDictionaryProvider(); + private static final DefaultDataDictionaryProvider provider = new DefaultDataDictionaryProvider(); private FixUtil() { @@ -233,7 +237,7 @@ public static Message fromString(String message) throws FieldNotFound, InvalidMe index2 = message.indexOf("\001", index1); String msgType = message.substring(index1+3, index2); boolean isApp = isApp(msgType); - DataDictionary dd = FixUtil.getDictionary(beginString, isApp); + DataDictionary dd = getDictionary(beginString, isApp); Message msg = new Message(); msg.fromString(message, dd, true); return msg; @@ -252,11 +256,11 @@ public static boolean isGroupField(FieldMap fieldMap, int tag) { private static long nextID = 1; public static synchronized String generateClorID() { - return String.valueOf(System.currentTimeMillis()+(nextID++)); + return String.valueOf(System.currentTimeMillis() + nextID++); } public static synchronized String generateClorIDSpecLng(int length) { - return String.valueOf(RandomStringUtils.random(length, "0123456789")); + return RandomStringUtils.random(length, "0123456789"); } public static String asString(Object obj) throws IllegalArgumentException, IllegalAccessException @@ -269,29 +273,24 @@ public static String asString(Object obj) throws IllegalArgumentException, Illeg && ((modifyers & Modifier.STATIC) == Modifier.STATIC) && ((modifyers & Modifier.PUBLIC) == Modifier.PUBLIC)) { - if (quickfix.IntField.class.isAssignableFrom(cls) - || quickfix.StringField.class.isAssignableFrom(cls) - || quickfix.CharField.class.isAssignableFrom(cls) - || quickfix.DoubleField.class.isAssignableFrom(cls) - || quickfix.BooleanField.class.isAssignableFrom(cls)) { - if (((quickfix.Field)obj).getObject().equals(constant.get(obj))) { + if(IntField.class.isAssignableFrom(cls) + || StringField.class.isAssignableFrom(cls) + || CharField.class.isAssignableFrom(cls) + || DoubleField.class.isAssignableFrom(cls) + || BooleanField.class.isAssignableFrom(cls)) { + if(((Field)obj).getObject().equals(constant.get(obj))) { return constant.getName(); } } } } - if (quickfix.Field.class.isAssignableFrom(cls)) - return String.valueOf(((quickfix.Field)obj).getObject()); - return obj.toString(); - } + return Field.class.isAssignableFrom(cls) ? String.valueOf(((Field)obj).getObject()) : obj.toString(); + } public static boolean isAdmin(String msgType) { - if (msgType != null && false == msgType.equals("")) { - return msgType.length() == 1 && "0A12345".indexOf(msgType.charAt(0)) != -1; - } - return false; - } + return msgType != null && msgType.length() == 1 && "0A12345".contains(msgType); + } public static boolean isApp(String msgType) { return !isAdmin(msgType); diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/IQuickfixApplication.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/IQuickfixApplication.java index a831747b..29eaef84 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/IQuickfixApplication.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/IQuickfixApplication.java @@ -21,11 +21,13 @@ import com.exactpro.sf.services.IServiceContext; import com.exactpro.sf.services.ISession; -public interface IQuickfixApplication extends quickfix.Application { +import quickfix.Application; - public void init(IServiceContext serviceContext, ApplicationContext applicationContext, ServiceName serviceName); - public List getSessions(); - public void startLogging(); - public void stopLogging(); - public default void onConnectionProblem(String reason) {} +public interface IQuickfixApplication extends Application { + + void init(IServiceContext serviceContext, ApplicationContext applicationContext, ServiceName serviceName); + List getSessions(); + void startLogging(); + void stopLogging(); + default void onConnectionProblem(String reason) {} } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/QFJDictionaryAdapter.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/QFJDictionaryAdapter.java index d31cb5d7..50148b94 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/QFJDictionaryAdapter.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/QFJDictionaryAdapter.java @@ -24,6 +24,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -71,16 +72,16 @@ public class QFJDictionaryAdapter extends DataDictionary { private boolean checkFieldsOutOfOrder = true; private boolean checkFieldsHaveValues = true; private boolean checkUserDefinedFields = true; - private boolean allowUnknownMessageFields = false; + private boolean allowUnknownMessageFields; private boolean checkUnorderedGroupFields = true; - private IDictionaryStructure iMsgDict; - private String version; + private final IDictionaryStructure iMsgDict; + private final String version; private String namespace; - private HashMap fields = new HashMap<>(); + private final HashMap fields = new HashMap<>(); - private HashMap messages = new HashMap<>(); - private HashMap> mesgFields = new HashMap<>(); + private final HashMap messages = new HashMap<>(); + private final HashMap> mesgFields = new HashMap<>(); private final Map> requiredFields = new HashMap<>(); private final Map> fieldValues = new HashMap<>(); private final Map messageCategory = new HashMap<>(); @@ -114,12 +115,6 @@ private void loadMsgTypes() { } } - private void addFieldName(int field, String name) /*throws ConfigError*/ { - if (names.put(name, field) != null) { - //throw new ConfigError("Field named " + name + " defined multiple times"); - } - } - private void indexFields(String messageType, Collection fieldStructures, boolean onlyFields) { HashMap msgFields = mesgFields.get(messageType); if (msgFields == null && !onlyFields) { @@ -147,7 +142,6 @@ private void indexFields(String messageType, Collection fieldSt msgFields.put(tag, fs); } fields.put(tag, fs); - addFieldName(tag.intValue(), fs.getName()); if (fs.isRequired() && !onlyFields) { try { if ( @@ -172,7 +166,7 @@ private void indexFields(String messageType, Collection fieldSt } for (String enumElement : fs.getValues().keySet()) { - if (JavaType.JAVA_LANG_BOOLEAN.equals(fs.getJavaType())) { + if(fs.getJavaType() == JavaType.JAVA_LANG_BOOLEAN) { fldValues.add(Boolean.TRUE.equals(fs.getValues().get(enumElement).getCastValue()) ? "Y" : "N"); } else { fldValues.add(fs.getValues().get(enumElement).getValue()); @@ -252,29 +246,29 @@ public void checkHasRequired(FieldMap header, FieldMap body, FieldMap trailer, S private void checkHasRequired(String msgType, FieldMap fields, boolean bodyOnly) { - final Set requiredFieldsForMessage = requiredFields.get(msgType); - if (requiredFieldsForMessage == null || requiredFieldsForMessage.size() == 0) { + Set requiredFieldsForMessage = requiredFields.get(msgType); + if(requiredFieldsForMessage == null || requiredFieldsForMessage.isEmpty()) { return; } - final Iterator fieldItr = requiredFieldsForMessage.iterator(); + Iterator fieldItr = requiredFieldsForMessage.iterator(); while (fieldItr.hasNext()) { - final int field = (fieldItr.next()).intValue(); + int field = fieldItr.next().intValue(); if (!fields.isSetField(field)) { throw new FieldException(SessionRejectReason.REQUIRED_TAG_MISSING, field); } } - final Map> groups = fields.getGroups(); - if (groups.size() > 0) { - final Iterator>> groupIter = groups.entrySet() + Map> groups = fields.getGroups(); + if(!groups.isEmpty()) { + Iterator>> groupIter = groups.entrySet() .iterator(); while (groupIter.hasNext()) { - final Map.Entry> entry = groupIter.next(); - final GroupInfo p = getGroup(msgType, (entry.getKey()).intValue()); - final List groupInstances = entry.getValue(); + Entry> entry = groupIter.next(); + GroupInfo p = getGroup(msgType, entry.getKey().intValue()); + List groupInstances = entry.getValue(); for (int i = 0; i < groupInstances.size(); i++) { - final FieldMap groupFields = groupInstances.get(i); + FieldMap groupFields = groupInstances.get(i); p.getDataDictionary().checkHasRequired(null, groupFields, null, msgType, bodyOnly); } @@ -285,9 +279,9 @@ private void checkHasRequired(String msgType, FieldMap fields, boolean bodyOnly) @Override public void iterate(FieldMap map, String msgType, DataDictionary dd) throws IncorrectTagValue, IncorrectDataFormat { - final Iterator> iterator = map.iterator(); + Iterator> iterator = map.iterator(); while (iterator.hasNext()) { - final StringField field = (StringField) iterator.next(); + StringField field = (StringField)iterator.next(); checkHasValue(field); @@ -305,8 +299,8 @@ public void iterate(FieldMap map, String msgType, DataDictionary dd) } } - for (final List groups : map.getGroups().values()) { - for (final Group group : groups) { + for(List groups : map.getGroups().values()) { + for(Group group : groups) { iterate(group, msgType, dd.getGroup(msgType, group.getFieldTag()) .getDataDictionary()); } @@ -324,12 +318,12 @@ private boolean shouldCheckTag(Field field) { } private void checkValue(StringField field) throws IncorrectTagValue { - final int tag = field.getField(); + int tag = field.getField(); if (!hasFieldValue(tag)) { return; } - final String value = field.getValue(); + String value = field.getValue(); if (!isFieldValue(tag, value)) { throw new IncorrectTagValue(tag); } @@ -345,13 +339,13 @@ private void checkIsInMessage(Field field, String msgType) { @Override public boolean isFieldValue(int field, String value) { - final Set validValues = fieldValues.get(field); + Set validValues = fieldValues.get(field); if (validValues.contains(ANY_VALUE)) { return true; } - if (validValues == null || validValues.size() == 0) { + if(validValues == null || validValues.isEmpty()) { return false; } @@ -360,7 +354,7 @@ public boolean isFieldValue(int field, String value) { } // MultipleValueString - final String[] values = value.split(" "); + String[] values = value.split(" "); for (int i = 0; i < values.length; i++) { if (!validValues.contains(values[i])) { return false; @@ -380,7 +374,7 @@ private void checkValidFormat(StringField field) throws IncorrectDataFormat { } try { - final FieldType fieldType = getFieldTypeEnum(field.getTag()); + FieldType fieldType = getFieldTypeEnum(field.getTag()); if (fieldType == FieldType.String) { // String } else if (fieldType == FieldType.Char) { @@ -434,14 +428,14 @@ private void checkValidFormat(StringField field) throws IncorrectDataFormat { } else if (fieldType == FieldType.Country) { // String } - } catch (final FieldConvertError e) { + } catch(FieldConvertError e) { throw new IncorrectDataFormat(field.getTag(), field.getValue()); } } // / Check if a field has a value. private void checkHasValue(StringField field) { - if (checkFieldsHaveValues && field.getValue().length() == 0) { + if(checkFieldsHaveValues && field.getValue().isEmpty()) { throw new FieldException(SessionRejectReason.TAG_SPECIFIED_WITHOUT_A_VALUE, field .getField()); } @@ -450,7 +444,7 @@ private void checkHasValue(StringField field) { // / Check if group count matches number of groups in @Override public void checkGroupCount(StringField field, FieldMap fieldMap, String msgType) { - final int fieldNum = field.getField(); + int fieldNum = field.getField(); if (isGroup(msgType, fieldNum)) { if (fieldMap.getGroupCount(fieldNum) != Integer.parseInt(field.getValue())) { throw new FieldException( @@ -514,7 +508,7 @@ public boolean isCheckUserDefinedFields() { @Override public Map> getMessageFields() { Map> msgFields = new HashMap<>(); - for (Map.Entry> mesgFld : mesgFields.entrySet()) { + for(Entry> mesgFld : mesgFields.entrySet()) { String msgType = mesgFld.getKey(); msgFields.put(msgType, new HashSet<>(mesgFld.getValue().keySet())); } @@ -566,19 +560,18 @@ public void setAllowUnknownMessageFields(boolean allowUnknownMessageFields) { @Override public String getValueName(int tag, String value) { - if (tag == MsgType.FIELD) + if(tag == MsgType.FIELD) { return getMessageName(value); - String result = null; + } IFieldStructure fieldType = iMsgDict.getFields().get(fields.get(tag).getName()); if (fieldType != null && fieldType.isEnum()) { for (String el : fieldType.getValues().keySet()) { if (fieldType.getValues().get(el).getValue().equals(value)) { - result = el; - break; + return el; } } } - return result; + return null; } @Override @@ -594,11 +587,8 @@ public boolean isGroup(String msgId, int field) { return false; } IFieldStructure fld = msgFld.get(field); - if (fld == null) { - return false; - } - return fld.isCollection(); - } + return fld != null && fld.isCollection(); + } @Override public int[] getOrderedFields() { @@ -628,16 +618,12 @@ public boolean isDataField(int tag) { return false; } String fixType = getAttributeValue(fs, ATTRIBUTE_FIX_TYPE); - if (fixType == null) { - //group field - return false; - } - return fixType.equals("DATA"); - } + return fixType != null && "DATA".equals(fixType); + } @Override public int getFieldTag(String name) { - final Integer tag = names.get(name); + Integer tag = names.get(name); return tag != null ? tag.intValue() : -1; } @@ -675,7 +661,7 @@ public boolean isHeaderGroup(int tag) { @Override public boolean isMsgField(String msgType, int tag) { - final HashMap fields = mesgFields.get(msgType); + HashMap fields = mesgFields.get(msgType); return fields != null && fields.containsKey(tag); } @@ -711,10 +697,10 @@ public Map getGroups() { } class GroupDictionary extends DataDictionary { - private int[] orderedFields = null; - private HashSet fields = null; + private int[] orderedFields; + private HashSet fields; private Set grpRequiredFields; - private IFieldStructure fieldStructure; + private final IFieldStructure fieldStructure; public GroupDictionary(String msg, int field, IFieldStructure fieldStructure) { this.fieldStructure = fieldStructure; @@ -762,29 +748,29 @@ public void checkHasRequired(FieldMap header, FieldMap body, } public void checkHasRequired(String msgType, FieldMap subGroup) { - final Set requiredFieldsForMessage = getRequiredFieldsForGroup() ; - if (requiredFieldsForMessage == null || requiredFieldsForMessage.size() == 0) { + Set requiredFieldsForMessage = getRequiredFieldsForGroup(); + if(requiredFieldsForMessage == null || requiredFieldsForMessage.isEmpty()) { return; } - final Iterator fieldItr = requiredFieldsForMessage.iterator(); + Iterator fieldItr = requiredFieldsForMessage.iterator(); while (fieldItr.hasNext()) { - final int field = (fieldItr.next()).intValue(); + int field = fieldItr.next().intValue(); if (!subGroup.isSetField(field)) { throw new FieldException(SessionRejectReason.REQUIRED_TAG_MISSING, field); } } - final Map> groups = subGroup.getGroups(); - if (groups.size() > 0) { - final Iterator>> groupIter = groups.entrySet() + Map> groups = subGroup.getGroups(); + if(!groups.isEmpty()) { + Iterator>> groupIter = groups.entrySet() .iterator(); while (groupIter.hasNext()) { - final Map.Entry> entry = groupIter.next(); - final GroupInfo p = getGroup(msgType, (entry.getKey()).intValue()); - final List groupInstances = entry.getValue(); + Entry> entry = groupIter.next(); + GroupInfo p = getGroup(msgType, entry.getKey().intValue()); + List groupInstances = entry.getValue(); for (int i = 0; i < groupInstances.size(); i++) { - final FieldMap groupFields = groupInstances.get(i); + FieldMap groupFields = groupInstances.get(i); p.getDataDictionary().checkHasRequired(null, groupFields, null, msgType, true); } @@ -877,10 +863,10 @@ private Integer getFieldTag(IFieldStructure fldstrct) { @Override public boolean isField(int tag) { - if (this.fields == null) { + if(fields == null) { indexFields(); } - return this.fields.contains(tag); + return fields.contains(tag); } @Override diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/MessageConvertException.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/MessageConvertException.java index 96aefce5..afaa30cf 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/MessageConvertException.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/MessageConvertException.java @@ -26,7 +26,6 @@ public class MessageConvertException extends Exception { private final Object sfMessage; public MessageConvertException(Object sfMessage) { - super(); this.sfMessage = sfMessage; } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/QFJIMessageConverter.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/QFJIMessageConverter.java index 3dfeff8f..26b73127 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/QFJIMessageConverter.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/QFJIMessageConverter.java @@ -158,12 +158,12 @@ public IMessage convert(Message message) throws MessageConvertException { return convert(message, null, null, false); } - public IMessage convert(final Message message, final Boolean verifyTagsOverride, final Boolean skipTagsOverride) throws MessageConvertException { + public IMessage convert(Message message, Boolean verifyTagsOverride, Boolean skipTagsOverride) throws MessageConvertException { return convert(message, verifyTagsOverride, skipTagsOverride, false); } - public IMessage convert(final Message message, final Boolean verifyTagsOverride, final Boolean skipTagsOverride, - final boolean ignoreFieldType) throws MessageConvertException { + public IMessage convert(Message message, Boolean verifyTagsOverride, Boolean skipTagsOverride, + boolean ignoreFieldType) throws MessageConvertException { if(message == null) { return null; } @@ -207,9 +207,9 @@ public IMessage convert(final Message message, final Boolean verifyTagsOverride, return resultMessage; } - protected void traverseMessage(final IMessage resultMessage, final FieldMap message, final IMessageFactory factory, - final IMessage rootMessage, final boolean verifyTags, - final boolean skipTags, final boolean ignoreFieldType) throws MessageConvertException { + protected void traverseMessage(IMessage resultMessage, FieldMap message, IMessageFactory factory, + IMessage rootMessage, boolean verifyTags, + boolean skipTags, boolean ignoreFieldType) throws MessageConvertException { String messageName = rootMessage.getName(); Iterator> it = message.iterator(); @@ -374,15 +374,15 @@ public Message convert(IMessage message, boolean fixt, Class } protected Message createInstance(String messageName, Class messageClass) throws InstantiationException, IllegalAccessException { - if (this.orderingFields && Message.class == messageClass) { + if(orderingFields && messageClass == Message.class) { IMessageStructure messageStructure = dictionary.getMessages().get(messageName); int[] fieldOrder = getFieldOrderPrimitive(messageStructure); - return new SailfishQuickfixMessage(fieldOrder, this.fieldOrderHeader, this.fieldOrderTrailer); + return new SailfishQuickfixMessage(fieldOrder, fieldOrderHeader, fieldOrderTrailer); } return messageClass.newInstance(); } - - protected void traverseIMessage(final FieldMap resultMessage, final IMessage message) throws MessageConvertException { + + protected void traverseIMessage(FieldMap resultMessage, IMessage message) throws MessageConvertException { IMessageStructure messageStructure = dictionary.getMessages().get(message.getName()); for(IFieldStructure fieldStructure : messageStructure.getFields().values()) { @@ -394,7 +394,7 @@ protected void traverseIMessage(final FieldMap resultMessage, final IMessage mes } if(fieldName.equals(FixMessageHelper.HEADER)) { - FieldMap header = ((quickfix.Message)resultMessage).getHeader(); + FieldMap header = ((Message)resultMessage).getHeader(); IMessage iHeader = message.getField(fieldName); traverseIMessage(header, iHeader); @@ -403,7 +403,7 @@ protected void traverseIMessage(final FieldMap resultMessage, final IMessage mes } if(fieldName.equals(FixMessageHelper.TRAILER)) { - FieldMap trailer = ((quickfix.Message)resultMessage).getTrailer(); + FieldMap trailer = ((Message)resultMessage).getTrailer(); IMessage iTrailer = message.getField(fieldName); traverseIMessage(trailer, iTrailer); @@ -446,7 +446,7 @@ protected void traverseIMessage(final FieldMap resultMessage, final IMessage mes resultMessage.setBoolean(fieldTag, (Boolean)fieldValue); continue; case JAVA_LANG_CHARACTER: - resultMessage.setString(fieldTag, (fieldValue.toString())); + resultMessage.setString(fieldTag, fieldValue.toString()); continue; case JAVA_LANG_DOUBLE: if(fieldValue instanceof BigDecimal) { diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/SailfishQuickfixMessage.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/SailfishQuickfixMessage.java index 72a2a091..11e7f4b1 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/SailfishQuickfixMessage.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/SailfishQuickfixMessage.java @@ -33,7 +33,7 @@ public SailfishQuickfixMessage(int[] fieldOrderBody, int[] fieldOrderHeader, int @Override public Object clone() { - final SailfishQuickfixMessage message = new SailfishQuickfixMessage(getFieldOrder(), getHeader().getFieldOrder(), getTrailer().getFieldOrder()); + SailfishQuickfixMessage message = new SailfishQuickfixMessage(getFieldOrder(), getHeader().getFieldOrder(), getTrailer().getFieldOrder()); message.initializeFrom(this); message.getSailfishHeader().initializeFrom(getHeader()); message.getSailfishTrailer().initializeFrom(getTrailer()); @@ -41,11 +41,11 @@ public Object clone() { } public SailfishQuickfixHeader getSailfishHeader() { - return this.header; + return header; } public SailfishQuickfixTrailer getSailfishTrailer() { - return this.trailer; + return trailer; } private final class SailfishQuickfixHeader extends Header { diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/DirtyQFJIMessageConverter.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/DirtyQFJIMessageConverter.java index c1d7d7d9..0eac0a75 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/DirtyQFJIMessageConverter.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/DirtyQFJIMessageConverter.java @@ -103,7 +103,7 @@ public IMessage convertDirty(Message message, Boolean verifyTagsOverride, Boolea return null; } - IMessage resultMessage = super.convert(message, verifyTagsOverride, skipTagsOverride, ignoreFieldType); + IMessage resultMessage = convert(message, verifyTagsOverride, skipTagsOverride, ignoreFieldType); if(inlineHeaderAndTrailer) { inlineMessage(resultMessage, FieldConst.HEADER); @@ -319,7 +319,7 @@ private void traverseDirtyIMessage(IMessage message, FieldList resultMessage, IF resultMessage.addField(new Field(fieldName, UtcTimestampConverter.convert(timestamp, includeMillis, includeMicros))); break; case JAVA_TIME_LOCAL_TIME: - resultMessage.addField(new Field(fieldName, UtcTimeOnlyConverter.convert(timestamp, this.includeMilliseconds, this.includeMicroseconds))); + resultMessage.addField(new Field(fieldName, UtcTimeOnlyConverter.convert(timestamp, includeMilliseconds, includeMicroseconds))); break; case JAVA_TIME_LOCAL_DATE: resultMessage.addField(new Field(fieldName, UtcDateOnlyConverter.convert(timestamp))); @@ -331,9 +331,9 @@ private void traverseDirtyIMessage(IMessage message, FieldList resultMessage, IF if (fieldValue instanceof LocalDate) { resultMessage.addField(new Field(fieldName, UtcDateOnlyConverter.convert(timestamp))); } else if (fieldValue instanceof LocalTime) { - resultMessage.addField(new Field(fieldName, UtcTimeOnlyConverter.convert(timestamp, this.includeMilliseconds, this.includeMicroseconds))); + resultMessage.addField(new Field(fieldName, UtcTimeOnlyConverter.convert(timestamp, includeMilliseconds, includeMicroseconds))); } else { - resultMessage.addField(new Field(fieldName, UtcTimestampConverter.convert(timestamp, this.includeMilliseconds, this.includeMicroseconds))); + resultMessage.addField(new Field(fieldName, UtcTimestampConverter.convert(timestamp, includeMilliseconds, includeMicroseconds))); } } } else if (fieldValue instanceof Boolean) { @@ -356,12 +356,7 @@ private List getFieldOrder(IFieldStructure messageStructure) { for(IFieldStructure fieldStructure : messageStructure.getFields().values()) { Integer fieldTag = getAttributeValue(fieldStructure, ATTRIBUTE_TAG); - - if(fieldTag != null) { - fieldOrder.add(fieldTag.toString()); - } else { - fieldOrder.add(fieldStructure.getName()); - } + fieldOrder.add(fieldTag != null ? fieldTag.toString() : fieldStructure.getName()); } // to ensure that comparator will place them at the start and the end accordingly @@ -373,10 +368,7 @@ private List getFieldOrder(IFieldStructure messageStructure) { private IFieldStructure getFieldStructure(String name, IFieldStructure messageStructure) { if(messageStructure == null) { - if (FieldConst.HEADER.equals(name) || FieldConst.TRAILER.equals(name)) { - return this.dictionary.getMessages().get(name); - } - return null; + return FieldConst.HEADER.equals(name) || FieldConst.TRAILER.equals(name) ? dictionary.getMessages().get(name) : null; } if (!messageStructure.isComplex()) { @@ -461,7 +453,7 @@ private void fillHeader(IMessage message, IMessageStructure messageStructure, St String sendingTimeValue = UtcTimestampConverter.convert( DateTimeUtility.toTimestamp(DateTimeUtility.nowLocalDateTime()), - this.includeMilliseconds, this.includeMicroseconds); + includeMilliseconds, includeMicroseconds); replaceIfNotExist(header, FieldConst.SENDING_TIME, sendingTimeValue); } @@ -474,7 +466,7 @@ private void fillHeader(IMessage message, IMessageStructure messageStructure, St * @return */ private Object extractComponent(String fieldName, Object fieldValue, IFieldStructure fieldStructure) { - if(fieldValue instanceof List && (fieldStructure != null && fieldStructure.isComplex() && !fieldStructure.isCollection())) { + if(fieldValue instanceof List && fieldStructure != null && fieldStructure.isComplex() && !fieldStructure.isCollection()) { return extractComponent(fieldValue); } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/Field.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/Field.java index 1e88aeef..e90285b7 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/Field.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/Field.java @@ -21,7 +21,7 @@ import java.util.Objects; public class Field { - private String name; + private final String name; private String value; private int index; private Field counter; @@ -117,9 +117,9 @@ public int getLength(Charset charset) { int length = 0; if(isSimple()) { - length = data.getBytes(charset).length; + return data.getBytes(charset).length; } else if(isComponent()) { - length = fields.getLength(charset); + return fields.getLength(charset); } else if(isGroup()) { if(counter != null) { length += counter.getLength(charset); diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/FieldList.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/FieldList.java index bc562c46..4aea71c0 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/FieldList.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/FieldList.java @@ -27,7 +27,7 @@ public class FieldList { private static final List LENGTH_EXCLUDED_FIELDS = Arrays.asList(FieldConst.BEGIN_STRING, FieldConst.BODY_LENGTH, FieldConst.CHECKSUM); - private List fields; + private final List fields; private List order; public FieldList() { @@ -62,9 +62,9 @@ public List getOrder() { } public void ensureOrder() { - Collections.sort(this.fields, new FieldComparator(this.order)); - - for (Field field : this.fields) { + Collections.sort(fields, new FieldComparator(order)); + + for(Field field : fields) { field.ensureOrder(); } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/RawMessage.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/RawMessage.java index 7c3fe38a..03f45d3f 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/RawMessage.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/converter/dirty/struct/RawMessage.java @@ -73,6 +73,6 @@ public void calculateCheckSum() { } public byte[] getBytes() { - return super.getBytes(CharsetSupport.getCharsetInstance()); + return getBytes(CharsetSupport.getCharsetInstance()); } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/AbstractProxyIoHandler.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/AbstractProxyIoHandler.java index 2e5c6f63..eeb7ab93 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/AbstractProxyIoHandler.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/AbstractProxyIoHandler.java @@ -19,26 +19,34 @@ import java.util.Iterator; import java.util.List; +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IoSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.configuration.FieldName; import com.exactpro.sf.configuration.FieldPosition; import com.exactpro.sf.configuration.RuleDescription; import com.exactpro.sf.services.tcpip.IProxyIoHandler; import com.exactpro.sf.services.tcpip.TCPIPProxy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IoSession; -import quickfix.*; + +import quickfix.Field; +import quickfix.FieldMap; +import quickfix.FieldNotFound; +import quickfix.Group; +import quickfix.Message; +import quickfix.StringField; /** - * Base class of {@link org.apache.mina.core.service.IoHandler} classes which handle + * Base class of {@link IoHandler} classes which handle * proxied connections. * */ public abstract class AbstractProxyIoHandler extends IoHandlerAdapter implements IProxyIoHandler { - private static Logger logger = LoggerFactory.getLogger(AbstractProxyIoHandler.class); + private static final Logger logger = LoggerFactory.getLogger(AbstractProxyIoHandler.class); private static final Charset CHARSET = Charset.forName("iso8859-1"); public static final String OTHER_IO_SESSION = AbstractProxyIoHandler.class.getName()+".OtherIoSession"; @@ -136,11 +144,11 @@ protected boolean isNotSendAndRulesProcess(Message mess, String msgType, TCPIPPr if (equals) { - if (null != rule.getNotSend()) { + if(rule.getNotSend() != null) { notSend = true; } else { - if (null != rule.getChange()) { + if(rule.getChange() != null) { for (FieldPosition field : rule.getChange().getField()) { int fieldId = getFieldId(field.getName()); @@ -151,26 +159,26 @@ protected boolean isNotSendAndRulesProcess(Message mess, String msgType, TCPIPPr try { - if (null != mess.getString(fieldId)) { - mess.setField(new quickfix.StringField(fieldId, field.getValue())); + if(mess.getString(fieldId) != null) { + mess.setField(new StringField(fieldId, field.getValue())); } } catch (FieldNotFound e) { - mess.getHeader().setField(new quickfix.StringField(fieldId, field.getValue())); + mess.getHeader().setField(new StringField(fieldId, field.getValue())); } } else { - map.setField(new quickfix.StringField(fieldId, field.getValue())); + map.setField(new StringField(fieldId, field.getValue())); } } } - if (null != rule.getRemove()) { + if(rule.getRemove() != null) { for (FieldName field : rule.getRemove().getField()) { int fieldId = getFieldId(field.getName()); @@ -181,7 +189,7 @@ protected boolean isNotSendAndRulesProcess(Message mess, String msgType, TCPIPPr try { - if (null != mess.getString(fieldId)) { + if(mess.getString(fieldId) != null) { mess.removeField(fieldId); } @@ -251,13 +259,9 @@ private FieldMap getField(FieldMap fmap, String name) throws NumberFormatExcepti } - if (null != fm) { - return getField(fm, name.substring(name.indexOf(".")+1, name.length())); - } - - return null; + return fm != null ? getField(fm, name.substring(name.indexOf(".") + 1)) : null; - } else { + } else { return fmap; } } diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ClientSideIoHandler.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ClientSideIoHandler.java index 20af134e..d87083ab 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ClientSideIoHandler.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ClientSideIoHandler.java @@ -55,19 +55,19 @@ */ public class ClientSideIoHandler extends AbstractProxyIoHandler { - private static Logger logger = LoggerFactory.getLogger(ClientSideIoHandler.class); - private ServerSideIoHandler connectorHandler = null; + private static final Logger logger = LoggerFactory.getLogger(ClientSideIoHandler.class); + private final ServerSideIoHandler connectorHandler; private final IoConnector connector; private final SocketAddress remoteAddress; - private IMessageStorage storage; - private IServiceHandler handler; - private DefaultMessageFactory factory = new DefaultMessageFactory(); - private DataDictionary appDictionary; + private final IMessageStorage storage; + private final IServiceHandler handler; + private final DefaultMessageFactory factory = new DefaultMessageFactory(); + private final DataDictionary appDictionary; private ServiceInfo serviceInfo; - private TCPIPProxy proxyService; - private ILoggingConfigurator logConfigurator; - private DirtyQFJIMessageConverter converter; - private ServiceName serviceName; + private final TCPIPProxy proxyService; + private final ILoggingConfigurator logConfigurator; + private final DirtyQFJIMessageConverter converter; + private final ServiceName serviceName; public ClientSideIoHandler(IoConnector connector, SocketAddress remoteAddress, IMessageStorage storage, IServiceHandler handler, TCPIPProxy proxyService, ILoggingConfigurator logConfigurator, IDictionaryStructure dictionary, IMessageFactory factory, @@ -89,7 +89,7 @@ public ClientSideIoHandler(IoConnector connector, } @Override - public void sessionOpened(final IoSession session) throws Exception { + public void sessionOpened(IoSession session) throws Exception { logger.debug("sessionOpened"); diff --git a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ServerSideIoHandler.java b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ServerSideIoHandler.java index 112ab6c9..0160ced7 100644 --- a/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ServerSideIoHandler.java +++ b/BackEnd/Service/service-fix/src/main/java/com/exactpro/sf/services/fix/handler/ServerSideIoHandler.java @@ -46,13 +46,13 @@ public class ServerSideIoHandler extends AbstractProxyIoHandler { private final Logger logger = LoggerFactory.getLogger(ServerSideIoHandler.class); - private IMessageStorage storage; - private IServiceHandler handler; - private DefaultMessageFactory factory; - private DataDictionary appDictionary; + private final IMessageStorage storage; + private final IServiceHandler handler; + private final DefaultMessageFactory factory; + private final DataDictionary appDictionary; private ServiceInfo serviceInfo; - private TCPIPProxy proxyService; - private DirtyQFJIMessageConverter converter; + private final TCPIPProxy proxyService; + private final DirtyQFJIMessageConverter converter; public ServerSideIoHandler(IoConnector connector, IMessageStorage storage, IServiceHandler handler, TCPIPProxy proxyService, DefaultMessageFactory factory, DataDictionary appDictionary, DirtyQFJIMessageConverter converter) { this.storage = storage; diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/SfDictionaryConverterTest.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/SfDictionaryConverterTest.java index bbe42953..e2cdefa6 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/SfDictionaryConverterTest.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/SfDictionaryConverterTest.java @@ -130,11 +130,13 @@ public void testConvert() throws Exception { } } finally { File del = new File(outputFolder); - if (del.exists()) + if(del.exists()) { FileUtils.deleteDirectory(del); + } File types = new File("types.xml"); - if (types.exists()) + if(types.exists()) { types.delete(); + } } } diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/TestFIXDictionaryValidator.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/TestFIXDictionaryValidator.java index 16a8258c..37d158f0 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/TestFIXDictionaryValidator.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/configuration/dictionary/TestFIXDictionaryValidator.java @@ -29,11 +29,7 @@ import com.exactpro.sf.util.AbstractTest; public class TestFIXDictionaryValidator extends AbstractTest { - private IDictionaryValidator dictionaryValidator; - - { - dictionaryValidator = new FIXDictionaryValidatorFactory().createDictionaryValidator(); - } + private final IDictionaryValidator dictionaryValidator = new FIXDictionaryValidatorFactory().createDictionaryValidator(); @Test public void testFIXDictionaryValidatorPositive() throws IOException { @@ -60,7 +56,7 @@ public void testFIXDictionaryValidatorNegative() throws IOException { for (DictionaryValidationError error : errors) { System.err.println(error.getError()); } - String[] errorMessages = new String[] { + String[] errorMessages = { "Field \"FieldWithIncorrectFixType\" contains incorrect value \"INCORRECTTYPE\" for \"fixtype\" attribute", "Message \"UndSecAltIDGrp_NoUnderlyingSecurityAltID\" doesn't contain fixtype attribute", "Field [1534] is missing in section for [CMRiskInstrumentScopesGrp_NoRiskInstrumentScopes] group", diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/FixCodecTest.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/FixCodecTest.java index ba7297b8..38e998c4 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/FixCodecTest.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/FixCodecTest.java @@ -18,6 +18,9 @@ import java.io.InputStream; import java.math.BigDecimal; import java.nio.charset.Charset; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -31,10 +34,8 @@ import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; import com.exactpro.sf.actions.DirtyFixUtil; import com.exactpro.sf.common.impl.messages.DefaultMessageFactory; @@ -106,7 +107,7 @@ public void init() { this.msgFactory = DefaultMessageFactory.getFactory(); this.codec = new FIXCodec(); - this.codec.init(serviceContext, settings, msgFactory, dictionary); + codec.init(serviceContext, settings, msgFactory, dictionary); } @Test @@ -123,39 +124,40 @@ public void testXmlSubMessage() throws Exception { IoSession session = new DummySession(); AbstractProtocolDecoderOutput outputDec = new MockProtocolDecoderOutput(); + @SuppressWarnings("ConfusingOctalEscapeSequence") String message = "8=FIXT.1.1\0019=1232\00135=777\00149=SEN\00156=TARGET\00134=2\00152=20121212-00:00:00\001" + - "11111=777.888999\001" + - "22222=StringField\001" + - "33333=333\001" + - "44444=-444.555666\001" + - "55555=Y\001" + - "66666=20170428\001" + - "77777=14:15:31.766\001" + - "88888=20170428-14:15:31.766\001" + - "99999=C\001" + - "7777=2\001" + // group - "7778=Tom\001" + - "7779=1\001" + - "7780=20001515-02:02:02.222\001" + - "7778=Jerry\001" + - "7779=2\001" + - "7780=20001515-03:03:03.333\001" + - "8888=CompString\001" + // component - "8889=-5\001" + - "8890=20001515-04:04:04.444\001" + - "100001=\012" + // xml message - " \012" + - " \012" + - " \012" + - " \012" + - " \012" + - " \012" + - " \012" + - " \012" + - " \012" + - "\012\001" + - "10=170\001"; + "11111=777.888999\001" + + "22222=StringField\001" + + "33333=333\001" + + "44444=-444.555666\001" + + "55555=Y\001" + + "66666=20170428\001" + + "77777=14:15:31.766\001" + + "88888=20170428-14:15:31.766\001" + + "99999=C\001" + + "7777=2\001" + // group + "7778=Tom\001" + + "7779=1\001" + + "7780=20001515-02:02:02.222\001" + + "7778=Jerry\001" + + "7779=2\001" + + "7780=20001515-03:03:03.333\001" + + "8888=CompString\001" + // component + "8889=-5\001" + + "8890=20001515-04:04:04.444\001" + + "100001=\012" + // xml message + " \012" + + " \012" + + " \012" + + " \012" + + " \012" + + " \012" + + " \012" + + " \012" + + " \012" + + "\012\001" + + "10=170\001"; IoBuffer buffer = IoBuffer.wrap(message.getBytes()); codec.decode(session, buffer, outputDec); @@ -271,6 +273,7 @@ public void testXmlSubMessage() throws Exception { // check component IMessage component = (IMessage)decodedMessage.getField("SomeComp"); Assert.assertEquals("CompString", component.getField("StringComp")); + //noinspection UnnecessaryParentheses Assert.assertEquals((Integer)(-5), component.getField("IntegerComp")); Assert.assertEquals(DateTimeUtility.toLocalDateTime( UtcTimestampConverter.convert("20001515-04:04:04.444")), @@ -398,21 +401,21 @@ public void testSendMessage() throws Exception { map.put("9", "001"); map.put("10", "2"); - IMessage iMessage = MessageUtil.convertToIMessage(map, this.msgFactory, "namespace", "name"); + IMessage iMessage = MessageUtil.convertToIMessage(map, msgFactory, "namespace", "name"); ProtocolEncoderOutput out = Mockito.mock(ProtocolEncoderOutput.class); Mockito.doAnswer(new Answer() { @Override - public Void answer(org.mockito.invocation.InvocationOnMock invocation) throws Throwable { + public Void answer(InvocationOnMock invocation) throws Throwable { Assert.assertEquals( //"8=FIXT.1.19=13935=216134=27582=CheckSum2010=12047=test2306=62620=modintsov3182=2254220=2451=2163464=MDRT006451=21632711=MDRT0067583=RefTagID10=151", "8=FIXT.1.19=00135=21612010=12047=test2306=62620=modintsov3182=2254220=2451=2163464=MDRT006451=21632711=MDRT00610=2", invocation.getArgument(0).getString(Charset.forName("UTF-8").newDecoder())); return null; - }; + } } ).when(out).write(Mockito.anyObject()); - this.codec.encode(null, iMessage, out); + codec.encode(null, iMessage, out); Assert.assertTrue(subMap1.containsKey("GroupDelimiter") && subMap2.containsKey("GroupDelimiter")); @@ -424,21 +427,21 @@ public Void answer(org.mockito.invocation.InvocationOnMock invocation) throws Th //TODO: Implement DUPLICATE_TAG for subMessage //subMap2.put(DirtyFixUtil.DUPLICATE_TAG, "2711=ABC;2711=DEF"); - iMessage = MessageUtil.convertToIMessage(map, this.msgFactory, "namespace", "name"); + iMessage = MessageUtil.convertToIMessage(map, msgFactory, "namespace", "name"); out = Mockito.mock(ProtocolEncoderOutput.class); Mockito.doAnswer(new Answer() { @Override - public Void answer(org.mockito.invocation.InvocationOnMock invocation) throws Throwable { + public Void answer(InvocationOnMock invocation) throws Throwable { Assert.assertEquals( //"8=FIXT.8.89=77735=216134=27582=CheckSum2010=12047=test2306=62620=modintsov3182=2254220=2451=2163464=MDRT006451=21632711=MDRT0067583=RefTagID2010=22010=310=999", "8=FIXT.8.89=77735=21612010=12010=22010=32047=test2306=62620=modintsov3182=2254220=2451=2163464=MDRT006451=21632711=MDRT00610=999", invocation.getArgument(0).getString(Charset.forName("UTF-8").newDecoder())); return null; - }; + } } ).when(out).write(Mockito.anyObject()); - this.codec.encode(null, iMessage, out); + codec.encode(null, iMessage, out); } @Test diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/QFJDictionaryAdapterTest.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/QFJDictionaryAdapterTest.java index 7d66a60d..344b77e6 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/QFJDictionaryAdapterTest.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/QFJDictionaryAdapterTest.java @@ -55,16 +55,16 @@ public void init() throws IOException { } this.qfjDictionaryAdapter = new QFJDictionaryAdapter(dictionaryStructure); - when(provider.getApplicationDataDictionary(new ApplVerID(ApplVerID.FIX50SP2))).thenReturn(this.qfjDictionaryAdapter); + when(provider.getApplicationDataDictionary(new ApplVerID(ApplVerID.FIX50SP2))).thenReturn(qfjDictionaryAdapter); } @Test public void testValidateInsertGroup() throws Exception { try { String messageString = "8=FIXT.1.19=24235=X49=TOR56=ft0134=852=20150529-11:30:20.596262=14328989480720000002-MBO1091=Y235=XD268=1279=0453=1448=25910=24"; - Message message = MessageUtils.parse(this.session, messageString); - this.qfjDictionaryAdapter.setAllowUnknownMessageFields(true); - this.qfjDictionaryAdapter.validate(message, false); + Message message = MessageUtils.parse(session, messageString); + qfjDictionaryAdapter.setAllowUnknownMessageFields(true); + qfjDictionaryAdapter.validate(message, false); } catch (Exception e){ e.printStackTrace(); Assert.fail(e.getMessage()); @@ -78,8 +78,8 @@ public void testSingleGroupInOtherGroup() throws Exception { Message msg = new Message(); msg.fromString(messageString, qfjDictionaryAdapter, true); // Message message = MessageUtils.parse(this.session, messageString); - this.qfjDictionaryAdapter.setAllowUnknownMessageFields(false); - this.qfjDictionaryAdapter.validate(msg, false); + qfjDictionaryAdapter.setAllowUnknownMessageFields(false); + qfjDictionaryAdapter.validate(msg, false); } catch (Exception e){ e.printStackTrace(); Assert.fail(e.getMessage()); @@ -90,9 +90,9 @@ public void testSingleGroupInOtherGroup() throws Exception { public void testAllowOtherValues() throws Exception { try { String messageString = "8=FIXT.1.19=23535=X49=TOR56=ft0134=852=20150529-11:30:20.596262=14328989480720000002-MBO234=000.1235=XD268=1279=0453=1448=25910=126"; - Message message = MessageUtils.parse(this.session, messageString); - this.qfjDictionaryAdapter.setAllowUnknownMessageFields(true); - this.qfjDictionaryAdapter.validate(message, false); + Message message = MessageUtils.parse(session, messageString); + qfjDictionaryAdapter.setAllowUnknownMessageFields(true); + qfjDictionaryAdapter.validate(message, false); } catch (Exception e){ e.printStackTrace(); Assert.fail(e.getMessage()); @@ -100,9 +100,9 @@ public void testAllowOtherValues() throws Exception { try { String messageString = "8=FIXT.1.19=23535=X49=TOR56=ft0134=852=20150529-11:30:20.596262=14328989480720000002-MBO234=XD235=0.001268=1279=0453=1448=25910=126"; - Message message = MessageUtils.parse(this.session, messageString); - this.qfjDictionaryAdapter.setAllowUnknownMessageFields(true); - this.qfjDictionaryAdapter.validate(message, false); + Message message = MessageUtils.parse(session, messageString); + qfjDictionaryAdapter.setAllowUnknownMessageFields(true); + qfjDictionaryAdapter.validate(message, false); } catch (IncorrectTagValue e) { Assert.assertEquals(235, e.field); } diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/DirtyQFJIMessageConverterTest.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/DirtyQFJIMessageConverterTest.java index 6eb04bb5..7b06c269 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/DirtyQFJIMessageConverterTest.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/DirtyQFJIMessageConverterTest.java @@ -17,6 +17,7 @@ import java.sql.Timestamp; import java.util.AbstractMap; +import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; @@ -68,7 +69,7 @@ public class DirtyQFJIMessageConverterTest extends ConverterTest { private static DataDictionary dataDictionary; private static IDictionaryStructure dictionary; private static final Logger logger = LoggerFactory.getLogger(DirtyQFJIMessageConverterTest.class); - private String MESSAGE = "8=FIXT.1.19=15535=Z34=115249=FIX_CSV_ds152=20151005-15:47:02.78556=FGW298=41166=1444060022986295=1299=test48=721994322=81461=11462=FIX_CSV_ds11463=D1464=7610=169"; + private final String MESSAGE = "8=FIXT.1.19=15535=Z34=115249=FIX_CSV_ds152=20151005-15:47:02.78556=FGW298=41166=1444060022986295=1299=test48=721994322=81461=11462=FIX_CSV_ds11463=D1464=7610=169"; @BeforeClass public static void initClass() { @@ -156,7 +157,7 @@ public void testConvertIMessageToRawWithoutExtract() throws Exception { IMessage iMessage = converter.convertDirty(message, false); RawMessage raw = converter.convertDirty(iMessage, "QuoteCancel", true, "FIXT.1.1", 1152, "FIX_CSV_ds1", "FGW"); - Assert.assertTrue("Message " + message.toString() + " is different from RawMessage " + raw.toString(), + Assert.assertTrue("Message " + message + " is different from RawMessage " + raw, compareMessages(message, raw)); } catch (Exception e) { logger.error(e.getMessage(), e); @@ -179,7 +180,7 @@ public void testConvertIMessageToRawWithExtract() throws Exception { IMessage iMessage = converter.convertDirty(message, true); String mock = null; RawMessage raw = converter.convertDirty(iMessage, "QuoteCancel", true, mock, 0, mock, mock); - Assert.assertTrue("Message " + message.toString() + " is different from RawMessage " + raw.toString(), + Assert.assertTrue("Message " + message + " is different from RawMessage " + raw, compareMessages(message, raw)); } catch (Exception e) { logger.error(e.getMessage(), e); @@ -252,13 +253,13 @@ public void testFillHeader() throws Exception { RawMessage raw = converter.convertDirty(iMessage, "QuoteCancel", true, "FIXT.1.1", 1152, "FIX_CSV_ds1", "FGW"); String timeExpected = UtcTimestampConverter.convert(new Timestamp(System.currentTimeMillis()), false, false).substring(0, 14); - Assert.assertTrue("Message " + message.toString() + " is different from RawMessage " + raw.toString(), + Assert.assertTrue("Message " + message + " is different from RawMessage " + raw, compareMessages(message, raw, 52)); String timeActual = getDateFromMessage(raw, 52); if (timeExpected != null) { Assert.assertEquals(timeExpected, timeActual.substring(0, 14)); } else { - Assert.fail("There is no SendingTime in the message " + raw.toString()); + Assert.fail("There is no SendingTime in the message " + raw); } } catch (Exception e) { logger.error(e.getMessage(), e); @@ -354,7 +355,7 @@ public void testConvertFromMessageToIMessageAndBack() throws Exception { false); IMessage iMessage = converter.convertDirty(message, false); RawMessage raw = converter.convertDirty(iMessage, "QuoteCancel", true, "", 0, "", ""); - Assert.assertTrue("Message " + message.toString() + " is different from RawMessage " + raw.toString(), + Assert.assertTrue("Message " + message + " is different from RawMessage " + raw, compareMessages(message, raw)); } catch (Exception e) { logger.error(e.getMessage(), e); @@ -437,7 +438,7 @@ public void testExcludeAutogeneratedTag() throws Exception { fields.clear(); excluded.clear(); - fields.add(new AbstractMap.SimpleEntry<>(CheckSum.class.getSimpleName(), + fields.add(new SimpleEntry<>(CheckSum.class.getSimpleName(), String.valueOf(CheckSum.FIELD))); raw = converter.convertDirty(iMessage, "QuoteCancel", true, "FIXT.1.1", 1152, "FIX_CSV_ds1", "FGW"); checkFieldExisting(raw.getField("trailer").getFields(), fields, excluded); @@ -458,19 +459,19 @@ public void testExcludeAutogeneratedTag() throws Exception { fields.clear(); excluded.clear(); - fields.add(new AbstractMap.SimpleEntry<>(BeginString.class.getSimpleName(), + fields.add(new SimpleEntry<>(BeginString.class.getSimpleName(), String.valueOf(BeginString.FIELD))); - fields.add(new AbstractMap.SimpleEntry<>(BodyLength.class.getSimpleName(), + fields.add(new SimpleEntry<>(BodyLength.class.getSimpleName(), String.valueOf(BodyLength.FIELD))); - fields.add(new AbstractMap.SimpleEntry<>(MsgType.class.getSimpleName(), + fields.add(new SimpleEntry<>(MsgType.class.getSimpleName(), String.valueOf(MsgType.FIELD))); - fields.add(new AbstractMap.SimpleEntry<>(SenderCompID.class.getSimpleName(), + fields.add(new SimpleEntry<>(SenderCompID.class.getSimpleName(), String.valueOf(SenderCompID.FIELD))); - fields.add(new AbstractMap.SimpleEntry<>(TargetCompID.class.getSimpleName(), + fields.add(new SimpleEntry<>(TargetCompID.class.getSimpleName(), String.valueOf(TargetCompID.FIELD))); - fields.add(new AbstractMap.SimpleEntry<>(MsgSeqNum.class.getSimpleName(), + fields.add(new SimpleEntry<>(MsgSeqNum.class.getSimpleName(), String.valueOf(MsgSeqNum.FIELD))); - fields.add(new AbstractMap.SimpleEntry<>(SendingTime.class.getSimpleName(), + fields.add(new SimpleEntry<>(SendingTime.class.getSimpleName(), String.valueOf(SendingTime.FIELD))); raw = converter.convertDirty(iMessage, "QuoteCancel", true, "FIXT.1.1", 1152, "FIX_CSV_ds1", "FGW"); @@ -509,7 +510,7 @@ public void testInlineWithoutExtract() throws Exception { IMessage iMessage = converter.convertDirty(message, true); RawMessage raw = converter.convertDirty(iMessage, "QuoteCancel", true, "FIXT.1.1", 1152, "FIX_CSV_ds1", "FGW"); - Assert.assertTrue("Message " + message.toString() + " is different from RawMessage " + raw.toString(), + Assert.assertTrue("Message " + message + " is different from RawMessage " + raw, compareMessages(message, raw, false, false)); } catch (Exception e) { logger.error(e.getMessage(), e); @@ -740,7 +741,7 @@ private void checkFieldExisting(FieldList message, Set> fi private void testGroupCounter(IMessage iMessage, Message message, DirtyQFJIMessageConverter converter) throws MessageConvertException { RawMessage raw = converter.convertDirty(iMessage, "QuoteCancel", false, "FIXT.1.1", 1152, "FIX_CSV_ds1", "FGW"); - Assert.assertTrue("Message " + message.toString() + " is different from RawMessage " + raw.toString(), + Assert.assertTrue("Message " + message + " is different from RawMessage " + raw, compareMessages(message, raw, 1461)); Assert.assertTrue("RawMessage doesn't contain 1461=2", raw.toString().contains("1461=2")); } diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/QFJMessage2IMessageTest.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/QFJMessage2IMessageTest.java index 9acca45d..524ffb84 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/QFJMessage2IMessageTest.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/QFJMessage2IMessageTest.java @@ -61,13 +61,14 @@ public void testRepeatingGroupOrderedFields() fixMessageSrc.fromString( "8=FIXT.1.19=14635=Z34=115249=FIX_CSV_ds152=20151005-15:47:02.78556=FGW298=41166=1444060022986295=1299=test48=721994322=81461=11462=FIX_CSV_ds11463=D1464=7610=169", dataDict, true); - if (fixMessageSrc.getException() != null) + if(fixMessageSrc.getException() != null) { throw fixMessageSrc.getException(); + } IDictionaryStructure dictionary = getSfDictionary("FIX50.TEST.xml"); QFJIMessageConverter converter = new QFJIMessageConverter(dictionary, messageFactory, false, true, false); IMessage iMessage = converter.convert(fixMessageSrc); - quickfix.Message fixMessageTarget = converter.convert(iMessage, true); + Message fixMessageTarget = converter.convert(iMessage, true); Assert.assertEquals( "8=FIXT.1.19=15535=Z34=115249=FIX_CSV_ds152=20151005-15:47:02.78556=FGW298=41166=1444060022986295=1299=test48=721994322=81461=11462=FIX_CSV_ds11463=D1464=7610=169", fixMessageTarget.toString()); @@ -98,8 +99,9 @@ public void testEmptyRepeatingGroup() throws Exception { Message fixMessageSrc = new Message(); DataDictionary dataDict = getFixDictionary("FIX50.xml"); fixMessageSrc.fromString(rawMessage, dataDict, true); - if (fixMessageSrc.getException() != null) + if(fixMessageSrc.getException() != null) { throw fixMessageSrc.getException(); + } IDictionaryStructure dictionary = getSfDictionary("FIX50.TEST.xml"); QFJIMessageConverter converter = new QFJIMessageConverter(dictionary, messageFactory, false, true, false); @@ -124,8 +126,9 @@ public void testEmptyRepeatingGroup2() throws Exception { Message fixMessageSrc = new Message(); DataDictionary dataDict = getFixDictionary("FIX50.xml"); fixMessageSrc.fromString(rawMessage, a, true); - if (fixMessageSrc.getException() != null) + if(fixMessageSrc.getException() != null) { throw fixMessageSrc.getException(); + } IDictionaryStructure dictionary = getSfDictionary("FIX50.TEST.xml"); QFJIMessageConverter converter = new QFJIMessageConverter(dictionary, messageFactory, false, true, false); @@ -149,7 +152,7 @@ public void testIncludeMilliseconds() throws InvalidMessage, ConfigError, FieldN QFJIMessageConverter converter = new QFJIMessageConverter(dictionary, messageFactory, false, true, false); IMessage iMessage = converter.convert(fixMessageSrc); - quickfix.Message fixMessageTarget = converter.convert(iMessage, true); + Message fixMessageTarget = converter.convert(iMessage, true); String fixMessageString = fixMessageTarget.toString(); Assert.assertTrue("With millisecond", fixMessageString.contains("52=20150707-09:05:21.580")); @@ -193,7 +196,7 @@ public void testFixToIMessageAndBack() "8=FIXT.1.19=17035=X34=78943=Y49=Sender52=20160630-10:37:21.00156=Target262=SomeReqID268=1279=0270=876.543271=123.5272=20160630273=10:37:21.003278=SomeEntryID711=1311=ABC10=090", dataDictionary); - System.out.println(message.toString()); + System.out.println(message); IDictionaryStructure dictionary = getSfDictionary("FIX50.TEST.xml"); QFJIMessageConverter converter = new QFJIMessageConverter(dictionary, messageFactory, false, true, false); @@ -201,8 +204,8 @@ public void testFixToIMessageAndBack() IMessage iMessage = converter.convert(message); Message newMessage = converter.convert(iMessage, true); - System.out.println(iMessage.toString()); - System.out.println(newMessage.toString()); + System.out.println(iMessage); + System.out.println(newMessage); Assert.assertEquals(message.toString(), newMessage.toString()); } @@ -263,7 +266,7 @@ public void testIMessageToFixAndBack() throws FileNotFoundException, IOException Message fixMessage = converter.convert(message, true); IMessage newMessage = converter.convert(fixMessage); - System.out.println(fixMessage.toString()); + System.out.println(fixMessage); ComparisonResult comparisonResult = MessageComparator.compare(message, newMessage, new ComparatorSettings()); @@ -311,13 +314,13 @@ public void testDifferentTypes() throws FileNotFoundException, IOException, Mess Message fixMessage = converter.convert(message, true); - System.out.println(fixMessage.toString()); + System.out.println(fixMessage); Group group = fixMessage.getGroup(1, 268); Assert.assertTrue(group.getDecimal(270).equals(new BigDecimal("123.5"))); Assert.assertTrue(group.getDouble(271) == 124.5); - Assert.assertTrue(group.getString(278).equals("S")); + Assert.assertTrue("S".equals(group.getString(278))); } @SuppressWarnings("serial") diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/TestRawMessage.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/TestRawMessage.java index ff0c9fb5..36183921 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/TestRawMessage.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/services/fix/converter/TestRawMessage.java @@ -32,8 +32,8 @@ public class TestRawMessage { - private final String[] bodyLangthPath = new String[] { FieldConst.HEADER, FieldConst.BODY_LENGTH }; - private final String[] checkSumPath = new String[] { FieldConst.TRAILER, FieldConst.CHECKSUM }; + private final String[] bodyLangthPath = { FieldConst.HEADER, FieldConst.BODY_LENGTH }; + private final String[] checkSumPath = { FieldConst.TRAILER, FieldConst.CHECKSUM }; @Test public void testCalculation() throws UnsupportedEncodingException { @@ -90,18 +90,16 @@ private RawMessage checkCalculation(RawMessage rawMessage, Charset charset) { } private String getField(FieldList fieldList, String... path) { - String result = null; for (int i = 0; i < path.length; i++) { if (i == path.length - 1) { - result = fieldList.getField(path[i]).getValue(); - break; + return fieldList.getField(path[i]).getValue(); } else { fieldList = fieldList.getField(path[i]).getFields(); } } - return result; + return null; } private int checkSum(RawMessage rawMessage, Charset charset) { diff --git a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/util/ConverterTest.java b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/util/ConverterTest.java index 8c282de3..1c05f7ab 100644 --- a/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/util/ConverterTest.java +++ b/BackEnd/Service/service-fix/src/test/java/com/exactpro/sf/util/ConverterTest.java @@ -49,9 +49,9 @@ public class ConverterTest extends AbstractTest { private final IMessageFactory messageFactory = DefaultMessageFactory.getFactory(); - private static IDictionaryStructureLoader loader = new XmlDictionaryStructureLoader(); - private static Map fixDixtionaries = new HashMap<>(); - private static Map sfDictionaries = new HashMap<>(); + private static final IDictionaryStructureLoader loader = new XmlDictionaryStructureLoader(); + private static final Map fixDixtionaries = new HashMap<>(); + private static final Map sfDictionaries = new HashMap<>(); protected static DataDictionary getFixDictionary(String fileName) throws FileNotFoundException, IOException, ConfigError { DataDictionary result = fixDixtionaries.get(fileName); diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/actions/ITCHCommonActions.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/actions/ITCHCommonActions.java index 9acf9eb3..3a8bbbb0 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/actions/ITCHCommonActions.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/actions/ITCHCommonActions.java @@ -15,14 +15,14 @@ ******************************************************************************/ package com.exactpro.sf.actions; -import com.exactpro.sf.common.impl.messages.BaseMessage; -import com.exactpro.sf.common.messages.IMessage; -import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.aml.CommonColumn; import com.exactpro.sf.aml.CommonColumns; import com.exactpro.sf.aml.Description; import com.exactpro.sf.aml.generator.matrix.Column; import com.exactpro.sf.aml.script.actions.WaitAction; +import com.exactpro.sf.common.impl.messages.BaseMessage; +import com.exactpro.sf.common.messages.IMessage; +import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.comparison.ComparisonResult; import com.exactpro.sf.configuration.ResourceAliases; import com.exactpro.sf.scriptrunner.AbstractCaller; @@ -42,7 +42,7 @@ * @author dmitry.guriev * */ -@ResourceAliases({"ITCHCommonActions"}) +@ResourceAliases("ITCHCommonActions") public class ITCHCommonActions extends AbstractCaller { protected final TestActions testActions; @@ -52,9 +52,7 @@ public ITCHCommonActions() { @Deprecated @Description("This function is deprecated, please use the reconnectService() method from TestActions.") - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void ITCH_Connect(IActionContext actionContext) throws InterruptedException { @@ -73,9 +71,7 @@ public void ITCH_Connect(IActionContext actionContext) throws InterruptedExcepti actionContext.getLogger().info("[{}] Successfully connected to channel", actionContext.getServiceName()); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void ITCH_Disconnect(IActionContext actionContext) throws InterruptedException { @@ -106,16 +102,16 @@ public void ITCH_Disconnect(IActionContext actionContext) throws InterruptedExce report.createVerification(StatusType.PASSED, "Disconnect from ITCH server", "", ""); } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void ITCH_IsConnected(IActionContext actionContext) throws Exception { IITCHClient client = getClient(actionContext); String actionId = actionContext.getId(); - if (actionId != "") actionId += " "; + if(actionId != "") { + actionId += " "; + } IActionReport report = actionContext.getReport(); String verificationName = actionId + String.format("Checking whether the service [%s] is connected", client.getName()); ComparisonResult cr = new ComparisonResult("ITCH_IsConnected"); @@ -139,16 +135,16 @@ public void ITCH_IsConnected(IActionContext actionContext) } } - @CommonColumns({ - @CommonColumn(value = Column.ServiceName, required = true) - }) + @CommonColumns(@CommonColumn(value = Column.ServiceName, required = true)) @ActionMethod public void ITCH_IsDisconnected(IActionContext actionContext) throws Exception { IITCHClient client = getClient(actionContext); String actionId = actionContext.getId(); - if (actionId != "") actionId += " "; + if(actionId != "") { + actionId += " "; + } IActionReport report = actionContext.getReport(); String verificationName = actionId + String.format("Checking whether the service [%s] is disconnected", client.getName()); ComparisonResult cr = new ComparisonResult("ITCH_IsDisconnected"); @@ -265,7 +261,8 @@ protected BaseMessage send(IActionContext actionContext, BaseMessage message) th try { tcpClient.sendMessage( message.getMessage()); - } + return message; + } catch (Exception err) { if(err instanceof InterruptedException){ @@ -274,16 +271,15 @@ protected BaseMessage send(IActionContext actionContext, BaseMessage message) th throw new ScriptRunException( "[" + actionContext.getServiceName() +"] " + "Can't send "+message.getClass().getSimpleName()+" to channel;", err ); } - return message; - } + } protected IMessage sendMulti(IActionContext actionContext, BaseMessage message) throws InterruptedException { - ITCHMulticastUDPSession session; ITCHMulticastServer service = ActionUtil.getService(actionContext, ITCHMulticastServer.class); - session = (ITCHMulticastUDPSession) service.getSession(); - if(session == null) + ITCHMulticastUDPSession session = (ITCHMulticastUDPSession)service.getSession(); + if(session == null) { throw new ScriptRunException("[" + actionContext.getServiceName() +"] " + "not runned;"); + } return session.send(message.getMessage()); } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/dictionary/impl/ITCHDictionaryValidator.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/dictionary/impl/ITCHDictionaryValidator.java index a6a4e30f..57238fba 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/dictionary/impl/ITCHDictionaryValidator.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/dictionary/impl/ITCHDictionaryValidator.java @@ -37,13 +37,13 @@ import com.exactpro.sf.configuration.dictionary.interfaces.IDictionaryValidator; import com.exactpro.sf.services.itch.ITCHMessageHelper; import com.exactpro.sf.services.itch.ITCHVisitorBase; +import com.exactpro.sf.services.itch.ITCHVisitorBase.ProtocolType; public class ITCHDictionaryValidator extends AbstractDictionaryValidator { private static final long serialVersionUID = 14671967127441418L; public ITCHDictionaryValidator() { - super(); } public ITCHDictionaryValidator(IDictionaryValidator parentValidator) { @@ -112,8 +112,9 @@ private boolean isSubMessage(IDictionaryStructure dictionary, IMessageStructure for(IMessageStructure message : dictionary.getMessages().values()) { for(IFieldStructure field : message.getFields().values()) { - if (field.getReferenceName() != null && field.getReferenceName().equals(subMessage.getName())) + if(field.getReferenceName() != null && field.getReferenceName().equals(subMessage.getName())) { return true; + } } } return false; @@ -162,8 +163,8 @@ private void checkRequiredAttributes(List errors, IMe return; } - ITCHVisitorBase.ProtocolType type = - ITCHVisitorBase.ProtocolType.getEnum(getAttributeValue(field, ITCHVisitorBase.TYPE_ATTRIBUTE)); + ProtocolType type = + ProtocolType.getEnum(getAttributeValue(field, ITCHVisitorBase.TYPE_ATTRIBUTE)); Integer length = getAttributeValue(field, ITCHVisitorBase.LENGTH_ATTRIBUTE); JavaType javaType = field.getJavaType(); @@ -214,12 +215,12 @@ private void checkRequiredAttributes(List errors, IMe JavaType.JAVA_LANG_DOUBLE, JavaType.JAVA_MATH_BIG_DECIMAL}, javaType); - if (javaType.equals(JavaType.JAVA_LANG_FLOAT)) { + if(javaType == JavaType.JAVA_LANG_FLOAT) { if (length != 4) { addProtocolTypeError(errors, message, field, type, 4, length); } - } else if (javaType.equals(JavaType.JAVA_LANG_DOUBLE) - || javaType.equals(JavaType.JAVA_MATH_BIG_DECIMAL)) { + } else if(javaType == JavaType.JAVA_LANG_DOUBLE + || javaType == JavaType.JAVA_MATH_BIG_DECIMAL) { if (length != 8) { addProtocolTypeError(errors, message, field, type, 8, length); } @@ -378,7 +379,7 @@ private void checkRequiredAttributes(List errors, IMe } - private void addProtocolTypeError(List errors, IMessageStructure message, IFieldStructure field, ITCHVisitorBase.ProtocolType type, + private void addProtocolTypeError(List errors, IMessageStructure message, IFieldStructure field, ProtocolType type, int expectedLength, int actualLength) { errors.add(new DictionaryValidationError(message == null ? null : message.getName(), field.getName(), "Attribute \"Length\" for type \"" + type @@ -390,7 +391,7 @@ private void addProtocolTypeError(List errors, IMessa private boolean checkJavaType(List errors, IMessageStructure message, IFieldStructure field, JavaType expectedType, JavaType actualType) { - if(!actualType.equals(expectedType)) { + if(actualType != expectedType) { errors.add(new DictionaryValidationError(message == null ? null : message.getName(), field.getName(), "Field \"" + field.getName() + "\" has incorrect type = [" + actualType + "]. Must be [" + expectedType + "]", @@ -405,7 +406,7 @@ private boolean checkJavaType(List errors, IMessageSt private boolean checkJavaTypeArray(List errors, IMessageStructure message, IFieldStructure field, JavaType[] expectedTypeList, JavaType actualType) { for(JavaType currentType : expectedTypeList) { - if(actualType.equals(currentType)) { + if(actualType == currentType) { return true; } } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/factory/ITCHMessageFactory.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/factory/ITCHMessageFactory.java index fe703ac8..ae2a5db6 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/factory/ITCHMessageFactory.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/configuration/factory/ITCHMessageFactory.java @@ -15,22 +15,18 @@ ******************************************************************************/ package com.exactpro.sf.configuration.factory; +import java.util.Set; + import com.exactpro.sf.common.impl.messages.AbstractMessageFactory; import com.exactpro.sf.services.itch.ITCHMessageHelper; import com.google.common.collect.ImmutableSet; -import java.util.Set; - public class ITCHMessageFactory extends AbstractMessageFactory { - public final static Set UNCHECKED_FIELDS; - - static { - UNCHECKED_FIELDS = ImmutableSet.of( - ITCHMessageHelper.FAKE_FIELD_MESSAGE_SEQUENCE_NUMBER, - ITCHMessageHelper.FAKE_FIELD_UH_SEQUENCE_NUMBER, - ITCHMessageHelper.FAKE_FIELD_UH_MARKET_DATA_GROUP, - ITCHMessageHelper.FAKE_FIELD_MESSAGE_TIME); - } + public static final Set UNCHECKED_FIELDS = ImmutableSet.of( + ITCHMessageHelper.FAKE_FIELD_MESSAGE_SEQUENCE_NUMBER, + ITCHMessageHelper.FAKE_FIELD_UH_SEQUENCE_NUMBER, + ITCHMessageHelper.FAKE_FIELD_UH_MARKET_DATA_GROUP, + ITCHMessageHelper.FAKE_FIELD_MESSAGE_TIME); @Override public String getProtocol() { diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHCodec.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHCodec.java index 1acc149c..0484b572 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHCodec.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHCodec.java @@ -66,8 +66,8 @@ public class ITCHCodec extends AbstractCodec { private final Map msgTypeToMsgStruct = new HashMap<>(); private final MessageStructureReader msgStructReader = new MessageStructureReader(); - private final MessageStructureWriter msgStructWriter = new MessageStructureWriter();; - private final ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; + private final MessageStructureWriter msgStructWriter = new MessageStructureWriter(); + private final ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; private IDictionaryStructure msgDictionary; private IMessageFactory msgFactory; @@ -92,13 +92,13 @@ public void init(IServiceContext serviceContext, ICommonSettings settings, IMess this.codecMessageFilter = new CodecMessageFilter(msettings.getFilterValues()); this.preprocessor = DefaultPreprocessor.loadPreprocessor(serviceContext, msettings.getDictionaryURI(), ITCH_PREPROCESSORS_MAPPING_FILE_URI, - this.getClass().getClassLoader()); + getClass().getClassLoader()); } if(codecMessageFilter != null) { codecMessageFilter.init(dictionary); } - this.msgTypeToMsgStruct.clear(); + msgTypeToMsgStruct.clear(); for(IMessageStructure msgStruct : dictionary.getMessages().values()) { Short msgType = getAttributeValue(msgStruct, ITCHMessageHelper.ATTRIBUTE_MESSAGE_TYPE); @@ -225,7 +225,7 @@ private boolean realDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput } } - if (!(someMsgDropped && messages.size() == 1 && (System.currentTimeMillis() - this.lastDecode < 2000))) { //Skip single "UnitHeader" + if(!(someMsgDropped && messages.size() == 1 && (System.currentTimeMillis() - lastDecode < 2000))) { //Skip single "UnitHeader" IMessage message = DefaultMessageFactory.getFactory().createMessage(ITCHMessageHelper.MESSAGELIST_NAME, ITCHMessageHelper.MESSAGELIST_NAMESPACE); message.addField(ITCHMessageHelper.SUBMESSAGES_FIELD_NAME, messages); @@ -253,13 +253,9 @@ public boolean doDecode(IoSession session, IoBuffer in, private int getMessageLength(IFieldStructure message) { int sum = 0; - for(IFieldStructure field : message.getFields().values()) { - if (field.isComplex()) { - sum+=getMessageLength(field); - } else { - sum += StructureUtils.getAttributeValue(field, ITCHVisitorBase.LENGTH_ATTRIBUTE); - } + for(IFieldStructure field : message.getFields().values()) { + sum += field.isComplex() ? getMessageLength(field) : StructureUtils.getAttributeValue(field, ITCHVisitorBase.LENGTH_ATTRIBUTE); } return sum; @@ -269,7 +265,7 @@ private void processMessagesLength(List messages) { int sumforHead = 0; for (Object message:messages) { IMessage m = (IMessage) message; - IFieldStructure structure = this.msgDictionary.getMessages().get(m.getName()); + IFieldStructure structure = msgDictionary.getMessages().get(m.getName()); if (structure == null) { throw new EPSCommonException("Could not find IMessageStructure for messageName=[" + m.getName() + "] Namespace=[" + m.getNamespace() + "]"); } @@ -312,10 +308,10 @@ public void encode(IoSession session, Object inMessage, ProtocolEncoderOutput ou Object fieldValue = messagesList.getField(ITCHMessageHelper.SUBMESSAGES_FIELD_NAME); - if (fieldValue == null && !messagesList.getName().equals("UnitHeader")) { + if(fieldValue == null && !"UnitHeader".equals(messagesList.getName())) { throw new NullPointerException("MessagesList didn't contain field: " + ITCHMessageHelper.SUBMESSAGES_FIELD_NAME); } - if (messagesList.getName().equals("UnitHeader")) { + if("UnitHeader".equals(messagesList.getName())) { fieldValue = new ArrayList(1); ((List)fieldValue).add(messagesList); } @@ -326,9 +322,7 @@ public void encode(IoSession session, Object inMessage, ProtocolEncoderOutput ou IoBuffer buffer = IoBuffer.allocate(DEFAULT_BUFFER_SIZE, false); ITCHVisitorEncode msgStructVisitor = new ITCHVisitorEncode(buffer, byteOrder); - - - if (this.msgDictionary == null) { + if(msgDictionary == null) { throw new NullPointerException("ITCH Encode: msgDictionary is not defined"); } @@ -340,7 +334,7 @@ public void encode(IoSession session, Object inMessage, ProtocolEncoderOutput ou String msgName = message.getName(); String msgNamespace = message.getNamespace(); - IMessageStructure msgStructure = this.msgDictionary.getMessages().get(msgName); + IMessageStructure msgStructure = msgDictionary.getMessages().get(msgName); if (msgStructure == null) { throw new EPSCommonException("Could not find IMessageStructure for messageName=[" + msgName + "] Namespace=[" + msgNamespace + "]"); diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHDeflateCodec.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHDeflateCodec.java index 4a718c48..222b6d3f 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHDeflateCodec.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHDeflateCodec.java @@ -15,6 +15,16 @@ ******************************************************************************/ package com.exactpro.sf.services.itch; +import java.nio.ByteOrder; +import java.util.Arrays; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.filter.codec.ProtocolDecoderOutput; +import org.apache.mina.filter.codec.ProtocolEncoderOutput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.common.codecs.AbstractCodec; import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.common.messages.structures.IDictionaryStructure; @@ -25,15 +35,6 @@ import com.jcraft.jzlib.Inflater; import com.jcraft.jzlib.JZlib; import com.jcraft.jzlib.ZStream; -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.ProtocolDecoderOutput; -import org.apache.mina.filter.codec.ProtocolEncoderOutput; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.nio.ByteOrder; -import java.util.Arrays; @SuppressWarnings("deprecation") public class ITCHDeflateCodec extends AbstractCodec { @@ -44,9 +45,9 @@ public class ITCHDeflateCodec extends AbstractCodec { private static final int DELIMITER_LENGTH = 2; - private Inflater inflater; + private final Inflater inflater = new Inflater(); - private byte[] uncompressed; + private final byte[] uncompressed = new byte[65536]; private byte[] delimiter; @@ -54,11 +55,7 @@ public ITCHDeflateCodec() { logger.debug("Instance created"); - this.inflater = new Inflater(); - - this.uncompressed = new byte[65536]; - - } + } @Override public void encode(IoSession session, Object message, @@ -75,7 +72,7 @@ public void init(IServiceContext serviceContext, ICommonSettings settings, this.delimiter = ((ITCHCodecSettings) settings).getChunkDelimiter(); - logger.debug("Delimiter is {}", this.delimiter); + logger.debug("Delimiter is {}", delimiter); } @@ -104,7 +101,7 @@ protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput if(! Arrays.equals(delimiter, actualDelimiter)) { - logger.error("Delimiter {} does not equeals to expected {}", actualDelimiter, this.delimiter); + logger.error("Delimiter {} does not equeals to expected {}", actualDelimiter, delimiter); } @@ -159,14 +156,12 @@ protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput private byte[] decompress(byte[] compressed){ - int err; - - int comprLen = compressed.length; + int comprLen = compressed.length; inflater.setInput(compressed); inflater.setOutput(uncompressed); - err = inflater.init(); + int err = inflater.init(); CHECK_ERR(inflater, err, "inflateInit"); while ( inflater.total_in < comprLen) { @@ -192,8 +187,9 @@ private byte[] decompress(byte[] compressed){ private void CHECK_ERR(ZStream z, int err, String msg) { if (err != JZlib.Z_OK) { - if (z.msg != null) - logger.error(z.msg); + if(z.msg != null) { + logger.error(z.msg); + } logger.error("{} error: {}", msg, err); throw new RuntimeException("Error on decode: " + msg + " error: " + err); } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHMessageHelper.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHMessageHelper.java index 032686f8..45ba613f 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHMessageHelper.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHMessageHelper.java @@ -52,7 +52,7 @@ public class ITCHMessageHelper extends MessageHelper { public static final String SUBMESSAGES_FIELD_NAME = "IncludedMessages"; public static final String MESSAGELIST_NAME = "MessagesList"; public static final String MESSAGELIST_NAMESPACE = "ITCH"; - public static final Short UNITHEADERMSGTYPE = new Short((short)256); + public static final Short UNITHEADERMSGTYPE = (short)256; public static final String FIELD_MARKET_DATA_GROUP_NAME = "MarketDataGroup"; public static final String FIELD_LENGTH_NAME = "Length"; public static final String ATTRIBUTE_LENGTH_NAME = FIELD_LENGTH_NAME; @@ -166,7 +166,7 @@ protected IMessageStructure getHeaderStructure(String messageNamespace){ public static List extractSubmessages(Object message) { if(message instanceof IMessage) { - return ((IMessage) message).>getField(ITCHMessageHelper.SUBMESSAGES_FIELD_NAME); + return ((IMessage)message).>getField(SUBMESSAGES_FIELD_NAME); } throw new EPSCommonException("Sent message is not an " + IMessage.class.getSimpleName()); diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHPreprocessor.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHPreprocessor.java index 4580784f..9cb21fe1 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHPreprocessor.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHPreprocessor.java @@ -15,14 +15,15 @@ ******************************************************************************/ package com.exactpro.sf.services.itch; -import com.exactpro.sf.common.messages.IMessage; -import com.exactpro.sf.common.messages.structures.IMessageStructure; -import com.exactpro.sf.util.LRUMap; +import java.math.BigDecimal; + import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.math.BigDecimal; +import com.exactpro.sf.common.messages.IMessage; +import com.exactpro.sf.common.messages.structures.IMessageStructure; +import com.exactpro.sf.util.LRUMap; public class ITCHPreprocessor extends DefaultPreprocessor { @@ -37,12 +38,12 @@ public void process(IMessage message, IoSession session, IMessageStructure struc // RM 25262 String msgName = message.getName(); - if (msgName.equals("AddOrder") || msgName.equals("AddAttributedOrder")) { + if("AddOrder".equals(msgName) || "AddAttributedOrder".equals(msgName)) { BigDecimal orderID = (BigDecimal) message.getField("OrderID"); Long instrumentID = (Long) message.getField("InstrumentID"); instruments.put(orderID, instrumentID); - } else if (msgName.equals("OrderModified") || msgName.equals("OrderExecuted") || msgName.equals("OrderExecutedWithPrice_Size")) { + } else if("OrderModified".equals(msgName) || "OrderExecuted".equals(msgName) || "OrderExecutedWithPrice_Size".equals(msgName)) { BigDecimal orderID = (BigDecimal) message.getField("OrderID"); Long instrumentID = instruments.get(orderID); diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHSession.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHSession.java index a5191fc1..36b423e4 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHSession.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHSession.java @@ -24,7 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger; public class ITCHSession extends MINASession { - private AtomicInteger seqnum = new AtomicInteger(0); + private final AtomicInteger seqnum = new AtomicInteger(0); private final byte marketDataGroup; diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTCPClientSettings.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTCPClientSettings.java index 87fe4c27..0165d7b5 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTCPClientSettings.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTCPClientSettings.java @@ -21,25 +21,25 @@ public class ITCHTCPClientSettings extends ITCHClientSettings { private static final long serialVersionUID = -5299816885595794380L; - private boolean doLiteLoginOnStart = false; + private boolean doLiteLoginOnStart; - private byte flag1 = 0; + private byte flag1; - private boolean sendHeartBeats = false; + private boolean sendHeartBeats; private int heartbeatTimeout = 5; private String username; - private boolean compressionUsed = false; + private boolean compressionUsed; private int compressedChunkDelimeter = 57005; - private boolean doLoginOnStart = false; + private boolean doLoginOnStart; - private boolean reconnecting = false; + private boolean reconnecting; - private boolean disposeWhenSessionClosed = false; + private boolean disposeWhenSessionClosed; private int reconnectingTimeout = 5000; diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTcpClient.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTcpClient.java index a231b5ad..f84c813a 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTcpClient.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHTcpClient.java @@ -15,6 +15,16 @@ ******************************************************************************/ package com.exactpro.sf.services.itch; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + import com.exactpro.sf.common.codecs.AbstractCodec; import com.exactpro.sf.common.codecs.CodecFactory; import com.exactpro.sf.common.messages.IMessage; @@ -28,25 +38,16 @@ import com.exactpro.sf.services.mina.AbstractMINATCPService; import com.exactpro.sf.services.mina.MINASession; import com.exactpro.sf.services.util.ServiceUtil; -import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; public class ITCHTcpClient extends AbstractMINATCPService implements IITCHClient { - private volatile boolean disconnecting = false; - private volatile boolean connectingFromMatrix = false; + private volatile boolean disconnecting; + private volatile boolean connectingFromMatrix; private volatile boolean reconecting; private volatile boolean disposeWhenSessionClosed; - private Runnable reconectCommand; - private Runnable sentHeartbeatCommand; + private final Runnable reconectCommand; + private final Runnable sentHeartbeatCommand; private int reconnectiongTimeout; private ITCHCodecSettings codecSettings; @@ -220,11 +221,11 @@ protected void disconnected0() { } if ( reconecting ) { - this.taskExecutor.schedule(reconectCommand, reconnectiongTimeout, TimeUnit.MILLISECONDS); - this.changeStatus(ServiceStatus.WARNING, "Connection was forcibly closed by the remote machine." + taskExecutor.schedule(reconectCommand, reconnectiongTimeout, TimeUnit.MILLISECONDS); + changeStatus(ServiceStatus.WARNING, "Connection was forcibly closed by the remote machine." + "Service will be reconnect after " + reconnectiongTimeout + " milliseconds"); } else { - this.changeStatus(ServiceStatus.ERROR, "Connection was forcibly closed by the remote machine"); + changeStatus(ServiceStatus.ERROR, "Connection was forcibly closed by the remote machine"); } } else { if (connectingFromMatrix) { @@ -240,9 +241,9 @@ protected void preDisconnect() throws Exception { } protected void sendLiteLogin() throws InterruptedException { - ITCHTCPClientSettings settings = this.getSettings(); + ITCHTCPClientSettings settings = getSettings(); - IMessage liteLogin = this.messageFactory.createMessage("LoginRequestLite", this.namespace); + IMessage liteLogin = messageFactory.createMessage("LoginRequestLite", namespace); liteLogin.addField("Username", settings.getUsername()); liteLogin.addField("Flag1", settings.getFlag1()); @@ -251,9 +252,9 @@ protected void sendLiteLogin() throws InterruptedException { } protected void sendLogin() throws InterruptedException { - ITCHTCPClientSettings settings = this.getSettings(); + ITCHTCPClientSettings settings = getSettings(); - IMessage liteLogin = this.messageFactory.createMessage("LoginRequest", this.namespace); + IMessage liteLogin = messageFactory.createMessage("LoginRequest", namespace); liteLogin.addField("Username", settings.getUsername()); @@ -267,8 +268,8 @@ protected void sendHeartBeat() throws InterruptedException { throw new ServiceException("Could not send a heartbeat. Client is not connected"); } - logger.info("Client sent UnitHeader with namespace {}", this.namespace); - IMessage unitHeader = this.messageFactory.createMessage("UnitHeader", this.namespace); + logger.info("Client sent UnitHeader with namespace {}", namespace); + IMessage unitHeader = messageFactory.createMessage("UnitHeader", namespace); unitHeader.addField("Length", 8); unitHeader.addField("MessageCount",(short) 0); @@ -281,7 +282,7 @@ protected void sendHeartBeat() throws InterruptedException { @Override protected void postConnect() throws Exception { super.postConnect(); - ITCHTCPClientSettings settings = this.getSettings(); + ITCHTCPClientSettings settings = getSettings(); if(settings.isDoLiteLoginOnStart()) { sendLiteLogin(); @@ -297,7 +298,7 @@ public void sessionIdle(IoSession session, IdleStatus status) throws Exception { super.sessionIdle(session, status); if(getSettings().isSendHeartBeats()) { - this.taskExecutor.schedule(sentHeartbeatCommand, 0, TimeUnit.MILLISECONDS); + taskExecutor.schedule(sentHeartbeatCommand, 0, TimeUnit.MILLISECONDS); } } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorBase.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorBase.java index 0e01f49a..3ac1a1e7 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorBase.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorBase.java @@ -39,13 +39,13 @@ public class ITCHVisitorBase extends DefaultMessageStructureVisitor { public static final String ISADMIN = "IsAdmin"; public static final String IMPILED_DECIMALS_ATTRIBUTE = "ImpliedDecimals"; - public static final UnsignedLong SIZE_DEVIDER = UnsignedLong.valueOf(100000000L); - public static final UnsignedLong SIZE4_DEVIDER = UnsignedLong.valueOf(10000L); + public static final UnsignedLong SIZE_DEVIDER = UnsignedLong.valueOf(100_000_000L); + public static final UnsignedLong SIZE4_DEVIDER = UnsignedLong.valueOf(10_000L); - public static final BigDecimal BD_SIZE_DEVIDER = new BigDecimal(100000000L); - public static final BigDecimal BD_PRICE_DEVIDER = new BigDecimal(100000000L); - public static final BigDecimal BD_UDT_DEVIDER = new BigDecimal(1000000000L); - public static final BigDecimal UDT_DEVIDER = new BigDecimal(1000000L); + public static final BigDecimal BD_SIZE_DEVIDER = new BigDecimal(100_000_000L); + public static final BigDecimal BD_PRICE_DEVIDER = new BigDecimal(100_000_000L); + public static final BigDecimal BD_UDT_DEVIDER = new BigDecimal(1_000_000_000L); + public static final BigDecimal UDT_DEVIDER = new BigDecimal(1_000_000L); protected static final String charsetName = "ISO-8859-1"; @@ -91,7 +91,7 @@ public enum ProtocolType { INT32("Int32"), INT64("Int64"); - private ProtocolType(String type) { + ProtocolType(String type) { } public static ProtocolType getEnum(String type) { diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorDecode.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorDecode.java index edc0e0fe..3bf8a4af 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorDecode.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorDecode.java @@ -228,7 +228,7 @@ public void visit(String fieldName, Double value, IFieldStructure fldStruct, boo reverseBytes(rawArray); } - final UnsignedLong divider = (type == ProtocolType.SIZE) ? SIZE_DEVIDER : SIZE4_DEVIDER; + UnsignedLong divider = (type == ProtocolType.SIZE) ? SIZE_DEVIDER : SIZE4_DEVIDER; double result = ServiceUtil.convertFromUint64(rawArray, divider); @@ -236,7 +236,7 @@ public void visit(String fieldName, Double value, IFieldStructure fldStruct, boo } else if (type == ProtocolType.PRICE || type == ProtocolType.PRICE4) { long val = buffer.getLong(); - boolean positive = ((byte) (val >> 63)) == 0; + boolean positive = (byte) (val >> 63) == 0; if (!positive) { long mask = 0x7FFFFFFFFFFFFFFFL; @@ -245,15 +245,10 @@ public void visit(String fieldName, Double value, IFieldStructure fldStruct, boo val = val * -1L; } - double valDouble; - if (type == ProtocolType.PRICE) { - valDouble = ServiceUtil.divide(val, 100000000L); - } else { - valDouble = ServiceUtil.divide(val, 10000L); - } + double valDouble = ServiceUtil.divide(val, type == ProtocolType.PRICE ? 100_000_000L : 10_000L); - msg.addField(fieldName, valDouble); + msg.addField(fieldName, valDouble); } else if (type == ProtocolType.UINT16) { BigDecimal val = new BigDecimal(buffer.getUnsignedShort()); @@ -371,7 +366,7 @@ public void visit(String fieldName, BigDecimal value, IFieldStructure fldStruct, } else if (type == ProtocolType.PRICE) { long val = buffer.getLong(); - boolean positive = ((byte) (val >> 63)) == 0; + boolean positive = (byte) (val >> 63) == 0; if (!positive) { long mask = 0x7FFFFFFFFFFFFFFFL; @@ -443,7 +438,7 @@ public void visit(String fieldName, LocalDate value, IFieldStructure fldStruct, throw new EPSCommonException("Incorrect field lenth = " + length + " for " + fieldName + " field"); } int days = buffer.getShort(); - msg.addField(fieldName, DateTimeUtility.toLocalDate(86400_000L * days)); + msg.addField(fieldName, DateTimeUtility.toLocalDate(86_400_000L * days)); } else if (type == ProtocolType.DATE) { byte[] array = new byte[length]; diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorEncode.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorEncode.java index a0b99f01..97924b47 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorEncode.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/ITCHVisitorEncode.java @@ -42,7 +42,7 @@ public class ITCHVisitorEncode extends ITCHVisitorBase { private final IoBuffer buffer; private final ByteOrder byteOrder; - private final static Byte DEFAULT_BYTE = 0x0; + private static final Byte DEFAULT_BYTE = 0x0; public ITCHVisitorEncode(IoBuffer buffer, ByteOrder byteOrder) { this.buffer = buffer; @@ -183,7 +183,7 @@ public void visit(String fieldName, Float value, IFieldStructure fldStruct, bool } if (type == ProtocolType.PRICE) { - int val = (int) (value.floatValue() * 10000); + int val = (int)(value.floatValue() * 10_000); buffer.putInt(val); } else { throw new EPSCommonException("Incorrect type = " + type + " for " + fieldName + " field"); @@ -201,10 +201,10 @@ public void visit(String fieldName, Double value, IFieldStructure fldStruct, boo } if (type == ProtocolType.PRICE || type == ProtocolType.SIZE) { - long val = (long) (value.doubleValue() * 100000000); + long val = (long)(value.doubleValue() * 100_000_000); buffer.putLong(val); } else if (type == ProtocolType.PRICE4 || type == ProtocolType.SIZE4) { - long val = (long) (value.doubleValue() * 10000); + long val = (long)(value.doubleValue() * 10_000); buffer.putLong(val); } else if (type == ProtocolType.UINT16) { double val = value.doubleValue(); @@ -242,7 +242,7 @@ public void visit(String fieldName, LocalDate value, IFieldStructure fldStruct, tryToFillDefaultBytes(type, value, fieldName, length); if (type == ProtocolType.DAYS) { - buffer.putShort((short) (DateTimeUtility.getMillisecond(value) / 86400_000L)); + buffer.putShort((short)(DateTimeUtility.getMillisecond(value) / 86_400_000L)); } else if (type == ProtocolType.DATE) { String temp = value.format(dateFormatter); buffer.put(temp.getBytes()); @@ -287,7 +287,7 @@ public void visit(String fieldName, BigDecimal value, IFieldStructure fldStruct, } buffer.putLong(val); } else if (type == ProtocolType.PRICE || type == ProtocolType.SIZE) { - long val = (long) (value.doubleValue() * 100000000); + long val = (long)(value.doubleValue() * 100_000_000); buffer.putLong(val); } else if (type == ProtocolType.UDT) { byte[] longArray = new byte[length]; diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/MessageLevelType.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/MessageLevelType.java index f66ad4de..b68b44d0 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/MessageLevelType.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/MessageLevelType.java @@ -18,5 +18,5 @@ public enum MessageLevelType { Admin, - Application; + Application } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHCodecFactory.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHCodecFactory.java index 4495f83d..03b73ebc 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHCodecFactory.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHCodecFactory.java @@ -15,14 +15,14 @@ ******************************************************************************/ package com.exactpro.sf.services.itch.multicast; - -import com.exactpro.sf.services.IServiceContext; -import com.exactpro.sf.services.MessageHelper; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; +import com.exactpro.sf.services.IServiceContext; +import com.exactpro.sf.services.MessageHelper; + /** * Created by alexey.zarovny on 11/29/14. */ @@ -38,11 +38,11 @@ public ITCHCodecFactory(IServiceContext serviceContext, MessageHelper itchHandle @Override public ProtocolEncoder getEncoder(IoSession ioSession) throws Exception { - return itchHandler.getCodec(this.serviceContext); + return itchHandler.getCodec(serviceContext); } @Override public ProtocolDecoder getDecoder(IoSession ioSession) throws Exception { - return itchHandler.getCodec(this.serviceContext); + return itchHandler.getCodec(serviceContext); } } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastCache.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastCache.java index e7f3c945..32b0689b 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastCache.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastCache.java @@ -15,11 +15,15 @@ ******************************************************************************/ package com.exactpro.sf.services.itch.multicast; -import com.exactpro.sf.common.messages.IMessage; - -import java.util.*; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; +import com.exactpro.sf.common.messages.IMessage; + /** * Created by alexey.zarovny on 11/28/14. */ @@ -27,7 +31,7 @@ public class ITCHMulticastCache { private final int limit; private final Map> cacheMap; - private AtomicInteger size; + private final AtomicInteger size; public enum Status { REQUEST_ACCEPTED, @@ -38,15 +42,15 @@ public enum Status { public ITCHMulticastCache(int limit) { cacheMap = new HashMap<>(); - if (limit == 0) + if(limit == 0) { throw new NullPointerException("Cache limit must not be null"); + } this.limit = limit; size = new AtomicInteger(0); } public void add(int seqNumber, IMessage message, byte mdGroup) { - Map mdGroupCache; - mdGroupCache = cacheMap.get(mdGroup); + Map mdGroupCache = cacheMap.get(mdGroup); if (mdGroupCache == null) { mdGroupCache = new TreeMap<>(); cacheMap.put(mdGroup, mdGroupCache); @@ -77,14 +81,17 @@ public Status getMessages(Integer startSeqNumber, int quantity, byte mdGroup, Li Map mdGroupCache = cacheMap.get(mdGroup); - if (mdGroupCache == null) - return Status.INVALID_MARKET_DATA_GROUP; + if(mdGroupCache == null) { + return Status.INVALID_MARKET_DATA_GROUP; + } - if (mdGroupCache.size() < quantity) - return Status.OUT_OF_RANGE; + if(mdGroupCache.size() < quantity) { + return Status.OUT_OF_RANGE; + } - if ((Integer) mdGroupCache.keySet().iterator().next() > startSeqNumber) - return Status.REPLAY_UNAVAILABLE; + if((Integer)mdGroupCache.keySet().iterator().next() > startSeqNumber) { + return Status.REPLAY_UNAVAILABLE; + } Iterator it = mdGroupCache.keySet().iterator(); int i = 0; @@ -96,10 +103,6 @@ public Status getMessages(Integer startSeqNumber, int quantity, byte mdGroup, Li } } - - if (result.size() < quantity) { - return Status.OUT_OF_RANGE; - } - return Status.REQUEST_ACCEPTED; + return result.size() < quantity ? Status.OUT_OF_RANGE : Status.REQUEST_ACCEPTED; } } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastServer.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastServer.java index 0d619b01..955ffe6c 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastServer.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastServer.java @@ -15,13 +15,22 @@ ******************************************************************************/ package com.exactpro.sf.services.itch.multicast; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import org.apache.mina.core.service.IoHandlerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.exactpro.sf.aml.script.actions.WaitAction; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.common.messages.MsgMetaData; import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.services.ServiceInfo; import com.exactpro.sf.common.services.ServiceName; -import com.exactpro.sf.aml.script.actions.WaitAction; import com.exactpro.sf.configuration.ILoggingConfigurator; import com.exactpro.sf.scriptrunner.actionmanager.actioncontext.IActionContext; import com.exactpro.sf.services.IInitiatorService; @@ -38,20 +47,12 @@ import com.exactpro.sf.services.itch.ITCHMessageHelper; import com.exactpro.sf.services.util.ServiceUtil; import com.exactpro.sf.storage.IMessageStorage; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; /** * Created by alexey.zarovny on 11/18/14. */ public class ITCHMulticastServer extends IoHandlerAdapter implements IInitiatorService { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private volatile ServiceStatus curStatus; private ServiceName serviceName; @@ -76,16 +77,17 @@ public class ITCHMulticastServer extends IoHandlerAdapter implements IInitiatorS @Override public void init( IServiceContext serviceContext, - final IServiceMonitor serviceMonitor, - final IServiceHandler handler, - final IServiceSettings settings, - final ServiceName name) { + IServiceMonitor serviceMonitor, + IServiceHandler handler, + IServiceSettings settings, + ServiceName name) { try { this.serviceName = name; - if (settings == null) + if(settings == null) { throw new NullPointerException("'settings' parameter is null"); + } this.settings = (ITCHMulticastSettings) settings; @@ -99,8 +101,9 @@ public void init( this.logConfigurator = Objects.requireNonNull(this.serviceContext.getLoggingConfigurator(), "'Logging configurator' parameter is null"); if (!((this.settings.getPrimaryAddress() != null && this.settings.getPrimaryPort() != 0) - || (this.settings.getSecondaryAddress() != null && this.settings.getSecondaryPort() != 0))) + || (this.settings.getSecondaryAddress() != null && this.settings.getSecondaryPort() != 0))) { throw new NullPointerException("At least one of address/port pairs must be set"); + } this.msgFactory = this.serviceContext.getDictionaryManager().getMessageFactory(this.settings.getDictionaryName()); @@ -110,7 +113,7 @@ public void init( Objects.requireNonNull(dictionary, "'Dictionary' parameter"); itchHandler = new ITCHMessageHelper(); - itchHandler.init(this.msgFactory, this.dictionary); + itchHandler.init(msgFactory, dictionary); this.udpSession = new ITCHMulticastUDPSession(this.serviceContext, serviceName + "UDP", settings.getDictionaryName(), this.settings.getMarketDataGroup(), this, itchHandler, msgFactory); @@ -120,11 +123,11 @@ public void init( this.handler = Objects.requireNonNull(handler, "'Service handler' parameter"); logger.info("Initiliazing service {} ... done", this); - this.changeStatus(ServiceStatus.INITIALIZED, "Service initialized", null); + changeStatus(ServiceStatus.INITIALIZED, "Service initialized", null); } catch (Throwable t) { - logger.error("Exception during service [{}] initializing", this.serviceName, t); - this.changeStatus(ServiceStatus.ERROR, "", t); - throw new ServiceException("Problem during service [" + this.serviceName + "] initializing", t); + logger.error("Exception during service [{}] initializing", serviceName, t); + changeStatus(ServiceStatus.ERROR, "", t); + throw new ServiceException("Problem during service [" + serviceName + "] initializing", t); } } @@ -141,18 +144,18 @@ public void connect() throws Exception { @Override public void start() { - logConfigurator.createIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.createIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); try { cache = new ITCHMulticastCache(settings.getCacheSize()); udpSession.open(settings.getPrimaryPort(), settings.getPrimaryAddress(), settings.getSecondaryPort(), settings.getSecondaryAddress(), cache); tcpSession.open(settings.getTcpPort(), cache); - this.changeStatus(ServiceStatus.STARTED, "Service started", null); + changeStatus(ServiceStatus.STARTED, "Service started", null); } catch (IOException e) { - logger.error("Exception during service [{}] starting", this.serviceName, e); - this.changeStatus(ServiceStatus.ERROR, "", e); - throw new ServiceException("Problem during service [" + this.serviceName + "] starting", e); + logger.error("Exception during service [{}] starting", serviceName, e); + changeStatus(ServiceStatus.ERROR, "", e); + throw new ServiceException("Problem during service [" + serviceName + "] starting", e); } } @@ -165,13 +168,13 @@ public void dispose() { if(tcpSession != null){ tcpSession.close(); } - this.changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); + changeStatus(ServiceStatus.DISPOSED, "Service disposed", null); } catch (Exception e) { - logger.error("Exception during service [{}] disposing", this.serviceName, e); - this.changeStatus(ServiceStatus.ERROR, "", e); - throw new ServiceException("Problem during service [" + this.serviceName + "] disposing", e); + logger.error("Exception during service [{}] disposing", serviceName, e); + changeStatus(ServiceStatus.ERROR, "", e); + throw new ServiceException("Problem during service [" + serviceName + "] disposing", e); } finally { - logConfigurator.destroyIndividualAppender(this.getClass().getName() + "@" + Integer.toHexString(hashCode()), + logConfigurator.destroyIndividualAppender(getClass().getName() + "@" + Integer.toHexString(hashCode()), serviceName); } } @@ -224,25 +227,21 @@ void handleMessage(boolean isFrom, boolean isAdmin, IMessage iMessage, ISession MsgMetaData metaData = msg.getMetaData(); if (isFrom) { - metaData.setToService(this.serviceName.toString()); + metaData.setToService(serviceName.toString()); metaData.setFromService(remoteName); } else { - metaData.setFromService(this.serviceName.toString()); + metaData.setFromService(serviceName.toString()); metaData.setToService(remoteName); } metaData.setServiceInfo(serviceInfo); if (settings.isStoreMessages()) { - this.msgStorage.storeMessage(msg); - } - - if (isFrom) { - logger.debug("Message received: {} ", msg); - } else { - logger.debug("Message sent: {} ", msg); + msgStorage.storeMessage(msg); } + logger.debug(isFrom ? "Message received: {} " : "Message sent: {} ", msg); + try { if (isAdmin && isFrom) { logger.debug("Add fromAdmin: {}", msg.getName()); @@ -250,10 +249,10 @@ void handleMessage(boolean isFrom, boolean isAdmin, IMessage iMessage, ISession } else if (!isAdmin && isFrom) { logger.debug("Add fromApp: {}", msg.getName()); handler.putMessage(iSession, ServiceHandlerRoute.FROM_APP, msg); - } else if (!isAdmin && !isFrom) { + } else if(!isAdmin) { logger.debug("Add toApp: {}", msg.getName()); handler.putMessage(iSession, ServiceHandlerRoute.TO_APP, msg); - } else if (!isAdmin && !isFrom) { + } else { logger.debug("Add toAdmin: {}", msg.getName()); handler.putMessage(iSession, ServiceHandlerRoute.TO_ADMIN, msg); } diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPHandlerAdapter.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPHandlerAdapter.java index 0e529f2c..cceacde7 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPHandlerAdapter.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPHandlerAdapter.java @@ -15,6 +15,17 @@ ******************************************************************************/ package com.exactpro.sf.services.itch.multicast; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.common.util.EPSCommonException; @@ -23,16 +34,7 @@ import com.exactpro.sf.services.ITaskExecutor; import com.exactpro.sf.services.MessageHelper; import com.exactpro.sf.services.itch.ITCHMessageHelper; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.exactpro.sf.services.itch.multicast.ITCHMulticastCache.Status; /** * Created by alexey.zarovny on 11/29/14. @@ -47,7 +49,7 @@ public class ITCHMulticastTCPHandlerAdapter extends IoHandlerAdapter { public static final String COUNT = "Count"; public static final String STATUS = "Status"; public static final String LOGIN_RESPONSE = "LoginResponse"; - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private final ITCHMulticastCache cache; private final ITCHMulticastServer service; @@ -55,9 +57,9 @@ public class ITCHMulticastTCPHandlerAdapter extends IoHandlerAdapter { private final int sessionIdleTimeout; private final int loginTimeout; private final IMessageFactory msgFactory; - private ITaskExecutor taskExecutor; + private final ITaskExecutor taskExecutor; private final byte mdGroup; - private MessageHelper itchHandler; + private final MessageHelper itchHandler; public ITCHMulticastTCPHandlerAdapter(ITCHMulticastCache cache, SailfishURI dictionaryURI, ITaskExecutor taskExecutor, ITCHMulticastServer service, ISession iSession, byte mdGroup, MessageHelper itchHandler, IMessageFactory msgFactory) { @@ -101,9 +103,9 @@ public void exceptionCaught(IoSession session, Throwable cause) { } @Override - public void messageReceived(final IoSession session, Object message) { + public void messageReceived(IoSession session, Object message) { if (message instanceof IMessage) { - final IMessage iMsg = (IMessage) message; + IMessage iMsg = (IMessage)message; if (ITCHMessageHelper.MESSAGELIST_NAME.equals(iMsg.getName())) { taskExecutor.addTask(new Runnable() { @@ -151,11 +153,11 @@ private IMessage onLogout(IMessage iMessage, IoSession session) { private IMessage onReplay(IMessage iMessage, IoSession session) { Object firstMessage = iMessage.getField(FIRST_MESSAGE); Object count = iMessage.getField(COUNT); - final Object marketDataGroup = iMessage.getField(MARKET_DATA_GROUP); + Object marketDataGroup = iMessage.getField(MARKET_DATA_GROUP); List messageList = new ArrayList<>(); IMessage result = msgFactory.createMessage(REPLAY_RESPONSE, iMessage.getNamespace()); result.addField(MARKET_DATA_GROUP, marketDataGroup); - ITCHMulticastCache.Status status = ITCHMulticastCache.Status.REQUEST_ACCEPTED; + Status status = Status.REQUEST_ACCEPTED; if (firstMessage != null && count != null) { logger.debug("ReplayRequest works"); status = cache.getMessages(Integer.valueOf(firstMessage.toString()), (Integer) count, new Byte(marketDataGroup.toString()), messageList); @@ -189,7 +191,7 @@ private IMessage onReplay(IMessage iMessage, IoSession session) { result = itchHandler.prepareMessageToEncode(result, params); session.write(result); handleMessage(result, false, false, session.getRemoteAddress().toString()); - if (status == ITCHMulticastCache.Status.REQUEST_ACCEPTED) { + if(status == Status.REQUEST_ACCEPTED) { for(IMessage msg:messageList){ session.write(msg); handleMessage(msg, false, false, session.getRemoteAddress().toString()); @@ -205,8 +207,7 @@ private void handleMessage(IMessage iMessage, boolean isFrom, boolean isAdmin, S private IMessage onLogon(IMessage iMessage, IoSession session) { handleMessage(iMessage, true, true, session.getRemoteAddress().toString()); - IMessage loginResponse; - loginResponse = msgFactory.createMessage(LOGIN_RESPONSE, iMessage.getNamespace()); + IMessage loginResponse = msgFactory.createMessage(LOGIN_RESPONSE, iMessage.getNamespace()); if (iMessage.getField("Username") != null && iMessage.getField("Password") != null) { loginResponse.addField(STATUS, toShort('A')); } else { diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPSession.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPSession.java index 510bd637..72714bbf 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPSession.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastTCPSession.java @@ -15,6 +15,11 @@ ******************************************************************************/ package com.exactpro.sf.services.itch.multicast; +import java.io.IOException; +import java.net.InetSocketAddress; + +import org.apache.mina.filter.codec.ProtocolCodecFilter; + import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.configuration.suri.SailfishURI; @@ -22,10 +27,6 @@ import com.exactpro.sf.services.ISession; import com.exactpro.sf.services.MessageHelper; import com.exactpro.sf.services.WrapperNioSocketAcceptor; -import org.apache.mina.filter.codec.ProtocolCodecFilter; - -import java.io.IOException; -import java.net.InetSocketAddress; /** * Created by alexey.zarovny on 11/19/14. @@ -40,7 +41,7 @@ public class ITCHMulticastTCPSession implements ISession { private int port; private WrapperNioSocketAcceptor acceptor; private boolean isClosed; - private MessageHelper itchHandler; + private final MessageHelper itchHandler; public ITCHMulticastTCPSession(IServiceContext serviceContext, String serviceName, SailfishURI dictionaryURI, ITCHMulticastServer service, MessageHelper itchHandler, IMessageFactory factory) { this.name = serviceName + "TCPSession"; @@ -55,9 +56,9 @@ public ITCHMulticastTCPSession(IServiceContext serviceContext, String serviceNam public void open(int port, ITCHMulticastCache cache) throws IOException { this.port = port; - acceptor = new WrapperNioSocketAcceptor(this.serviceContext.getTaskExecutor()); - acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ITCHCodecFactory(this.serviceContext, itchHandler))); - acceptor.setHandler(new ITCHMulticastTCPHandlerAdapter(cache, dictionaryURI, this.serviceContext.getTaskExecutor(), service, this, ((ITCHMulticastSettings) service.getSettings()).getMarketDataGroup(), itchHandler, factory)); + acceptor = new WrapperNioSocketAcceptor(serviceContext.getTaskExecutor()); + acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ITCHCodecFactory(serviceContext, itchHandler))); + acceptor.setHandler(new ITCHMulticastTCPHandlerAdapter(cache, dictionaryURI, serviceContext.getTaskExecutor(), service, this, ((ITCHMulticastSettings)service.getSettings()).getMarketDataGroup(), itchHandler, factory)); acceptor.setReuseAddress(true); acceptor.bind(new InetSocketAddress(this.port)); isClosed = false; @@ -83,7 +84,7 @@ public IMessage sendDirty(Object message) { @Override public void close() { if (acceptor != null) { - acceptor.unbind(new InetSocketAddress(this.port)); + acceptor.unbind(new InetSocketAddress(port)); acceptor.dispose(); } isClosed = true; diff --git a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastUDPSession.java b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastUDPSession.java index 3d9d63db..1ef28f66 100644 --- a/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastUDPSession.java +++ b/BackEnd/Service/service-itch/src/main/java/com/exactpro/sf/services/itch/multicast/ITCHMulticastUDPSession.java @@ -15,6 +15,27 @@ ******************************************************************************/ package com.exactpro.sf.services.itch.multicast; +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.MulticastSocket; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.DefaultWriteFuture; +import org.apache.mina.core.future.WriteFuture; +import org.apache.mina.core.session.DummySession; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.filter.codec.AbstractProtocolEncoderOutput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.common.codecs.AbstractCodec; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMessageFactory; @@ -27,53 +48,33 @@ import com.exactpro.sf.services.ITaskExecutor; import com.exactpro.sf.services.MessageHelper; import com.exactpro.sf.services.itch.ITCHMessageHelper; -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.DefaultWriteFuture; -import org.apache.mina.core.future.WriteFuture; -import org.apache.mina.core.session.DummySession; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.filter.codec.AbstractProtocolEncoderOutput; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.MulticastSocket; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; /** * Created by alexey.zarovny on 11/18/14. */ public class ITCHMulticastUDPSession implements ISession { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName() + "@" + Integer.toHexString(hashCode())); + private final Logger logger = LoggerFactory.getLogger(getClass().getName() + "@" + Integer.toHexString(hashCode())); private final String name; private final SailfishURI dictionaryURI; private final ITCHMulticastServer service; private final int heartbeatInterval; - private AbstractCodec codec; + private final AbstractCodec codec; private DatagramSocket udpPrimarySocket; private DatagramSocket udpSecondarySocket; - private InetAddress primaryAddress = null; - private InetAddress secondaryAddress = null; - private int primaryPort = 0; - private int secondaryPort = 0; + private InetAddress primaryAddress; + private InetAddress secondaryAddress; + private int primaryPort; + private int secondaryPort; private final IMessageFactory msgFactory; - private AtomicInteger sequenceNumber = new AtomicInteger(1); - private byte marketDataGroup; + private final AtomicInteger sequenceNumber = new AtomicInteger(1); + private final byte marketDataGroup; private ITCHMulticastCache cache; private final IoSession dummySession; private Future heartbeatFuture; - private String remoteName; - private MessageHelper itchHandler; + private final String remoteName; + private final MessageHelper itchHandler; private final IServiceContext serviceContext; @@ -94,7 +95,7 @@ public ITCHMulticastUDPSession(IServiceContext serviceContext, String name, Sail private void runHeartBeatTimer() { ITaskExecutor taskExecutor = service.getTaskExecutor(); - heartbeatFuture = taskExecutor.addRepeatedTask(new HeartBeatTimerTask(this.serviceContext, this), 0L, heartbeatInterval, TimeUnit.SECONDS); + heartbeatFuture = taskExecutor.addRepeatedTask(new HeartBeatTimerTask(serviceContext, this), 0L, heartbeatInterval, TimeUnit.SECONDS); } @Override @@ -111,10 +112,11 @@ public IMessage send(Object message) throws InterruptedException { ProtocolEncoder pdOut = new ProtocolEncoder(dummySession); IMessage iMsg = (IMessage) message; byte mdGroup = 0; - if (iMsg.getField(ITCHMessageHelper.FAKE_FIELD_UH_MARKET_DATA_GROUP) != null) + if(iMsg.getField(ITCHMessageHelper.FAKE_FIELD_UH_MARKET_DATA_GROUP) != null) { mdGroup = Byte.valueOf(Byte.valueOf(iMsg.getField(ITCHMessageHelper.FAKE_FIELD_UH_MARKET_DATA_GROUP).toString())); + } mdGroup = mdGroup != 0 ? mdGroup : marketDataGroup; - final byte marketDataGroup = mdGroup; + byte marketDataGroup = mdGroup; @SuppressWarnings("serial") Map params = new HashMap(){{ put(ITCHMessageHelper.FIELD_MARKET_DATA_GROUP_NAME, String.valueOf(marketDataGroup)); @@ -168,8 +170,9 @@ public void open(int primaryPort, String primaryAddress, int secondaryPort, Stri @Override public void close() { - if(heartbeatFuture != null) + if(heartbeatFuture != null) { heartbeatFuture.cancel(true); + } if (udpPrimarySocket != null) { udpPrimarySocket.close(); diff --git a/BackEnd/Service/service-itch/src/test/java/com/exactpro/sf/services/itch/TestITCHClientNegative.java b/BackEnd/Service/service-itch/src/test/java/com/exactpro/sf/services/itch/TestITCHClientNegative.java index c5f3680c..7a443481 100644 --- a/BackEnd/Service/service-itch/src/test/java/com/exactpro/sf/services/itch/TestITCHClientNegative.java +++ b/BackEnd/Service/service-itch/src/test/java/com/exactpro/sf/services/itch/TestITCHClientNegative.java @@ -15,17 +15,19 @@ ******************************************************************************/ package com.exactpro.sf.services.itch; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.services.CollectorServiceHandler; import com.exactpro.sf.services.ServiceException; import com.exactpro.sf.services.ServiceStatus; import com.exactpro.sf.util.TestITCHClientBase; + import junit.framework.Assert; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class TestITCHClientNegative extends TestITCHClientBase { @@ -121,7 +123,7 @@ public void testConnectToNotStartedServer() throws Exception { try { server.dispose(); long time = DISCONNECT_WAITING_TIMEOUT + System.currentTimeMillis(); - while(System.currentTimeMillis()