diff --git a/.classpath b/.classpath deleted file mode 100644 index 075b839..0000000 --- a/.classpath +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000..9b9378c --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,68 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ master ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ master ] + schedule: + - cron: '15 0 * * 6' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + language: [ 'java' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + - name: Cache Maven packages + uses: actions/cache@v2 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + - name: Set up Java + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Build + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + run: mvn -B clean package + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index e7d65c0..e295577 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -38,17 +38,27 @@ jobs: uses: actions/setup-java@v1 with: java-version: 11 + server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml + server-username: OSSRH_USERNAME # env variable for username in deploy + server-password: OSSRH_PASSWORD # env variable for token in deploy - name: Build and analyze + run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar - - - run: mkdir staging && cp target/*.jar staging + BUILD_NUMBER: ${{ github.run_id }}-${{ github.run_number }} - name: Upload Maven build artifact - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v2 with: name: artifact - path: staging \ No newline at end of file + path: target/*.jar + + # Upload if develop branch + - name: Upload snapshot to OSSRH if development release + if: ${{ github.ref == 'refs/heads/develop' && github.event_name == 'push' }} + run: mvn deploy --batch-mode --update-snapshots -P !sign,!build-extras,deploy-ossrh -Dmaven.test.skip=true -DskipChecks -DskipTest + env: + OSSRH_USERNAME: ${{ secrets.OSSRH_JIRA_USERNAME }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_JIRA_PASSWORD }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 100df23..9bacfac 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,21 @@ -/target/ -local-upload.bat +.antlr* +.classpath +.idea +.project +.DS_Store +*.iml +npm-debug.log +.build.log + +.metadata/ bin/ +target/ +src-gen/ +xtend-gen/ +.history/ + +*/plugin.xml_gen +**/.settings/org.eclipse.* + +.vscode +.factorypath \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 086bdba..0000000 --- a/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - de.csdev.ebus - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - - diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 7934df7..0000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,8 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/java/de/csdev/ebus/core/EBusWorkerThreadFactory.java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding//src/main/resources/manufactures.json=UTF-8 -encoding//src/test/java=UTF-8 -encoding//src/test/resources=UTF-8 -encoding/=UTF-8 diff --git a/.settings/org.eclipse.core.runtime.prefs b/.settings/org.eclipse.core.runtime.prefs deleted file mode 100644 index 5a0ad22..0000000 --- a/.settings/org.eclipse.core.runtime.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -line.separator=\n diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index c809b82..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,117 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullable.secondary= -org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.APILeak=warning -org.eclipse.jdt.core.compiler.problem.annotatedTypeArgumentToUnannotated=info -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning -org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=error -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=error -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.suppressWarningsNotFullyAnalysed=info -org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning -org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled -org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=warning -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.release=enabled -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/.settings/org.eclipse.pde.core.prefs b/.settings/org.eclipse.pde.core.prefs deleted file mode 100644 index e8ff8be..0000000 --- a/.settings/org.eclipse.pde.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -pluginProject.equinox=false -pluginProject.extensions=false -resolve.requirebundle=false diff --git a/CHANGELOG.md b/CHANGELOG.md index 4690391..87f80e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ All notable changes to this project will be documented in this file. ## Unreleased +## [1.1.3] - 2020-12-25 +### Changed +- Changed many line of code to fix sonarlint/cloud issues +- Add more ``final`` to parameters +- Changed to Java 8 syntax like Lambda expressions or Multi-Exceptions +- Fixed one or two wrong handled Interrupts + ## [1.1.2] - 2020-12-17 ### Added - Added ``sonarcloud`` to build pipeline diff --git a/pom.xml b/pom.xml index 245a774..348e601 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ eBUS core library - This library handles the communication with heating engineering via the BUS specification. This protocol is used by many heating manufacturers in Europe. de.cs-dev.ebus ebus-core - 1.1.2 + 1.1.3 https://github.com/csowada/ebus bundle @@ -18,7 +18,7 @@ 1.8 8 2020 - + ${project.version} csowada_ebus csowada https://sonarcloud.io @@ -102,7 +102,7 @@ org.apache.felix maven-bundle-plugin - 1.4.0 + 3.0.1 true @@ -300,7 +300,7 @@ junit junit - 4.12 + 4.13.1 test diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index 3130950..0000000 --- a/sonar-project.properties +++ /dev/null @@ -1,6 +0,0 @@ -sonar.organization=csowada -sonar.projectKey=csowada_ebus - -# relative paths to source directories. More details and properties are described -# in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/ -sonar.sources=. \ No newline at end of file diff --git a/src/main/java/de/csdev/ebus/cfg/EBusConfigurationReaderException.java b/src/main/java/de/csdev/ebus/cfg/EBusConfigurationReaderException.java index f451f91..c70abcb 100644 --- a/src/main/java/de/csdev/ebus/cfg/EBusConfigurationReaderException.java +++ b/src/main/java/de/csdev/ebus/cfg/EBusConfigurationReaderException.java @@ -18,19 +18,19 @@ public class EBusConfigurationReaderException extends Exception { private static final long serialVersionUID = 1L; - public EBusConfigurationReaderException(String message, Throwable cause, Object... args) { + public EBusConfigurationReaderException(final String message, final Throwable cause, final Object... args) { super(String.format(message, args), cause); } - public EBusConfigurationReaderException(String message, Object... args) { + public EBusConfigurationReaderException(final String message, final Object... args) { super(MessageFormat.format(message, args)); } - public EBusConfigurationReaderException(String message) { + public EBusConfigurationReaderException(final String message) { super(message); } - public EBusConfigurationReaderException(String message, Throwable cause) { + public EBusConfigurationReaderException(final String message, final Throwable cause) { super(message, cause); } diff --git a/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationProvider.java b/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationProvider.java index c277a1c..1d53d56 100644 --- a/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationProvider.java +++ b/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationProvider.java @@ -34,7 +34,7 @@ public interface IEBusConfigurationProvider { * @param configurationId * @return Returns a configuration label for an id or null if not existent. */ - public @Nullable String getConfigurationLabel(String configurationId); + public @Nullable String getConfigurationLabel(final String configurationId); /** * Returns the input stream for a configuration id or null if not existent. @@ -42,6 +42,6 @@ public interface IEBusConfigurationProvider { * @param configurationId * @return Returns the input stream for a configuration id or null if not existent. */ - public @Nullable InputStream getConfigurationStream(String configurationId); + public @Nullable InputStream getConfigurationStream(final String configurationId); } \ No newline at end of file diff --git a/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationReader.java b/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationReader.java index 1dab598..56b8159 100644 --- a/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationReader.java +++ b/src/main/java/de/csdev/ebus/cfg/IEBusConfigurationReader.java @@ -40,21 +40,21 @@ public interface IEBusConfigurationReader { * @throws EBusConfigurationReaderException * @throws IOException */ - public @Nullable IEBusCommandCollection loadConfigurationCollection(URL url) + public @Nullable IEBusCommandCollection loadConfigurationCollection(final URL url) throws EBusConfigurationReaderException, IOException; /** * @param url * @return */ - public List loadConfigurationCollectionBundle(URL url); + public List loadConfigurationCollectionBundle(final URL url); /** * Sets the eBUS type registry to use * * @param ebusTypes */ - public void setEBusTypes(EBusTypeRegistry ebusTypes); + public void setEBusTypes(final EBusTypeRegistry ebusTypes); /** * Clears all internal states diff --git a/src/main/java/de/csdev/ebus/cfg/std/EBusConfigurationReader.java b/src/main/java/de/csdev/ebus/cfg/std/EBusConfigurationReader.java index 9a1655d..4481e77 100644 --- a/src/main/java/de/csdev/ebus/cfg/std/EBusConfigurationReader.java +++ b/src/main/java/de/csdev/ebus/cfg/std/EBusConfigurationReader.java @@ -69,8 +69,8 @@ public class EBusConfigurationReader implements IEBusConfigurationReader { private @NonNull EBusTypeRegistry registry; - private @NonNull Map<@NonNull String, @Nullable Collection<@NonNull EBusCommandValue>> templateValueRegistry = new HashMap<@NonNull String, @Nullable Collection<@NonNull EBusCommandValue>>(); - private @NonNull Map<@NonNull String, @Nullable Collection<@NonNull EBusCommandValue>> templateBlockRegistry = new HashMap<@NonNull String, @Nullable Collection<@NonNull EBusCommandValue>>(); + private @NonNull Map<@NonNull String, @Nullable Collection<@NonNull EBusCommandValue>> templateValueRegistry = new HashMap<>(); + private @NonNull Map<@NonNull String, @Nullable Collection<@NonNull EBusCommandValue>> templateBlockRegistry = new HashMap<>(); public EBusConfigurationReader() { try { @@ -108,8 +108,7 @@ public EBusConfigurationReader() { Type merchantListType = new TypeToken>() { }.getType(); - Gson gson = new Gson(); - gson = new GsonBuilder().registerTypeAdapter(merchantListType, new EBusValueJsonDeserializer()).create(); + Gson gson = new GsonBuilder().registerTypeAdapter(merchantListType, new EBusValueJsonDeserializer()).create(); MessageDigest md = null; @@ -171,7 +170,7 @@ protected void parseTemplateConfiguration(@NonNull EBusCollectionDTO collection) List templateValues = templates.getTemplate(); if (templateValues != null) { - Collection blockList = new ArrayList(); + Collection blockList = new ArrayList<>(); for (EBusValueDTO value : templateValues) { if (value != null) { @@ -211,11 +210,11 @@ protected EBusCommand parseTelegramConfiguration(@NonNull IEBusCommandCollection Objects.requireNonNull(commandCollection, "commandCollection"); - LinkedHashMap templateMap = new LinkedHashMap(); - ArrayList templateList = new ArrayList(); + LinkedHashMap templateMap = new LinkedHashMap<>(); + ArrayList templateList = new ArrayList<>(); // collect available channels - List methods = new ArrayList(); + List methods = new ArrayList<>(); if (commandElement.getGet() != null) { methods.add("get"); } @@ -357,7 +356,7 @@ protected EBusCommand parseTelegramConfiguration(@NonNull IEBusCommandCollection Objects.requireNonNull(valueDto, "valueDto"); - Collection<@NonNull EBusCommandValue> result = new ArrayList<@NonNull EBusCommandValue>(); + Collection<@NonNull EBusCommandValue> result = new ArrayList<>(); String typeStr = valueDto.getType(); String collectionId = null; @@ -402,7 +401,6 @@ protected EBusCommand parseTelegramConfiguration(@NonNull IEBusCommandCollection } else if (templateMap != null) { // return the complete template block from within command block - // templateCollection = templateMap.values(); templateCollection = new ArrayList<>(templateList); } else { @@ -443,7 +441,7 @@ protected EBusCommand parseTelegramConfiguration(@NonNull IEBusCommandCollection } else if (templateMap != null && templateMap.containsKey(id)) { // return the complete template block from within command block - templateCollection = new ArrayList<@NonNull EBusCommandValue>(); + templateCollection = new ArrayList<>(); templateCollection.add(templateMap.get(id)); } else { @@ -474,7 +472,7 @@ protected EBusCommand parseTelegramConfiguration(@NonNull IEBusCommandCollection // convert static content to bytes byte[] byteArray = EBusUtils.toByteArray(valueDto.getDefault()); - Map properties = new HashMap(); + Map properties = new HashMap<>(); properties.put("length", byteArray.length); final IEBusType typeByte = registry.getType(EBusTypeBytes.TYPE_BYTES, properties); @@ -571,7 +569,7 @@ public void setEBusTypes(@NonNull EBusTypeRegistry ebusTypes) { Objects.requireNonNull(url, "url"); - List<@NonNull IEBusCommandCollection> result = new ArrayList<@NonNull IEBusCommandCollection>(); + List<@NonNull IEBusCommandCollection> result = new ArrayList<>(); Gson gson = new Gson(); Type type = new TypeToken>() { @@ -593,12 +591,10 @@ public void setEBusTypes(@NonNull EBusTypeRegistry ebusTypes) { try { logger.debug("Load configuration from url {} ...", fileUrl); IEBusCommandCollection collection = loadConfigurationCollection(fileUrl); - if (collection != null) { - result.add(collection); - } + result.add(collection); } catch (EBusConfigurationReaderException e) { - logger.error(e.getMessage() + " (Url: " + fileUrl + ")"); + logger.error("{} (url: {})", e.getMessage(), fileUrl); } catch (IOException e) { logger.error("error!", e); } @@ -607,11 +603,7 @@ public void setEBusTypes(@NonNull EBusTypeRegistry ebusTypes) { } } - } catch (JsonSyntaxException e) { - logger.error("error!", e); - } catch (JsonIOException e) { - logger.error("error!", e); - } catch (IOException e) { + } catch (JsonSyntaxException | JsonIOException | IOException e) { logger.error("error!", e); } diff --git a/src/main/java/de/csdev/ebus/cfg/std/EBusValueJsonDeserializer.java b/src/main/java/de/csdev/ebus/cfg/std/EBusValueJsonDeserializer.java index 52b5201..86fd388 100644 --- a/src/main/java/de/csdev/ebus/cfg/std/EBusValueJsonDeserializer.java +++ b/src/main/java/de/csdev/ebus/cfg/std/EBusValueJsonDeserializer.java @@ -45,9 +45,9 @@ public List deserialize(JsonElement jElement, Type typeOfT, JsonDe throws JsonParseException { JsonArray asJsonArray = jElement.getAsJsonArray(); - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); - ArrayList fields = new ArrayList(); + ArrayList fields = new ArrayList<>(); for (Field field : EBusValueDTO.class.getDeclaredFields()) { SerializedName annotation = field.getAnnotation(SerializedName.class); diff --git a/src/main/java/de/csdev/ebus/client/EBusClient.java b/src/main/java/de/csdev/ebus/client/EBusClient.java index 7788315..b81928f 100644 --- a/src/main/java/de/csdev/ebus/client/EBusClient.java +++ b/src/main/java/de/csdev/ebus/client/EBusClient.java @@ -40,6 +40,8 @@ */ public class EBusClient { + private static final String LABEL_LISTENER = "listener"; + private @NonNull EBusCommandRegistry commandRegistry; private @Nullable IEBusController controller; @@ -57,7 +59,7 @@ public class EBusClient { * * @param commandRegistry */ - public EBusClient(@NonNull EBusCommandRegistry commandRegistry) { + public EBusClient(final @NonNull EBusCommandRegistry commandRegistry) { Objects.requireNonNull(commandRegistry); @@ -76,8 +78,8 @@ public EBusClient(@NonNull EBusCommandRegistry commandRegistry) { * @param listener * @see de.csdev.ebus.service.device.EBusDeviceTable#addEBusDeviceTableListener(IEBusDeviceTableListener) */ - public void addEBusDeviceTableListener(@NonNull IEBusDeviceTableListener listener) { - Objects.requireNonNull(listener, "listener"); + public void addEBusDeviceTableListener(final @NonNull IEBusDeviceTableListener listener) { + Objects.requireNonNull(listener, LABEL_LISTENER); if (deviceTable != null) { deviceTable.addEBusDeviceTableListener(listener); } @@ -89,8 +91,8 @@ public void addEBusDeviceTableListener(@NonNull IEBusDeviceTableListener listene * @param listener * @see de.csdev.ebus.core.EBusControllerBase#addEBusEventListener(IEBusConnectorEventListener) */ - public void addEBusEventListener(@NonNull IEBusConnectorEventListener listener) { - Objects.requireNonNull(listener, "listener"); + public void addEBusEventListener(final @NonNull IEBusConnectorEventListener listener) { + Objects.requireNonNull(listener, LABEL_LISTENER); if (controller != null) { controller.addEBusEventListener(listener); } @@ -102,8 +104,8 @@ public void addEBusEventListener(@NonNull IEBusConnectorEventListener listener) * @param listener * @see de.csdev.ebus.client.EBusClient#addEBusParserListener(IEBusParserListener) */ - public void addEBusParserListener(@NonNull IEBusParserListener listener) { - Objects.requireNonNull(listener, "listener"); + public void addEBusParserListener(final @NonNull IEBusParserListener listener) { + Objects.requireNonNull(listener, LABEL_LISTENER); if (resolverService != null) { resolverService.addEBusParserListener(listener); } @@ -117,11 +119,10 @@ public void addEBusParserListener(@NonNull IEBusParserListener listener) { * @throws EBusControllerException * @see de.csdev.ebus.core.EBusLowLevelController#addToSendQueue(byte[]) */ - public @NonNull Integer addToSendQueue(byte @NonNull [] buffer) throws EBusControllerException { + public @NonNull Integer addToSendQueue(final byte @NonNull [] buffer) throws EBusControllerException { Objects.requireNonNull(buffer, "buffer"); - IEBusController controller = this.controller; if (controller == null) { throw new EBusControllerException("Controller not set!"); } @@ -138,14 +139,13 @@ public void addEBusParserListener(@NonNull IEBusParserListener listener) { * @throws EBusControllerException * @see de.csdev.ebus.core.EBusLowLevelController#addToSendQueue(byte[], int) */ - public @NonNull Integer addToSendQueue(byte @NonNull [] buffer, int maxAttemps) throws EBusControllerException { + public @NonNull Integer addToSendQueue(final byte @NonNull [] buffer, final int maxAttemps) throws EBusControllerException { - IEBusController controller = this.controller; - if (controller == null) { + if (this.controller == null) { throw new EBusControllerException("Controller not set!"); } - return controller.addToSendQueue(buffer, maxAttemps); + return this.controller.addToSendQueue(buffer, maxAttemps); } /** @@ -157,8 +157,8 @@ public void addEBusParserListener(@NonNull IEBusParserListener listener) { * @throws EBusTypeException * @throws EBusCommandException */ - public @NonNull ByteBuffer buildTelegram(@NonNull IEBusCommandMethod commandMethod, - @NonNull Byte destinationAddress, @Nullable Map values) + public @NonNull ByteBuffer buildTelegram(final @NonNull IEBusCommandMethod commandMethod, + final @NonNull Byte destinationAddress, final @Nullable Map values) throws EBusTypeException, EBusCommandException { Objects.requireNonNull(commandMethod, "commandMethod"); @@ -174,7 +174,7 @@ public void addEBusParserListener(@NonNull IEBusParserListener listener) { * @param controller * @param masterAddress */ - public void connect(@NonNull IEBusController controller, byte masterAddress) { + public void connect(final @NonNull IEBusController controller, final byte masterAddress) { Objects.requireNonNull(controller, "Parameter controller can't be null!"); @@ -200,38 +200,26 @@ public void connect(@NonNull IEBusController controller, byte masterAddress) { public void dispose() { if (controller != null) { controller.interrupt(); - // controller = null; } - // if (commandRegistry != null) { - // commandRegistry = null; - // } - if (deviceTableService != null) { deviceTableService.dispose(); - // deviceTableService = null; } if (deviceTable != null) { deviceTable.dispose(); - // deviceTable = null; } if (resolverService != null) { resolverService.dispose(); - // resolverService = null; } - - // if (metricsService != null) { - // metricsService = null; - // } } /** * @param id * @return */ - public @Nullable IEBusCommandCollection getCommandCollection(@NonNull String id) { + public @Nullable IEBusCommandCollection getCommandCollection(final @NonNull String id) { Objects.requireNonNull(id); return getConfigurationProvider().getCommandCollection(id); } @@ -304,7 +292,7 @@ public void dispose() { * @return * @see de.csdev.ebus.service.device.EBusDeviceTable#removeEBusDeviceTableListener(IEBusDeviceTableListener) */ - public boolean removeEBusDeviceTableListener(@NonNull IEBusDeviceTableListener listener) { + public boolean removeEBusDeviceTableListener(final @NonNull IEBusDeviceTableListener listener) { Objects.requireNonNull(listener); return getDeviceTable().removeEBusDeviceTableListener(listener); } @@ -316,7 +304,7 @@ public boolean removeEBusDeviceTableListener(@NonNull IEBusDeviceTableListener l * @return * @see de.csdev.ebus.core.EBusControllerBase#removeEBusEventListener(IEBusConnectorEventListener) */ - public boolean removeEBusEventListener(@NonNull IEBusConnectorEventListener listener) { + public boolean removeEBusEventListener(final @NonNull IEBusConnectorEventListener listener) { Objects.requireNonNull(listener); if (controller != null) { @@ -332,7 +320,7 @@ public boolean removeEBusEventListener(@NonNull IEBusConnectorEventListener list * @return * @see de.csdev.ebus.client.EBusClient#removeEBusParserListener(IEBusParserListener) */ - public boolean removeEBusParserListener(@NonNull IEBusParserListener listener) { + public boolean removeEBusParserListener(final @NonNull IEBusParserListener listener) { Objects.requireNonNull(listener); return getResolverService().removeEBusParserListener(listener); } diff --git a/src/main/java/de/csdev/ebus/command/EBusCommand.java b/src/main/java/de/csdev/ebus/command/EBusCommand.java index 60a83c7..73c9b5c 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommand.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommand.java @@ -28,8 +28,7 @@ @NonNullByDefault public class EBusCommand implements IEBusCommand { - private Map channels = new EnumMap( - IEBusCommandMethod.Method.class); + private Map channels = new EnumMap<>(IEBusCommandMethod.Method.class); private @Nullable String configurationSource; @@ -139,7 +138,7 @@ public void setParentCollection(IEBusCommandCollection parentCollection) { public void setProperties(Map properties) { Objects.requireNonNull(properties, "properties"); - this.properties = new HashMap(); + this.properties = new HashMap<>(); this.properties.putAll(properties); } diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandCollection.java b/src/main/java/de/csdev/ebus/command/EBusCommandCollection.java index aa9d6d5..3cc8593 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandCollection.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandCollection.java @@ -17,6 +17,7 @@ import java.util.Objects; import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import de.csdev.ebus.utils.CollectionUtils; @@ -25,46 +26,41 @@ * @author Christian Sowada - Initial contribution * */ +@NonNullByDefault public class EBusCommandCollection implements IEBusCommandCollection { - private @NonNull Map commands = new HashMap(); + private @NonNull Map commands = new HashMap<>(); private @NonNull String description; private @NonNull String id; - private @NonNull List identification = new ArrayList(); + private @NonNull List identification = new ArrayList<>(); private @NonNull String label; - private @NonNull Map properties; + private @NonNull Map properties = new HashMap<>(); private byte[] sourceHash; - public EBusCommandCollection(String id, String label, String description, Map properties) { + public EBusCommandCollection(final String id, final String label, final String description, final Map properties) { Objects.requireNonNull(id); Objects.requireNonNull(label); Objects.requireNonNull(description); + Objects.requireNonNull(properties); this.id = id; this.label = label; this.description = description; - - this.properties = new HashMap(); - - if (properties != null) { - // this.properties = CollectionUtils.newMapIfNull(this.properties); - this.properties.putAll(properties); - } - + this.properties.putAll(properties); } - public void addCommand(IEBusCommand command) { + public void addCommand(final IEBusCommand command) { this.commands.put(command.getId(), command); } - public void addCommands(List commands) { + public void addCommands(final List commands) { for (IEBusCommand command : commands) { addCommand(command); } @@ -137,18 +133,18 @@ public String getLabel() { * @see de.csdev.ebus.command.IEBusCommandCollection#getProperty(java.lang.String) */ @Override - public Object getProperty(String key) { + public Object getProperty(final String key) { return CollectionUtils.get(properties, key); } - public void setIdentification(@Nullable List identification) { + public void setIdentification(final @Nullable List identification) { if (identification != null && !identification.isEmpty()) { this.identification.clear(); this.identification.addAll(identification); } } - public void setSourceHash(byte[] sourceHash) { + public void setSourceHash(final byte[] sourceHash) { this.sourceHash = sourceHash; } @@ -159,7 +155,7 @@ public String toString() { } @Override - public IEBusCommand getCommand(String id) { + public IEBusCommand getCommand(final String id) { return commands.get(id); } diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandException.java b/src/main/java/de/csdev/ebus/command/EBusCommandException.java index 714136d..dea0723 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandException.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandException.java @@ -22,19 +22,19 @@ public EBusCommandException() { super(); } - public EBusCommandException(String message, Throwable cause) { + public EBusCommandException(final String message, final Throwable cause) { super(message, cause); } - public EBusCommandException(String message) { + public EBusCommandException(final String message) { super(message); } - public EBusCommandException(String message, Object... args) { + public EBusCommandException(final String message, final Object... args) { super(MessageFormat.format(message, args)); } - public EBusCommandException(Throwable cause) { + public EBusCommandException(final Throwable cause) { super(cause); } diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandMethod.java b/src/main/java/de/csdev/ebus/command/EBusCommandMethod.java index 8ce772f..b18b2f5 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandMethod.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandMethod.java @@ -60,7 +60,7 @@ public EBusCommandMethod(EBusCommand parent, IEBusCommandMethod.Method method) { */ public EBusCommandMethod addMasterValue(IEBusValue value) { if (masterTypes == null) { - masterTypes = new ArrayList<@NonNull IEBusValue>(); + masterTypes = new ArrayList<>(); } if (value != null) { @@ -77,7 +77,7 @@ public EBusCommandMethod addMasterValue(IEBusValue value) { */ public EBusCommandMethod addSlaveValue(IEBusValue value) { if (slaveTypes == null) { - slaveTypes = new ArrayList<@NonNull IEBusValue>(); + slaveTypes = new ArrayList<>(); } if (value != null) { diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandNestedValue.java b/src/main/java/de/csdev/ebus/command/EBusCommandNestedValue.java index a9bc33f..db4dab2 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandNestedValue.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandNestedValue.java @@ -21,7 +21,7 @@ */ public class EBusCommandNestedValue extends EBusCommandValue implements IEBusNestedValue { - private @NonNull List<@NonNull IEBusValue> list = new ArrayList<@NonNull IEBusValue>(); + private @NonNull List<@NonNull IEBusValue> list = new ArrayList<>(); @Override public void setParent(@Nullable EBusCommandMethod parent) { diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandRegistry.java b/src/main/java/de/csdev/ebus/command/EBusCommandRegistry.java index 11ee931..406b863 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandRegistry.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandRegistry.java @@ -41,7 +41,7 @@ public class EBusCommandRegistry { private final Logger logger = LoggerFactory.getLogger(EBusCommandRegistry.class); - private @NonNull Map collections = new HashMap(); + private @NonNull Map collections = new HashMap<>(); private @NonNull EBusTypeRegistry typeRegistry; @@ -62,7 +62,6 @@ public EBusCommandRegistry(Class readerClass * @param readerClass * @param loadBuildInCommands */ - @SuppressWarnings("null") public EBusCommandRegistry(Class readerClass, boolean loadBuildInCommands) { try { @@ -75,19 +74,7 @@ public EBusCommandRegistry(Class readerClass loadBuildInCommandCollections(); } - } catch (InstantiationException e) { - throw new IllegalStateException(e); - } catch (IllegalAccessException e) { - throw new IllegalStateException(e); - } catch (IllegalArgumentException e) { - throw new IllegalStateException(e); - } catch (InvocationTargetException e) { - throw new IllegalStateException(e); - } catch (NoSuchMethodException e) { - throw new IllegalStateException(e); - } catch (SecurityException e) { - throw new IllegalStateException(e); - } catch (EBusTypeException e) { + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | EBusTypeException e) { throw new IllegalStateException(e); } } @@ -98,7 +85,7 @@ public EBusCommandRegistry(Class readerClass public void loadBuildInCommandCollections() { List<@NonNull IEBusCommandCollection> loadBuildInConfigurations = reader.loadBuildInConfigurationCollections(); - if (loadBuildInConfigurations != null && !loadBuildInConfigurations.isEmpty()) { + if (!loadBuildInConfigurations.isEmpty()) { for (IEBusCommandCollection collection : loadBuildInConfigurations) { addCommandCollection(collection); } @@ -117,9 +104,7 @@ public void loadCommandCollection(@NonNull URL url) { try { addCommandCollection(reader.loadConfigurationCollection(url)); - } catch (EBusConfigurationReaderException e) { - logger.error("error!", e); - } catch (IOException e) { + } catch (EBusConfigurationReaderException | IOException e) { logger.error("error!", e); } @@ -132,9 +117,7 @@ public void loadCommandCollectionBundle(@NonNull URL url) { Objects.requireNonNull(url); - List<@NonNull IEBusCommandCollection> collections = reader.loadConfigurationCollectionBundle(url); - - for (IEBusCommandCollection collection : collections) { + for (IEBusCommandCollection collection : reader.loadConfigurationCollectionBundle(url)) { addCommandCollection(collection); } } @@ -156,7 +139,6 @@ public void addCommandCollection(IEBusCommandCollection collection) { * @param data The complete unescaped eBUS telegram * @return Returns the a list of all matching configuration methods or an empty list */ - @SuppressWarnings("null") public @NonNull List find(byte @NonNull [] data) { Objects.requireNonNull(data); @@ -175,7 +157,7 @@ public void addCommandCollection(IEBusCommandCollection collection) { Objects.requireNonNull(data); - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); for (IEBusCommandCollection collection : collections.values()) { for (IEBusCommand command : collection.getCommands()) { @@ -230,7 +212,6 @@ public void addCommandCollection(IEBusCommandCollection collection) { * * @return */ - @SuppressWarnings("null") public @NonNull List<@NonNull IEBusCommandCollection> getCommandCollections() { return Collections.unmodifiableList(new ArrayList(collections.values())); } @@ -273,11 +254,11 @@ public boolean matchesCommand(@NonNull IEBusCommandMethod command, @NonNull Byte Byte.valueOf((byte) 0x00)); // fast check - is this the right telegram type? - if (data.get(1) == EBusConsts.BROADCAST_ADDRESS && command.getType() != Type.BROADCAST) { - return false; - } else if (EBusUtils.isMasterAddress(data.get(1)) && command.getType() != Type.MASTER_MASTER) { - return false; - } else if (EBusUtils.isSlaveAddress(data.get(1)) && command.getType() != Type.MASTER_SLAVE) { + boolean isInvalidBroadcast = data.get(1) == EBusConsts.BROADCAST_ADDRESS && command.getType() != Type.BROADCAST; + boolean isInvalidMasterMaster = EBusUtils.isMasterAddress(data.get(1)) && command.getType() != Type.MASTER_MASTER; + boolean isInvalidMasterSlave = EBusUtils.isSlaveAddress(data.get(1)) && command.getType() != Type.MASTER_SLAVE; + + if (isInvalidBroadcast || isInvalidMasterMaster || isInvalidMasterSlave) { return false; } @@ -304,10 +285,13 @@ public boolean matchesCommand(@NonNull IEBusCommandMethod command, @NonNull Byte // is a broadcast or master-master telegram if (!EBusUtils.isSlaveAddress(data.get(1))) { - logger.warn( + if (logger.isWarnEnabled()) { + logger.warn( "Data for matching command configuration \"{}\" is not a master-slave telegram as expected!", EBusCommandUtils.getFullId(command)); - logger.warn("DATA: {}", EBusUtils.toHexDumpString(data)); + logger.warn("DATA: {}", EBusUtils.toHexDumpString(data)); + } + return false; // slave data is not defined in the configuration, not good! @@ -347,7 +331,7 @@ public boolean matchesCommand(@NonNull IEBusCommandMethod command, @NonNull Byte } } catch (Exception e) { logger.error("DATA: {}", EBusUtils.toHexDumpString(data)); - logger.error("CMD : {}", command.getParent().getParentCollection().getId(), command.getParent().getId()); + logger.error("CMD : {}, {}", command.getParent().getParentCollection().getId(), command.getParent().getId()); logger.error("error!", e); } diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandUtils.java b/src/main/java/de/csdev/ebus/command/EBusCommandUtils.java index 295deff..02f9620 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandUtils.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandUtils.java @@ -39,7 +39,11 @@ */ public class EBusCommandUtils { - private final static Logger logger = LoggerFactory.getLogger(EBusCommandUtils.class); + private static final Logger logger = LoggerFactory.getLogger(EBusCommandUtils.class); + + private EBusCommandUtils() { + throw new IllegalStateException("Utility class"); + } /** * Returns a full unique id to a method @@ -110,8 +114,10 @@ public class EBusCommandUtils { * @return */ public static byte unescapeSymbol(byte reversedByte) { - return reversedByte == (byte) 0x00 ? EBusConsts.ESCAPE - : reversedByte == (byte) 0x01 ? EBusConsts.SYN : reversedByte; + if (reversedByte == (byte) 0x00 ) { + return EBusConsts.ESCAPE; + } + return reversedByte == (byte) 0x01 ? EBusConsts.SYN : reversedByte; } /** @@ -120,7 +126,6 @@ public static byte unescapeSymbol(byte reversedByte) { * @param b The byte to escape * @return A escaped byte if required or the parameter byte as array */ - @SuppressWarnings("null") public static byte @NonNull [] escapeSymbol(byte b) { if (b == EBusConsts.ESCAPE) { return EBusConsts.ESCAPE_REPLACEMENT; @@ -143,7 +148,7 @@ public static byte unescapeSymbol(byte reversedByte) { * @throws EBusTypeException */ public static @NonNull ByteBuffer buildCompleteTelegram(byte source, byte target, byte[] command, byte[] masterData, - byte[] slaveData) throws EBusTypeException { + byte[] slaveData) { boolean isMastereMaster = EBusUtils.isMasterAddress(target); boolean isBroadcast = target == EBusConsts.BROADCAST_ADDRESS; @@ -188,7 +193,7 @@ public static byte unescapeSymbol(byte reversedByte) { * @throws EBusTypeException */ public static @NonNull ByteBuffer buildPartMasterTelegram(byte source, byte target, byte[] command, - byte[] masterData) throws EBusTypeException { + byte[] masterData) { ByteBuffer buf = ByteBuffer.allocate(50); @@ -221,14 +226,16 @@ public static byte unescapeSymbol(byte reversedByte) { * @return * @throws EBusTypeException */ - public static @NonNull ByteBuffer buildPartSlave(byte @NonNull [] slaveData) throws EBusTypeException { + public static @NonNull ByteBuffer buildPartSlave(byte @NonNull [] slaveData) { + + Objects.requireNonNull(slaveData, "slaveData"); ByteBuffer buf = ByteBuffer.allocate(50); buf.put(EBusConsts.ACK_OK); // ACK // if payload available - if (slaveData != null && slaveData.length > 0) { + if (slaveData.length > 0) { buf.put((byte) slaveData.length); // NN - Length // add the escaped bytes @@ -266,7 +273,7 @@ public static byte unescapeSymbol(byte reversedByte) { ByteBuffer buf = ByteBuffer.allocate(50); - Map> complexTypes = new HashMap>(); + Map> complexTypes = new HashMap<>(); List<@NonNull IEBusValue> masterTypes = commandMethod.getMasterTypes(); if (masterTypes != null) { @@ -283,7 +290,6 @@ public static byte unescapeSymbol(byte reversedByte) { int n = 0; for (int i = 0; i < list.size(); i++) { - @SuppressWarnings("null") IEBusValue childValue = list.get(i); if (values != null && values.containsKey(childValue.getName())) { Boolean object = (Boolean) values.get(childValue.getName()); @@ -319,11 +325,10 @@ public static byte unescapeSymbol(byte reversedByte) { } if (b == null) { - throw new RuntimeException("Encoded value is null! " + type.toString()); + throw new EBusTypeException("Encoded value is null! " + type.toString()); } - // buf.p + buf.put(b); - // len += type.getTypeLength(); } } @@ -369,7 +374,7 @@ public static byte unescapeSymbol(byte reversedByte) { @Nullable Byte source, @Nullable Byte target, @Nullable Map values, boolean skipAddressChecks) throws EBusTypeException, EBusCommandException { - Objects.requireNonNull(commandMethod, "Parameter command is null!"); + Objects.requireNonNull(commandMethod, "commandMethod"); if (source == null && commandMethod.getSourceAddress() != null) { source = commandMethod.getSourceAddress(); @@ -394,8 +399,10 @@ public static byte unescapeSymbol(byte reversedByte) { if (commandMethod.getType().equals(Type.BROADCAST)) { if (target != EBusConsts.BROADCAST_ADDRESS) { targetChecked = EBusConsts.BROADCAST_ADDRESS; - logger.warn("Replace target address {} with valid broadcast address 0xFE !", + if (logger.isWarnEnabled()) { + logger.warn("Replace target address {} with valid broadcast address 0xFE !", EBusUtils.toHexDumpString(target)); + } } } else if (commandMethod.getType().equals(Type.MASTER_MASTER)) { if (!EBusUtils.isMasterAddress(target)) { @@ -406,14 +413,16 @@ public static byte unescapeSymbol(byte reversedByte) { "Cannot replace the slave address 0x%s with a master address because it is a slave address without a master address.", EBusUtils.toHexDumpString(target))); } else { - logger.warn("Replace slave target address {} with valid master address {}!", + if (logger.isWarnEnabled()) { + logger.warn("Replace slave target address {} with valid master address {}!", EBusUtils.toHexDumpString(target), EBusUtils.toHexDumpString(targetChecked)); + } } } - } else if (commandMethod.getType().equals(Type.MASTER_SLAVE)) { - if (EBusUtils.isMasterAddress(target)) { - targetChecked = EBusUtils.getSlaveAddress(target); + } else if (commandMethod.getType().equals(Type.MASTER_SLAVE) && EBusUtils.isMasterAddress(target)) { + targetChecked = EBusUtils.getSlaveAddress(target); + if (logger.isWarnEnabled()) { logger.warn("Replace master target address {} with valid slave address {}!", EBusUtils.toHexDumpString(target), EBusUtils.toHexDumpString(targetChecked)); } @@ -425,9 +434,7 @@ public static byte unescapeSymbol(byte reversedByte) { } byte[] data = EBusUtils.toByteArray(composeMasterData(commandMethod, values)); - ByteBuffer byteBuffer = buildPartMasterTelegram(source, targetChecked, commandMethod.getCommand(), data); - - return byteBuffer; + return buildPartMasterTelegram(source, targetChecked, commandMethod.getCommand(), data); } /** @@ -451,15 +458,15 @@ public static byte unescapeSymbol(byte reversedByte) { decode = multiply; } - if (nev.getMin() != null && multiply.compareTo(nev.getMin()) == -1) { + if (nev.getMin() != null && multiply.compareTo(nev.getMin()) < 0) { logger.debug("Value {} with {} is smaller then allowed {}", - new Object[] { ev.getName(), multiply, nev.getMax() }); + ev.getName(), multiply, nev.getMax()); decode = null; } - if (nev.getMax() != null && multiply.compareTo(nev.getMax()) == 1) { + if (nev.getMax() != null && multiply.compareTo(nev.getMax()) > 0) { logger.debug("Value {} with {} is larger then allowed {}", - new Object[] { ev.getName(), multiply, nev.getMax() }); + ev.getName(), multiply, nev.getMax()); decode = null; } } @@ -535,17 +542,17 @@ private static int decodeValueList(@Nullable List<@NonNull IEBusValue> values, b public static @NonNull Map decodeTelegram(@NonNull IEBusCommandMethod commandChannel, byte @NonNull [] data) throws EBusTypeException { - Objects.requireNonNull(commandChannel, "Parameter command is null!"); - Objects.requireNonNull(data); + Objects.requireNonNull(commandChannel, "commandChannel"); + Objects.requireNonNull(data, "data"); - HashMap result = new HashMap(); + HashMap result = new HashMap<>(); int pos = 6; pos = decodeValueList(commandChannel.getMasterTypes(), data, result, pos); pos += 3; - pos = decodeValueList(commandChannel.getSlaveTypes(), data, result, pos); + decodeValueList(commandChannel.getSlaveTypes(), data, result, pos); return result; } @@ -558,7 +565,6 @@ private static int decodeValueList(@Nullable List<@NonNull IEBusValue> values, b Objects.requireNonNull(commandChannel, "Parameter command is null!"); - // byte len = 0; ByteBuffer buf = ByteBuffer.allocate(50); buf.put(commandChannel.getSourceAddress() == null ? (byte) 0x00 : (byte) 0xFF); // QQ - Source buf.put(commandChannel.getDestinationAddress() == null ? (byte) 0x00 : (byte) 0xFF); // ZZ - Target diff --git a/src/main/java/de/csdev/ebus/command/EBusCommandValue.java b/src/main/java/de/csdev/ebus/command/EBusCommandValue.java index 136711e..683346f 100644 --- a/src/main/java/de/csdev/ebus/command/EBusCommandValue.java +++ b/src/main/java/de/csdev/ebus/command/EBusCommandValue.java @@ -77,14 +77,14 @@ protected EBusCommandValue createInstance() { clone.type = this.type; if (this.mapping != null) { - clone.mapping = new HashMap(); + clone.mapping = new HashMap<>(); for (Entry elem : this.mapping.entrySet()) { clone.mapping.put(elem.getKey(), elem.getValue()); } } if (this.properties != null) { - clone.properties = new HashMap(); + clone.properties = new HashMap<>(); for (Entry elem : this.properties.entrySet()) { clone.properties.put(elem.getKey(), elem.getValue()); } @@ -190,7 +190,7 @@ public void setParent(@Nullable EBusCommandMethod parent) { } public void setProperties(Map properties) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); this.properties.putAll(properties); } diff --git a/src/main/java/de/csdev/ebus/command/IEBusCommand.java b/src/main/java/de/csdev/ebus/command/IEBusCommand.java index 0278990..b836d81 100644 --- a/src/main/java/de/csdev/ebus/command/IEBusCommand.java +++ b/src/main/java/de/csdev/ebus/command/IEBusCommand.java @@ -35,7 +35,7 @@ public interface IEBusCommand { * @param method * @return */ - public @Nullable IEBusCommandMethod getCommandMethod(IEBusCommandMethod.@NonNull Method method); + public @Nullable IEBusCommandMethod getCommandMethod(final IEBusCommandMethod.@NonNull Method method); /** * Returns the available command method enums. diff --git a/src/main/java/de/csdev/ebus/command/IEBusCommandMethod.java b/src/main/java/de/csdev/ebus/command/IEBusCommandMethod.java index d10631b..516ccef 100644 --- a/src/main/java/de/csdev/ebus/command/IEBusCommandMethod.java +++ b/src/main/java/de/csdev/ebus/command/IEBusCommandMethod.java @@ -23,7 +23,7 @@ public interface IEBusCommandMethod { /** * Type of the method */ - public static enum Type { + public enum Type { /** master slave telegram */ MASTER_SLAVE, @@ -39,7 +39,7 @@ public static enum Type { /** * Kind of the method */ - public static enum Method { + public enum Method { /** A getter command */ GET, diff --git a/src/main/java/de/csdev/ebus/command/datatypes/EBusAbstractType.java b/src/main/java/de/csdev/ebus/command/datatypes/EBusAbstractType.java index b919e0b..b4c87d5 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/EBusAbstractType.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/EBusAbstractType.java @@ -23,6 +23,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import de.csdev.ebus.core.EBusConsts; import de.csdev.ebus.utils.EBusUtils; /** @@ -33,7 +34,7 @@ public abstract class EBusAbstractType implements IEBusType { private static final Logger logger = LoggerFactory.getLogger(EBusAbstractType.class); - protected Map> otherInstances = new HashMap>(); + protected Map> otherInstances = new HashMap<>(); protected byte[] replaceValue = null; @@ -67,23 +68,13 @@ protected byte[] applyByteOrder(byte[] data) { private EBusAbstractType createNewInstance() { try { - @SuppressWarnings({ "unchecked", "null" }) + @SuppressWarnings({ "unchecked"}) EBusAbstractType newInstance = this.getClass().getDeclaredConstructor().newInstance(); newInstance.types = this.types; return newInstance; - } catch (InstantiationException e) { - logger.error("error!", e); - } catch (IllegalAccessException e) { - logger.error("error!", e); - } catch (IllegalArgumentException e) { - logger.error("error!", e); - } catch (InvocationTargetException e) { - logger.error("error!", e); - } catch (NoSuchMethodException e) { - logger.error("error!", e); - } catch (SecurityException e) { - logger.error("error!", e); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); } return null; @@ -123,7 +114,7 @@ private EBusAbstractType createNewInstance() { * @throws EBusTypeException */ public @Nullable T decodeInt(byte @Nullable [] data) throws EBusTypeException { - throw new RuntimeException("Must be overwritten by superclass!"); + throw new UnsupportedOperationException("Must be overwritten by superclass!"); } /* @@ -160,7 +151,7 @@ public byte[] encode(@Nullable Object data) throws EBusTypeException { * @throws EBusTypeException */ public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - throw new RuntimeException("Must be overwritten by superclass!"); + throw new UnsupportedOperationException("Must be overwritten by superclass!"); } /** @@ -187,7 +178,7 @@ public IEBusType getInstance(@Nullable Map properties) { } // Sort all members to have a reliable key - TreeMap sortedMap = new TreeMap(properties); + TreeMap sortedMap = new TreeMap<>(properties); String instanceKey = sortedMap.toString(); EBusAbstractType instance = otherInstances.get(instanceKey); @@ -252,7 +243,7 @@ protected void setInstanceProperty(@Nullable EBusAbstractType instance, @Null try { instance.setReplaceValue(EBusUtils.toByteArray((String) value)); } catch (EBusTypeException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } } @@ -266,12 +257,8 @@ protected void setInstanceProperty(@Nullable EBusAbstractType instance, @Null field.set(instance, value); } - } catch (SecurityException e) { - logger.error("error!", e); - } catch (IllegalArgumentException e) { - logger.error("error!", e); - } catch (IllegalAccessException e) { - logger.error("error!", e); + } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); } } diff --git a/src/main/java/de/csdev/ebus/command/datatypes/EBusTypeRegistry.java b/src/main/java/de/csdev/ebus/command/datatypes/EBusTypeRegistry.java index 40ac950..4efc645 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/EBusTypeRegistry.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/EBusTypeRegistry.java @@ -212,18 +212,7 @@ public void add(Class clazz) throws EBusTypeException { types.put(typeName, newInstance); } - } catch (InstantiationException e) { - logger.error("error!", e); - - } catch (IllegalAccessException e) { - logger.error("error!", e); - } catch (IllegalArgumentException e) { - logger.error("error!", e); - } catch (InvocationTargetException e) { - logger.error("error!", e); - } catch (NoSuchMethodException e) { - logger.error("error!", e); - } catch (SecurityException e) { + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { logger.error("error!", e); } } diff --git a/src/main/java/de/csdev/ebus/command/datatypes/ext/EBusTypeMultiWord.java b/src/main/java/de/csdev/ebus/command/datatypes/ext/EBusTypeMultiWord.java index fa2f1cb..af94cf1 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/ext/EBusTypeMultiWord.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/ext/EBusTypeMultiWord.java @@ -15,8 +15,8 @@ import de.csdev.ebus.command.datatypes.EBusAbstractType; import de.csdev.ebus.command.datatypes.EBusTypeException; import de.csdev.ebus.command.datatypes.std.EBusTypeWord; -import de.csdev.ebus.utils.EBusTypeUtils; import de.csdev.ebus.utils.EBusUtils; +import de.csdev.ebus.utils.NumberUtils; /** * @author Christian Sowada - Initial contribution @@ -72,7 +72,12 @@ public BigDecimal decodeInt(byte @Nullable [] data) throws EBusTypeException { @Override public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - BigDecimal value = EBusTypeUtils.toBigDecimal(data); + BigDecimal value = NumberUtils.toBigDecimal(data); + + if (value == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } + byte[] result = new byte[getTypeLength()]; int length = this.length - 1; diff --git a/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeNumber.java b/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeNumber.java index 957f538..0a77bb3 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeNumber.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeNumber.java @@ -16,7 +16,7 @@ import de.csdev.ebus.command.datatypes.EBusAbstractType; import de.csdev.ebus.command.datatypes.EBusTypeException; -import de.csdev.ebus.utils.EBusTypeUtils; +import de.csdev.ebus.utils.NumberUtils; public abstract class AbstractEBusTypeNumber extends EBusAbstractType { @@ -40,7 +40,11 @@ public BigDecimal decodeInt(byte @Nullable [] data) throws EBusTypeException { @Override public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - BigDecimal b = EBusTypeUtils.toBigDecimal(data == null ? 0 : data); + BigDecimal b = NumberUtils.toBigDecimal(data == null ? 0 : data); + + if (b == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } long l = b.longValue(); int length = getTypeLength(); diff --git a/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeUnsignedNumber.java b/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeUnsignedNumber.java index 64fe49e..57c1071 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeUnsignedNumber.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/std/AbstractEBusTypeUnsignedNumber.java @@ -16,7 +16,7 @@ import de.csdev.ebus.command.datatypes.EBusAbstractType; import de.csdev.ebus.command.datatypes.EBusTypeException; -import de.csdev.ebus.utils.EBusTypeUtils; +import de.csdev.ebus.utils.NumberUtils; /** * @author Christian Sowada - Initial contribution @@ -36,7 +36,12 @@ public BigDecimal decodeInt(byte @Nullable [] data) throws EBusTypeException { @Override public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - BigDecimal b = EBusTypeUtils.toBigDecimal(data == null ? 0 : data); + BigDecimal b = NumberUtils.toBigDecimal(data == null ? 0 : data); + + if (b == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } + long l = b.longValue() & Long.MAX_VALUE; int length = getTypeLength(); diff --git a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeBCD.java b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeBCD.java index 7a837af..1fbc336 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeBCD.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeBCD.java @@ -15,7 +15,6 @@ import de.csdev.ebus.command.datatypes.EBusAbstractType; import de.csdev.ebus.command.datatypes.EBusTypeException; -import de.csdev.ebus.utils.EBusTypeUtils; import de.csdev.ebus.utils.EBusUtils; import de.csdev.ebus.utils.NumberUtils; @@ -72,7 +71,11 @@ public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { final BigDecimal hundred = BigDecimal.valueOf(100); byte[] result = new byte[getTypeLength()]; - BigDecimal b = EBusTypeUtils.toBigDecimal(data); + BigDecimal b = NumberUtils.toBigDecimal(data); + + if (b == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } for (int i = 0; i < result.length; i++) { diff --git a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData1c.java b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData1c.java index dae9023..855548b 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData1c.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData1c.java @@ -13,8 +13,8 @@ import org.eclipse.jdt.annotation.Nullable; import de.csdev.ebus.command.datatypes.EBusTypeException; -import de.csdev.ebus.utils.EBusTypeUtils; import de.csdev.ebus.utils.EBusUtils; +import de.csdev.ebus.utils.NumberUtils; /** * @author Christian Sowada - Initial contribution @@ -44,7 +44,12 @@ public BigDecimal decodeInt(byte @Nullable [] data) throws EBusTypeException { @Override public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - BigDecimal b = EBusTypeUtils.toBigDecimal(data); + BigDecimal b = NumberUtils.toBigDecimal(data); + + if (b == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } + return super.encodeInt(b.multiply(BigDecimal.valueOf(2))); } diff --git a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2b.java b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2b.java index 7f11a47..0d1906c 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2b.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2b.java @@ -13,8 +13,8 @@ import org.eclipse.jdt.annotation.Nullable; import de.csdev.ebus.command.datatypes.EBusTypeException; -import de.csdev.ebus.utils.EBusTypeUtils; import de.csdev.ebus.utils.EBusUtils; +import de.csdev.ebus.utils.NumberUtils; /** * @author Christian Sowada - Initial contribution @@ -44,7 +44,12 @@ public BigDecimal decodeInt(byte @Nullable [] data) throws EBusTypeException { @Override public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - BigDecimal b = EBusTypeUtils.toBigDecimal(data); + BigDecimal b = NumberUtils.toBigDecimal(data); + + if (b == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } + return super.encodeInt(b.multiply(BigDecimal.valueOf(256))); } diff --git a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2c.java b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2c.java index 0d0f7cf..b2dd47b 100644 --- a/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2c.java +++ b/src/main/java/de/csdev/ebus/command/datatypes/std/EBusTypeData2c.java @@ -13,8 +13,8 @@ import org.eclipse.jdt.annotation.Nullable; import de.csdev.ebus.command.datatypes.EBusTypeException; -import de.csdev.ebus.utils.EBusTypeUtils; import de.csdev.ebus.utils.EBusUtils; +import de.csdev.ebus.utils.NumberUtils; /** * @author Christian Sowada - Initial contribution @@ -44,7 +44,12 @@ public BigDecimal decodeInt(byte @Nullable [] data) throws EBusTypeException { @Override public byte[] encodeInt(@Nullable Object data) throws EBusTypeException { - BigDecimal b = EBusTypeUtils.toBigDecimal(data); + BigDecimal b = NumberUtils.toBigDecimal(data); + + if (b == null) { + throw new EBusTypeException("Unable to convert input data to number!"); + } + return super.encodeInt(b.multiply(BigDecimal.valueOf(16))); } diff --git a/src/main/java/de/csdev/ebus/core/EBusConnectorEventListener.java b/src/main/java/de/csdev/ebus/core/EBusConnectorEventListener.java index 5ab1121..2719ed8 100644 --- a/src/main/java/de/csdev/ebus/core/EBusConnectorEventListener.java +++ b/src/main/java/de/csdev/ebus/core/EBusConnectorEventListener.java @@ -26,7 +26,7 @@ public class EBusConnectorEventListener implements IEBusConnectorEventListener { * @see de.csdev.ebus.core.IEBusConnectorEventListener#onTelegramReceived(byte[], java.lang.Integer) */ @Override - public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueId) { + public void onTelegramReceived(final byte[] receivedData, final @Nullable Integer sendQueueId) { // noop } @@ -37,7 +37,7 @@ public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueI * java.lang.Integer) */ @Override - public void onTelegramException(EBusDataException exception, @Nullable Integer sendQueueId) { + public void onTelegramException(final EBusDataException exception, final @Nullable Integer sendQueueId) { // noop } @@ -47,12 +47,12 @@ public void onTelegramException(EBusDataException exception, @Nullable Integer s * @see de.csdev.ebus.core.IEBusConnectorEventListener#onConnectionException(java.lang.Exception) */ @Override - public void onConnectionException(Exception e) { + public void onConnectionException(final Exception e) { // noop } @Override - public void onConnectionStatusChanged(ConnectionStatus status) { + public void onConnectionStatusChanged(final ConnectionStatus status) { // noop } } diff --git a/src/main/java/de/csdev/ebus/core/EBusConsts.java b/src/main/java/de/csdev/ebus/core/EBusConsts.java index a7f1475..d93f520 100644 --- a/src/main/java/de/csdev/ebus/core/EBusConsts.java +++ b/src/main/java/de/csdev/ebus/core/EBusConsts.java @@ -14,34 +14,39 @@ */ public class EBusConsts { - /** The Broadcast address */ - public final static byte BROADCAST_ADDRESS = (byte) 0xFE; + private EBusConsts() { + throw new IllegalStateException("Utility class"); + } - /** The ACK FAIL answer byte */ - public final static byte ACK_FAIL = (byte) 0xFF; + /** The Broadcast address 0xFE */ + public static final byte BROADCAST_ADDRESS = (byte) 0xFE; - /** The ACK OK answer byte */ - public final static byte ACK_OK = (byte) 0x00; + /** The ACK FAIL answer byte 0xFF */ + public static final byte ACK_FAIL = (byte) 0xFF; - /** The SYN byte */ - public final static byte SYN = (byte) 0xAA; + /** The ACK OK answer byte 0x00 */ + public static final byte ACK_OK = (byte) 0x00; - /** The escape byte for expanded bytes */ - public final static byte ESCAPE = (byte) 0xA9; + /** The SYN byte 0xAA */ + public static final byte SYN = (byte) 0xAA; + + /** The escape byte for expanded bytes 0xA9 */ + public static final byte ESCAPE = (byte) 0xA9; /** replacement for an excape symbol */ - public final static byte[] ESCAPE_REPLACEMENT = new byte[] { EBusConsts.ESCAPE, 0x00 }; + public static final byte[] ESCAPE_REPLACEMENT = new byte[] { EBusConsts.ESCAPE, 0x00 }; /** replacement for an sync symbol */ - public final static byte[] SYN_REPLACEMENT = new byte[] { EBusConsts.ESCAPE, 0x01 }; + public static final byte[] SYN_REPLACEMENT = new byte[] { EBusConsts.ESCAPE, 0x01 }; /** eBUS standard collection id */ - public final static String COLLECTION_STD = "std"; + public static final String COLLECTION_STD = "std"; - public final static String COMMAND_INQ_EXISTENCE = "common.inquiry_of_existence"; + public static final String COMMAND_INQ_EXISTENCE = "common.inquiry_of_existence"; - public final static String COMMAND_SIGN_OF_LIFE = "common.sign_of_life"; + public static final String COMMAND_SIGN_OF_LIFE = "common.sign_of_life"; - public final static String COMMAND_IDENTIFICATION = "common.identification"; + public static final String COMMAND_IDENTIFICATION = "common.identification"; + public static final String LOG_ERR_DEF = "error!"; } diff --git a/src/main/java/de/csdev/ebus/core/EBusControllerBase.java b/src/main/java/de/csdev/ebus/core/EBusControllerBase.java index 4348310..53388a1 100644 --- a/src/main/java/de/csdev/ebus/core/EBusControllerBase.java +++ b/src/main/java/de/csdev/ebus/core/EBusControllerBase.java @@ -31,11 +31,13 @@ public abstract class EBusControllerBase extends Thread implements IEBusControll private static final Logger logger = LoggerFactory.getLogger(EBusControllerBase.class); + private static final String THREADPOOL_NOT_READY = "ThreadPool not ready!"; + /** serial receive buffer */ protected @NonNull EBusReceiveStateMachine machine = new EBusReceiveStateMachine(); /** the list for listeners */ - private final @NonNull List listeners = new CopyOnWriteArrayList(); + private final @NonNull List listeners = new CopyOnWriteArrayList<>(); /** The thread pool to execute events without blocking */ private ExecutorService threadPool; @@ -56,7 +58,7 @@ public abstract class EBusControllerBase extends Thread implements IEBusControll * @see de.csdev.ebus.core.IEBusController#addToSendQueue(byte[], int) */ @Override - public @NonNull Integer addToSendQueue(byte @NonNull [] buffer, int maxAttemps) throws EBusControllerException { + public @NonNull Integer addToSendQueue(final byte @NonNull [] buffer, final int maxAttemps) throws EBusControllerException { if (getConnectionStatus() != ConnectionStatus.CONNECTED) { throw new EBusControllerException("Controller not connected, unable to add telegrams to send queue!"); } @@ -76,7 +78,7 @@ public abstract class EBusControllerBase extends Thread implements IEBusControll * @see de.csdev.ebus.core.IEBusController#addToSendQueue(byte[]) */ @Override - public @NonNull Integer addToSendQueue(byte @NonNull [] buffer) throws EBusControllerException { + public @NonNull Integer addToSendQueue(final byte @NonNull [] buffer) throws EBusControllerException { if (getConnectionStatus() != ConnectionStatus.CONNECTED) { throw new EBusControllerException("Controller not connected, unable to add telegrams to send queue!"); } @@ -96,7 +98,7 @@ public abstract class EBusControllerBase extends Thread implements IEBusControll * @see de.csdev.ebus.core.IEBusController#addEBusEventListener(de.csdev.ebus.core.IEBusConnectorEventListener) */ @Override - public void addEBusEventListener(@NonNull IEBusConnectorEventListener listener) { + public void addEBusEventListener(final @NonNull IEBusConnectorEventListener listener) { Objects.requireNonNull(listener); listeners.add(listener); } @@ -107,7 +109,7 @@ public void addEBusEventListener(@NonNull IEBusConnectorEventListener listener) * @see de.csdev.ebus.core.IEBusController#removeEBusEventListener(de.csdev.ebus.core.IEBusConnectorEventListener) */ @Override - public boolean removeEBusEventListener(@NonNull IEBusConnectorEventListener listener) { + public boolean removeEBusEventListener(final @NonNull IEBusConnectorEventListener listener) { Objects.requireNonNull(listener); return listeners.remove(listener); } @@ -124,21 +126,17 @@ protected void fireOnConnectionException(final @NonNull Exception e) { } if (threadPool == null || threadPool.isTerminated()) { - logger.warn("ThreadPool not ready!"); + logger.warn(THREADPOOL_NOT_READY); return; } - threadPool.execute(new Runnable() { - @Override - public void run() { - for (IEBusConnectorEventListener listener : listeners) { - try { - listener.onConnectionException(e); - } catch (Exception e) { - logger.error("Error while firing onConnectionException events!", e); - } + threadPool.execute(() -> { + for (IEBusConnectorEventListener listener : listeners) { + try { + listener.onConnectionException(e); + } catch (Exception e1) { + logger.error("Error while firing onConnectionException events!", e1); } - } }); } @@ -157,24 +155,21 @@ protected void fireOnEBusTelegramReceived(final byte @NonNull [] receivedData, f } if (threadPool == null || threadPool.isTerminated()) { - logger.warn("ThreadPool not ready! Can't fire onTelegramReceived events ..."); + logger.warn(THREADPOOL_NOT_READY + " Can't fire onTelegramReceived events ..."); return; } - if (receivedData == null || receivedData.length == 0) { - logger.warn("Telegram data is null or empty! Can't fire onTelegramReceived events ..."); + if (receivedData.length == 0) { + logger.warn("Telegram data is empty! Can't fire onTelegramReceived events ..."); return; } - threadPool.execute(new Runnable() { - @Override - public void run() { - for (IEBusConnectorEventListener listener : listeners) { - try { - listener.onTelegramReceived(receivedData, sendQueueId); - } catch (Exception e) { - logger.error("Error while firing onTelegramReceived events!", e); - } + threadPool.execute(() -> { + for (IEBusConnectorEventListener listener : listeners) { + try { + listener.onTelegramReceived(receivedData, sendQueueId); + } catch (Exception e) { + logger.error("Error while firing onTelegramReceived events!", e); } } }); @@ -193,19 +188,16 @@ protected void fireOnEBusDataException(final @NonNull EBusDataException exceptio } if (threadPool == null || threadPool.isTerminated()) { - logger.warn("ThreadPool not ready!"); + logger.warn(THREADPOOL_NOT_READY); return; } - threadPool.execute(new Runnable() { - @Override - public void run() { - for (IEBusConnectorEventListener listener : listeners) { - try { - listener.onTelegramException(exception, sendQueueId); - } catch (Exception e) { - logger.error("Error while firing onTelegramException events!", e); - } + threadPool.execute(() -> { + for (IEBusConnectorEventListener listener : listeners) { + try { + listener.onTelegramException(exception, sendQueueId); + } catch (Exception e) { + logger.error("Error while firing onTelegramException events!", e); } } }); @@ -214,7 +206,7 @@ public void run() { /** * @param status */ - protected void fireOnEBusConnectionStatusChange(@NonNull ConnectionStatus status) { + protected void fireOnEBusConnectionStatusChange(final @NonNull ConnectionStatus status) { Objects.requireNonNull(status); @@ -228,19 +220,16 @@ protected void fireOnEBusConnectionStatusChange(@NonNull ConnectionStatus status } if (threadPool == null || threadPool.isTerminated()) { - logger.warn("ThreadPool not ready!"); + logger.warn(THREADPOOL_NOT_READY); return; } - threadPool.execute(new Runnable() { - @Override - public void run() { - for (IEBusConnectorEventListener listener : listeners) { - try { - listener.onConnectionStatusChanged(status); - } catch (Exception e) { - logger.error("Error while firing fireOnEBusConnectionStatusChange events!", e); - } + threadPool.execute(() -> { + for (IEBusConnectorEventListener listener : listeners) { + try { + listener.onConnectionStatusChanged(status); + } catch (Exception e) { + logger.error("Error while firing fireOnEBusConnectionStatusChange events!", e); } } }); @@ -252,7 +241,7 @@ public void run() { protected void initThreadPool() { // create new thread pool to send received telegrams // limit the number of threads to 30 - threadPool = new ThreadPoolExecutor(0, 30, 60L, TimeUnit.SECONDS, new SynchronousQueue(), + threadPool = new ThreadPoolExecutor(0, 30, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new EBusWorkerThreadFactory("ebus-receiver", true)); // create watch dog thread pool @@ -260,9 +249,10 @@ protected void initThreadPool() { } /** + * @throws InterruptedException * */ - protected void shutdownThreadPool() { + protected void shutdownThreadPool() throws InterruptedException { // shutdown threadpool if (threadPool != null && !threadPool.isShutdown()) { threadPool.shutdownNow(); @@ -273,21 +263,15 @@ protected void shutdownThreadPool() { } if (threadPool != null) { - try { - // wait up to 10sec. for the thread pool - threadPool.awaitTermination(10, TimeUnit.SECONDS); - threadPool = null; - } catch (InterruptedException e) { - } + // wait up to 10sec. for the thread pool + threadPool.awaitTermination(10, TimeUnit.SECONDS); + threadPool = null; } if (threadPoolWDT != null) { - try { - // wait up to 10sec. for the thread pool - threadPoolWDT.awaitTermination(10, TimeUnit.SECONDS); - threadPoolWDT = null; - } catch (InterruptedException e) { - } + // wait up to 10sec. for the thread pool + threadPoolWDT.awaitTermination(10, TimeUnit.SECONDS); + threadPoolWDT = null; } } @@ -301,7 +285,7 @@ public boolean isRunning() { return !isInterrupted() && isAlive(); } - protected void dispose() { + protected void dispose() throws InterruptedException { listeners.clear(); @@ -314,12 +298,7 @@ protected void dispose() { } protected void resetWatchdogTimer() { - Runnable r = new Runnable() { - @Override - public void run() { - EBusControllerBase.this.fireWatchDogTimer(); - } - }; + Runnable r = EBusControllerBase.this::fireWatchDogTimer; if (watchdogTimer != null && !watchdogTimer.isCancelled()) { watchdogTimer.cancel(true); @@ -337,13 +316,13 @@ public void run() { * @see de.csdev.ebus.core.IEBusController#setWatchdogTimerTimeout(int) */ @Override - public void setWatchdogTimerTimeout(int seconds) { + public void setWatchdogTimerTimeout(final int seconds) { watchdogTimerTimeout = seconds; } protected abstract void fireWatchDogTimer(); - protected void setConnectionStatus(@NonNull ConnectionStatus status) { + protected void setConnectionStatus(final @NonNull ConnectionStatus status) { Objects.requireNonNull(status, "status"); @@ -355,4 +334,9 @@ protected void setConnectionStatus(@NonNull ConnectionStatus status) { public ConnectionStatus getConnectionStatus() { return this.connectionStatus; } + + @Override + public void run() { + throw new IllegalStateException("Method run() should be overwritten!"); + } } diff --git a/src/main/java/de/csdev/ebus/core/EBusControllerException.java b/src/main/java/de/csdev/ebus/core/EBusControllerException.java index 5352b54..faa1a2b 100644 --- a/src/main/java/de/csdev/ebus/core/EBusControllerException.java +++ b/src/main/java/de/csdev/ebus/core/EBusControllerException.java @@ -25,15 +25,15 @@ public EBusControllerException() { super(); } - public EBusControllerException(String message, Throwable cause) { + public EBusControllerException(final String message, final Throwable cause) { super(message, cause); } - public EBusControllerException(String message) { + public EBusControllerException(final String message) { super(message); } - public EBusControllerException(Throwable cause) { + public EBusControllerException(final Throwable cause) { super(cause); } diff --git a/src/main/java/de/csdev/ebus/core/EBusDataException.java b/src/main/java/de/csdev/ebus/core/EBusDataException.java index 58fb22a..4366e5d 100644 --- a/src/main/java/de/csdev/ebus/core/EBusDataException.java +++ b/src/main/java/de/csdev/ebus/core/EBusDataException.java @@ -51,40 +51,51 @@ public enum EBusError { */ private static final long serialVersionUID = 1L; - private EBusError error = EBusError.NONE; + private final EBusError error; - private byte[] data; + private final byte[] data; - private Integer sendId; + private final Integer sendId; public EBusDataException(String message) { super(message); + this.data = new byte[0]; + this.sendId = null; + this.error = EBusError.NONE; } public EBusDataException(String message, EBusError errorCode) { super(message); this.error = errorCode; + this.data = new byte[0]; + this.sendId = null; } public EBusDataException(String message, EBusError errorCode, byte[] data) { - this(message, errorCode); + super(message); + this.error = errorCode; this.data = data; + this.sendId = null; } public EBusDataException(String message, EBusError errorCode, ByteBuffer data) { - this(message, errorCode); + super(message); + this.error = errorCode; this.data = EBusUtils.toByteArray(data); + this.sendId = null; } public EBusDataException(String message, EBusError errorCode, byte[] data, int sendId) { - this(message, errorCode); + super(message); + this.error = errorCode; this.data = data; this.sendId = sendId; } public EBusDataException(String message, EBusError errorCode, ByteBuffer data, int sendId) { - this(message, errorCode); - this.data = EBusUtils.toByteArray(data); + super(message); + this.error = errorCode; + this.data = EBusUtils.toByteArray(data);; this.sendId = sendId; } @@ -103,7 +114,7 @@ public Integer getSendId() { @Override public String getMessage() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(super.getMessage()); sb.append(" ["); diff --git a/src/main/java/de/csdev/ebus/core/EBusEbusdController.java b/src/main/java/de/csdev/ebus/core/EBusEbusdController.java index fa4a5a6..55d69dd 100644 --- a/src/main/java/de/csdev/ebus/core/EBusEbusdController.java +++ b/src/main/java/de/csdev/ebus/core/EBusEbusdController.java @@ -97,7 +97,10 @@ public void run() { // count as send attempt queueEntry.sendAttempts++; - logger.trace("-->>|" + buildEbusdSendString(queueEntry.buffer) + "|"); + if (logger.isTraceEnabled()) { + logger.trace("-->>|{}|", buildEbusdSendString(queueEntry.buffer)); + } + writer.write(buildEbusdSendString(queueEntry.buffer) + "\n"); writer.flush(); @@ -112,7 +115,7 @@ public void run() { Thread.sleep(100); } catch (EBusDataException | IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } catch (InterruptedException e) { // re-enable the interrupt to stop the while loop @@ -131,7 +134,9 @@ private ByteBuffer parseLine(String readLine) throws IOException, InterruptedExc try { - logger.trace("<<--|" + readLine + "|"); + if (logger.isTraceEnabled()) { + logger.trace("<<--|{}|", readLine); + } if (readLine == null) { logger.error("End of stream has been reached!"); @@ -169,7 +174,7 @@ private ByteBuffer parseLine(String readLine) throws IOException, InterruptedExc } } catch (Exception e) { // do not stop because of version check - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } } else if (directMode) { @@ -292,14 +297,15 @@ public void run() { this.fireOnEBusDataException(e, currentSendId); } catch (InterruptedIOException e) { - // disable the interrupt, can be a simple java.net.SocketTimeoutException: Read timed out + // disable the interrupt, can be a simple java.net.SocketTimeoutException: Read + // timed out } catch (InterruptedException e) { // re-enable the interrupt to stop the while loop Thread.currentThread().interrupt(); } catch (IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); fireOnConnectionException(e); try { @@ -312,10 +318,15 @@ public void run() { } // while loop } catch (Exception e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } - dispose(); + try { + dispose(); + } catch (InterruptedException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); + Thread.currentThread().interrupt(); + } } @@ -429,7 +440,7 @@ private boolean connect() throws UnknownHostException, IOException { Thread.sleep(100); } catch (InterruptedException e) { - // noop + Thread.currentThread().interrupt(); } return true; @@ -445,7 +456,7 @@ protected void fireWatchDogTimer() { } @Override - protected void dispose() { + protected void dispose() throws InterruptedException { logger.debug("eBUS connection thread is shutting down ..."); diff --git a/src/main/java/de/csdev/ebus/core/EBusLowLevelController.java b/src/main/java/de/csdev/ebus/core/EBusLowLevelController.java index 2237a12..b40c3fb 100644 --- a/src/main/java/de/csdev/ebus/core/EBusLowLevelController.java +++ b/src/main/java/de/csdev/ebus/core/EBusLowLevelController.java @@ -146,7 +146,7 @@ private void reconnect() throws IOException, InterruptedException { * @return * @throws IOException */ - private boolean resend() throws IOException { + private boolean resend() { QueueEntry entry = queue.getCurrent(); @@ -178,7 +178,7 @@ public void run() { connection.open(); } } catch (IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); fireOnConnectionException(e); } @@ -215,9 +215,7 @@ public void run() { } } - } catch (InterruptedIOException e) { - Thread.currentThread().interrupt(); - } catch (InterruptedException e) { + } catch (InterruptedIOException | InterruptedException e) { Thread.currentThread().interrupt(); } catch (IOException e) { @@ -243,7 +241,12 @@ public void run() { } } // while loop - dispose(); + try { + dispose(); + } catch (InterruptedException e) { + logger.error("error!", e); + Thread.currentThread().interrupt(); + } } /** @@ -329,14 +332,15 @@ private void send(boolean secondTry) throws IOException { if (readByte == EBusConsts.SYN) { logger.debug("eBUS collision with SYN detected!"); } else { - logger.debug("eBUS collision detected! 0x{}", EBusUtils.toHexDumpString(readByte)); + if (logger.isDebugEnabled()) { + logger.debug("eBUS collision detected! 0x{}", EBusUtils.toHexDumpString(readByte)); + } } // last send try was a collision if (queue.isLastSendCollisionDetected()) { logger.warn("A second collision occured!"); queue.resetSendQueue(); - return; } // priority class identical else if ((byte) (readByte & 0x0F) == (byte) (b & 0x0F)) { @@ -381,8 +385,11 @@ else if ((byte) (readByte & 0x0F) == (byte) (b & 0x0F)) { return; } else if (b0 != b1) { - logger.warn("Received byte 0x{} is not equal to send byte 0x{}! Stop send attempt ...", - EBusUtils.toHexDumpString(b1), EBusUtils.toHexDumpString(b0)); + if (logger.isWarnEnabled()) { + logger.warn("Received byte 0x{} is not equal to send byte 0x{}! Stop send attempt ...", + EBusUtils.toHexDumpString(b1), EBusUtils.toHexDumpString(b0)); + } + queue.setBlockNextSend(true); return; } @@ -423,7 +430,10 @@ else if ((byte) (readByte & 0x0F) == (byte) (b & 0x0F)) { // after send process the received telegram if (sendMachine.isTelegramAvailable()) { - logger.debug("Succesful send: {}", sendMachine.toDumpString()); + if (logger.isDebugEnabled()) { + logger.debug("Succesful send: {}", sendMachine.toDumpString()); + } + fireOnEBusTelegramReceived(sendMachine.getTelegramData(), sendEntry.id); } @@ -442,7 +452,7 @@ else if ((byte) (readByte & 0x0F) == (byte) (b & 0x0F)) { } @Override - protected void dispose() { + protected void dispose() throws InterruptedException { logger.info("eBUS connection thread is shuting down ..."); @@ -459,7 +469,6 @@ protected void dispose() { try { if (connection != null) { connection.close(); - // connection = null; } } catch (IOException e) { logger.error(e.toString(), e); @@ -474,7 +483,7 @@ protected void fireWatchDogTimer() { try { connection.close(); } catch (IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } } } diff --git a/src/main/java/de/csdev/ebus/core/EBusQueue.java b/src/main/java/de/csdev/ebus/core/EBusQueue.java index ea16dc4..1c85556 100644 --- a/src/main/java/de/csdev/ebus/core/EBusQueue.java +++ b/src/main/java/de/csdev/ebus/core/EBusQueue.java @@ -29,11 +29,11 @@ public class EBusQueue { private static final Logger logger = LoggerFactory.getLogger(EBusQueue.class); - /** the send output queue */ - private final Queue outputQueue = new LinkedBlockingQueue(20); - /** eBUS lockout */ - private static int LOCKOUT_COUNTER_MAX = 3; + private static final int LOCKOUT_COUNTER_MAX = 3; + + /** the send output queue */ + private final Queue outputQueue = new LinkedBlockingQueue<>(20); /** data to send */ private QueueEntry sendEntry; diff --git a/src/main/java/de/csdev/ebus/core/EBusReceiveStateMachine.java b/src/main/java/de/csdev/ebus/core/EBusReceiveStateMachine.java index 50f0f32..2b3ec3c 100644 --- a/src/main/java/de/csdev/ebus/core/EBusReceiveStateMachine.java +++ b/src/main/java/de/csdev/ebus/core/EBusReceiveStateMachine.java @@ -172,11 +172,7 @@ public boolean isWaitingForMasterSYN() { return true; } - if (state.equals(State.ACK2)) { - return true; - } - - return false; + return state.equals(State.ACK2); } /** @@ -186,7 +182,7 @@ public void reset() { reset(false); } - private void reset(boolean ignoreState) { + private void reset(final boolean ignoreState) { len = 0; crc = 0; isEscapedByte = false; @@ -199,12 +195,14 @@ private void reset(boolean ignoreState) { } } - private void setState(State newState) { - logger.trace("Update state from " + state.name() + " to " + newState.name()); + private void setState(final State newState) { + if (logger.isTraceEnabled()) { + logger.trace("Update state from {} to {}", state.name(), newState.name()); + } state = newState; } - private void throwExceptionIfSYN(byte data) throws EBusDataException { + private void throwExceptionIfSYN(final byte data) throws EBusDataException { if (data == EBusConsts.SYN) { bb.put(data); throw new EBusDataException("Received SYN byte while receiving telegram!", @@ -227,7 +225,9 @@ public String toDumpString() { * @param data The next byte * @throws EBusDataException throws an exception on any telegram error */ - public void update(byte data) throws EBusDataException { + public void update(final byte data0) throws EBusDataException { + + byte data = data0; try { @@ -327,7 +327,10 @@ public void update(byte data) throws EBusDataException { } len = data; - logger.trace("Master data length: " + len); + + if (logger.isTraceEnabled()) { + logger.trace("Master data length: {}", len); + } // add data to result and crc bb.put(data); @@ -365,7 +368,9 @@ public void update(byte data) throws EBusDataException { setState(State.DATA1); } else { // keep in this state - logger.trace("Data " + len); + if (logger.isTraceEnabled()) { + logger.trace("Data length: {}", len); + } } break; @@ -475,7 +480,10 @@ public void update(byte data) throws EBusDataException { } len = data; - logger.trace("Slave data Length: " + len); + + if (logger.isTraceEnabled()) { + logger.trace("Slave data length: {}", len); + } // if no payload goto CRC2 setState(len == 0 ? State.CRC2 : State.LENGTH2); @@ -514,7 +522,9 @@ public void update(byte data) throws EBusDataException { setState(State.DATA2); } else { // keep in this state - logger.trace("Data " + len); + if (logger.isTraceEnabled()) { + logger.trace("Data length: {}", len); + } } break; diff --git a/src/main/java/de/csdev/ebus/core/EBusVersion.java b/src/main/java/de/csdev/ebus/core/EBusVersion.java index 3500538..07799c7 100644 --- a/src/main/java/de/csdev/ebus/core/EBusVersion.java +++ b/src/main/java/de/csdev/ebus/core/EBusVersion.java @@ -16,8 +16,11 @@ @NonNullByDefault public class EBusVersion { - @SuppressWarnings("null") - private static String getAttribute(Class rootClass, String name) { + protected EBusVersion() { + throw new IllegalStateException("Utility class"); + } + + private static String getAttribute(final Class rootClass, final String name) { try { Manifest manifest = new Manifest(rootClass.getResourceAsStream("/META-INF/MANIFEST.MF")); return manifest.getMainAttributes().getValue(name); @@ -31,7 +34,7 @@ public static String getVersion() { return getVersion(EBusVersion.class); } - protected static String getVersion(Class rootClass) { + protected static String getVersion(final Class rootClass) { return getAttribute(rootClass, "Bundle-Version"); } @@ -39,7 +42,7 @@ public static String getBuildCommit() { return getBuildCommit(EBusVersion.class); } - protected static String getBuildCommit(Class rootClass) { + protected static String getBuildCommit(final Class rootClass) { return getAttribute(rootClass, "Build-Commit"); } @@ -47,7 +50,7 @@ public static String getBuildTimestamp() { return getBuildTimestamp(EBusVersion.class); } - protected static String getBuildTimestamp(Class rootClass) { + protected static String getBuildTimestamp(final Class rootClass) { return getAttribute(rootClass, "Build-Timestamp"); } @@ -55,7 +58,7 @@ public static String getBuildNumber() { return getBuildNumber(EBusVersion.class); } - protected static String getBuildNumber(Class rootClass) { + protected static String getBuildNumber(final Class rootClass) { return getAttribute(rootClass, "Build-Number"); } diff --git a/src/main/java/de/csdev/ebus/core/EBusWorkerThreadFactory.java b/src/main/java/de/csdev/ebus/core/EBusWorkerThreadFactory.java index 0070307..bd60f46 100644 --- a/src/main/java/de/csdev/ebus/core/EBusWorkerThreadFactory.java +++ b/src/main/java/de/csdev/ebus/core/EBusWorkerThreadFactory.java @@ -22,13 +22,13 @@ public class EBusWorkerThreadFactory implements ThreadFactory { private String prefix = ""; private boolean useCounter; - public EBusWorkerThreadFactory(String prefix, boolean useCounter) { + public EBusWorkerThreadFactory(final String prefix, final boolean useCounter) { this.prefix = prefix; this.useCounter = useCounter; } @Override - public Thread newThread(Runnable runnable) { + public Thread newThread(final Runnable runnable) { String name = useCounter ? prefix + "-" + counter++ : prefix; return new Thread(runnable, name); } diff --git a/src/main/java/de/csdev/ebus/core/IEBusConnectorEventListener.java b/src/main/java/de/csdev/ebus/core/IEBusConnectorEventListener.java index 8cbec4b..279cea8 100644 --- a/src/main/java/de/csdev/ebus/core/IEBusConnectorEventListener.java +++ b/src/main/java/de/csdev/ebus/core/IEBusConnectorEventListener.java @@ -28,7 +28,7 @@ public interface IEBusConnectorEventListener { * @param receivedData * @param sendQueueId */ - public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueId); + public void onTelegramReceived(final byte[] receivedData, final @Nullable Integer sendQueueId); /** * A new valid telegram has been received. @@ -36,19 +36,19 @@ public interface IEBusConnectorEventListener { * @param exception * @param sendQueueId */ - public void onTelegramException(EBusDataException exception, @Nullable Integer sendQueueId); + public void onTelegramException(final EBusDataException exception, final @Nullable Integer sendQueueId); /** * A connection exception has occurred * * @param e */ - public void onConnectionException(Exception e); + public void onConnectionException(final Exception e); /** * The connection status has changed * * @param status ConnectionStatus.CONNECTING, ConnectionStatus.CONNECTED or ConnectionStatus.DISCONNECTED */ - public void onConnectionStatusChanged(ConnectionStatus status); + public void onConnectionStatusChanged(final ConnectionStatus status); } diff --git a/src/main/java/de/csdev/ebus/core/IEBusController.java b/src/main/java/de/csdev/ebus/core/IEBusController.java index 8f6e313..cd7c3c7 100644 --- a/src/main/java/de/csdev/ebus/core/IEBusController.java +++ b/src/main/java/de/csdev/ebus/core/IEBusController.java @@ -13,7 +13,7 @@ public interface IEBusController { @NonNull - Integer addToSendQueue(byte @NonNull [] buffer, int maxAttemps) throws EBusControllerException; + Integer addToSendQueue(final byte @NonNull [] buffer, final int maxAttemps) throws EBusControllerException; /** * @param buffer @@ -21,14 +21,14 @@ public interface IEBusController { * @throws EBusControllerException */ @NonNull - Integer addToSendQueue(byte @NonNull [] buffer) throws EBusControllerException; + Integer addToSendQueue(final byte @NonNull [] buffer) throws EBusControllerException; /** * Add an eBUS listener to receive valid eBus telegrams * * @param listener */ - void addEBusEventListener(@NonNull IEBusConnectorEventListener listener); + void addEBusEventListener(final @NonNull IEBusConnectorEventListener listener); /** * Remove an eBUS listener @@ -36,7 +36,7 @@ public interface IEBusController { * @param listener * @return */ - boolean removeEBusEventListener(@NonNull IEBusConnectorEventListener listener); + boolean removeEBusEventListener(final @NonNull IEBusConnectorEventListener listener); boolean isRunning(); diff --git a/src/main/java/de/csdev/ebus/core/connection/AbstractEBusConnection.java b/src/main/java/de/csdev/ebus/core/connection/AbstractEBusConnection.java index e9b99a6..3ef60e7 100644 --- a/src/main/java/de/csdev/ebus/core/connection/AbstractEBusConnection.java +++ b/src/main/java/de/csdev/ebus/core/connection/AbstractEBusConnection.java @@ -52,12 +52,12 @@ public boolean isOpen() throws IOException { } @Override - public int readBytes(byte[] buffer) throws IOException { + public int readBytes(final byte[] buffer) throws IOException { return inputStream.read(buffer); } @Override - public int readByte(boolean lowLatency) throws IOException { + public int readByte(final boolean lowLatency) throws IOException { return inputStream.read(); } @@ -67,7 +67,7 @@ public boolean isReceiveBufferEmpty() throws IOException { } @Override - public void writeByte(int b) throws IOException { + public void writeByte(final int b) throws IOException { outputStream.write(b); outputStream.flush(); } diff --git a/src/main/java/de/csdev/ebus/core/connection/EBusCaptureProxyConnection.java b/src/main/java/de/csdev/ebus/core/connection/EBusCaptureProxyConnection.java index eb4e208..9b64249 100644 --- a/src/main/java/de/csdev/ebus/core/connection/EBusCaptureProxyConnection.java +++ b/src/main/java/de/csdev/ebus/core/connection/EBusCaptureProxyConnection.java @@ -22,7 +22,7 @@ public class EBusCaptureProxyConnection implements IEBusConnection { private EmulatorCapture captureWriter; - public EBusCaptureProxyConnection(IEBusConnection proxyConnection, EmulatorCapture captureWriter) { + public EBusCaptureProxyConnection(final IEBusConnection proxyConnection, final EmulatorCapture captureWriter) { this.proxyConnection = proxyConnection; this.captureWriter = captureWriter; } @@ -40,7 +40,7 @@ public boolean isOpen() throws IOException { return proxyConnection.isOpen(); } - public int readByte(boolean lowLatency) throws IOException { + public int readByte(final boolean lowLatency) throws IOException { int readByte = proxyConnection.readByte(lowLatency); if (readByte != -1) { @@ -54,13 +54,13 @@ public boolean isReceiveBufferEmpty() throws IOException { return proxyConnection.isReceiveBufferEmpty(); } - public int readBytes(byte[] buffer) throws IOException { + public int readBytes(final byte[] buffer) throws IOException { int readBytes = proxyConnection.readBytes(buffer); captureWriter.write(buffer, readBytes); return readBytes; } - public void writeByte(int b) throws IOException { + public void writeByte(final int b) throws IOException { proxyConnection.writeByte(b); } diff --git a/src/main/java/de/csdev/ebus/core/connection/EBusEmulatorConnection.java b/src/main/java/de/csdev/ebus/core/connection/EBusEmulatorConnection.java index ce6baa5..23d6fff 100644 --- a/src/main/java/de/csdev/ebus/core/connection/EBusEmulatorConnection.java +++ b/src/main/java/de/csdev/ebus/core/connection/EBusEmulatorConnection.java @@ -13,6 +13,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import de.csdev.ebus.core.EBusConsts; import de.csdev.ebus.utils.Emulator; /** @@ -43,20 +44,21 @@ public boolean open() throws IOException { } @Override - public void writeByte(int b) throws IOException { + public void writeByte(final int b) throws IOException { emu.write((byte) b); } - public void writeBytes(byte[] byteArray) { + public void writeBytes(final byte[] byteArray) { emu.write(byteArray); } - public void writeBytesDelayed(byte[] byteArray, long delay) { + public void writeBytesDelayed(final byte[] byteArray, final long delay) { try { Thread.sleep(delay); } catch (InterruptedException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); + Thread.currentThread().interrupt(); } writeBytes(byteArray); diff --git a/src/main/java/de/csdev/ebus/core/connection/EBusJSerialCommConnection.java b/src/main/java/de/csdev/ebus/core/connection/EBusJSerialCommConnection.java index 773b1ec..6e6499e 100644 --- a/src/main/java/de/csdev/ebus/core/connection/EBusJSerialCommConnection.java +++ b/src/main/java/de/csdev/ebus/core/connection/EBusJSerialCommConnection.java @@ -10,11 +10,13 @@ import java.io.IOException; +import com.fazecast.jSerialComm.SerialPort; + import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fazecast.jSerialComm.SerialPort; +import de.csdev.ebus.core.EBusConsts; /** * @author Christian Sowada - Initial contribution @@ -22,7 +24,6 @@ */ public class EBusJSerialCommConnection extends AbstractEBusConnection { - @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(EBusJSerialCommConnection.class); /** The serial object */ @@ -62,22 +63,19 @@ public boolean open() throws IOException { @Override public boolean close() throws IOException { if (serialPort == null) { - return true; + return false; } // run the serial.close in a new not-interrupted thread to // prevent an IllegalMonitorStateException error - Thread shutdownThread = new Thread(new Runnable() { - @Override - public void run() { + Thread shutdownThread = new Thread(() -> { - IOUtils.closeQuietly(inputStream); - IOUtils.closeQuietly(outputStream); + IOUtils.closeQuietly(inputStream); + IOUtils.closeQuietly(outputStream); - if (serialPort != null) { - serialPort.closePort(); - serialPort = null; - } + if (serialPort != null) { + serialPort.closePort(); + serialPort = null; } }, "eBUS serial shutdown thread"); @@ -87,6 +85,8 @@ public void run() { // wait for shutdown shutdownThread.join(2000); } catch (InterruptedException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); + Thread.currentThread().interrupt(); } return true; diff --git a/src/main/java/de/csdev/ebus/core/connection/EBusSerialNRJavaSerialConnection.java b/src/main/java/de/csdev/ebus/core/connection/EBusSerialNRJavaSerialConnection.java index d898613..7089c35 100644 --- a/src/main/java/de/csdev/ebus/core/connection/EBusSerialNRJavaSerialConnection.java +++ b/src/main/java/de/csdev/ebus/core/connection/EBusSerialNRJavaSerialConnection.java @@ -15,12 +15,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import de.csdev.ebus.core.EBusConsts; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; -import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; /** @@ -58,20 +58,9 @@ public boolean open() throws IOException { serialPort.setSerialPortParams(2400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); - // serialPort.disableReceiveFraming(); - // serialPort.enableReceiveThreshold(1); - // serialPort.disableReceiveTimeout(); - // serialPort.enableReceiveTimeout(0); - serialPort.enableReceiveThreshold(1); serialPort.disableReceiveTimeout(); - // serialPort.disableReceiveThreshold(); - // serialPort.enableReceiveTimeout(10000); - - // not working with Linux (ArchLinux on ARM7), simply stops here - // serialPort.setLowLatency(); - // set buffers to 1 for low latency serialPort.setOutputBufferSize(1); serialPort.setInputBufferSize(50); @@ -85,13 +74,10 @@ public boolean open() throws IOException { } // use event to let readByte wait until data is available, optimize cpu usage - serialPort.addEventListener(new SerialPortEventListener() { - @Override - public void serialEvent(SerialPortEvent event) { - if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) { - synchronized (inputStream) { - inputStream.notifyAll(); - } + serialPort.addEventListener(event -> { + if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) { + synchronized (inputStream) { + inputStream.notifyAll(); } } }); @@ -125,38 +111,37 @@ public void serialEvent(SerialPortEvent event) { */ @Override public boolean close() throws IOException { + if (serialPort == null) { - return true; + return false; } // run the serial.close in a new not-interrupted thread to // prevent an IllegalMonitorStateException error - Thread shutdownThread = new Thread(new Runnable() { - @Override - public void run() { + Thread shutdownThread = new Thread(() -> { - IOUtils.closeQuietly(inputStream); + IOUtils.closeQuietly(inputStream); - if (outputStream != null) { - try { - outputStream.flush(); - } catch (IOException e) { - } - IOUtils.closeQuietly(outputStream); + if (outputStream != null) { + try { + outputStream.flush(); + } catch (IOException e) { + // noop } + IOUtils.closeQuietly(outputStream); + } - if (serialPort != null) { - - serialPort.notifyOnDataAvailable(false); - serialPort.removeEventListener(); + if (serialPort != null) { - serialPort.close(); - serialPort = null; - } + serialPort.notifyOnDataAvailable(false); + serialPort.removeEventListener(); - inputStream = null; - outputStream = null; + serialPort.close(); + serialPort = null; } + + inputStream = null; + outputStream = null; }, "eBUS serial shutdown thread"); shutdownThread.start(); @@ -165,6 +150,8 @@ public void run() { // wait for shutdown shutdownThread.join(2000); } catch (InterruptedException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); + Thread.currentThread().interrupt(); } return true; @@ -178,14 +165,6 @@ public void run() { @Override public int readByte(boolean lowLatency) throws IOException { if (lowLatency) { - - // while (true) { - // int read = inputStream.read(); - // if (read != -1) { - // return read; - // } - // } - return inputStream.read(); } else { if (inputStream.available() > 0) { diff --git a/src/main/java/de/csdev/ebus/core/connection/IEBusConnection.java b/src/main/java/de/csdev/ebus/core/connection/IEBusConnection.java index 73092aa..fd98b2d 100644 --- a/src/main/java/de/csdev/ebus/core/connection/IEBusConnection.java +++ b/src/main/java/de/csdev/ebus/core/connection/IEBusConnection.java @@ -47,7 +47,7 @@ public interface IEBusConnection { * @return * @throws IOException */ - public int readByte(boolean lowLatency) throws IOException; + public int readByte(final boolean lowLatency) throws IOException; /** * Returns true if not data is available in the buffer @@ -64,7 +64,7 @@ public interface IEBusConnection { * @return * @throws IOException */ - public int readBytes(byte[] buffer) throws IOException; + public int readBytes(final byte[] buffer) throws IOException; /** * Writes a byte to the connection @@ -72,7 +72,7 @@ public interface IEBusConnection { * @param b * @throws IOException */ - public void writeByte(int b) throws IOException; + public void writeByte(final int b) throws IOException; /** * Resets the connection and flushes all buffers diff --git a/src/main/java/de/csdev/ebus/service/device/EBusDevice.java b/src/main/java/de/csdev/ebus/service/device/EBusDevice.java index a340a3b..d8e0b47 100644 --- a/src/main/java/de/csdev/ebus/service/device/EBusDevice.java +++ b/src/main/java/de/csdev/ebus/service/device/EBusDevice.java @@ -10,6 +10,7 @@ import java.math.BigDecimal; import java.util.Arrays; +import java.util.Objects; import de.csdev.ebus.utils.EBusUtils; @@ -147,10 +148,18 @@ public int hashCode() { } public void setDeviceId(byte[] deviceId) { + + Objects.requireNonNull(deviceId, "deviceId"); + + if(deviceId.length != 5) { + throw new IllegalArgumentException("Argument 'deviceId' must be an array of 5 bytes!"); + } + this.deviceId = deviceId; } public void setHardwareVersion(BigDecimal hardwareVersion) { + Objects.requireNonNull(hardwareVersion, "hardwareVersion"); this.hardwareVersion = hardwareVersion; } @@ -159,10 +168,12 @@ public void setLastActivity(long lastActivity) { } public void setManufacturer(Byte manufactur) { + Objects.requireNonNull(manufactur, "manufactur"); this.manufacturer = manufactur; } public void setSoftwareVersion(BigDecimal softwareVersion) { + Objects.requireNonNull(softwareVersion, "softwareVersion"); this.softwareVersion = softwareVersion; } diff --git a/src/main/java/de/csdev/ebus/service/device/EBusDeviceTable.java b/src/main/java/de/csdev/ebus/service/device/EBusDeviceTable.java index f537947..5d88051 100644 --- a/src/main/java/de/csdev/ebus/service/device/EBusDeviceTable.java +++ b/src/main/java/de/csdev/ebus/service/device/EBusDeviceTable.java @@ -20,18 +20,18 @@ import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + import org.apache.commons.lang.ObjectUtils; import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import de.csdev.ebus.command.datatypes.EBusTypeException; import de.csdev.ebus.core.EBusConsts; -import de.csdev.ebus.utils.EBusTypeUtils; import de.csdev.ebus.utils.EBusUtils; +import de.csdev.ebus.utils.NumberUtils; /** * @author Christian Sowada - Initial contribution @@ -44,7 +44,7 @@ public class EBusDeviceTable { private Map deviceTable; /** the list for listeners */ - private final List listeners = new CopyOnWriteArrayList(); + private final List listeners = new CopyOnWriteArrayList<>(); private Map vendors; @@ -52,13 +52,14 @@ public class EBusDeviceTable { private byte ownAddress; public EBusDeviceTable() { - deviceTable = new HashMap(); + deviceTable = new HashMap<>(); } + /** + * + */ public void dispose() { - if (listeners != null) { - listeners.clear(); - } + listeners.clear(); if (deviceTable != null) { deviceTable.clear(); @@ -69,13 +70,22 @@ public void dispose() { } } - public void setOwnAddress(byte ownAddress) { + /** + * + * @param ownAddress + */ + public void setOwnAddress(final byte ownAddress) { this.ownAddress = ownAddress; EBusDevice d = new EBusDevice(ownAddress, this); deviceTable.put(d.getMasterAddress(), d); } - public String getManufacturerName(byte vendorCode) { + /** + * + * @param vendorCode + * @return + */ + public String getManufacturerName(final byte vendorCode) { // vendor list not loaded? if (vendors == null) { @@ -97,35 +107,41 @@ public String getManufacturerName(byte vendorCode) { return vendors.get(EBusUtils.toHexDumpString(vendorCode)); } - public void updateDevice(byte address, Map<@NonNull String, @NonNull Object> data) { + /** + * + * @param address + * @param data + */ + public void updateDevice(final byte address, final Map<@NonNull String, @Nullable Object> data) { boolean newDevice = false; boolean updatedDevice = false; + byte addr = address; - if (address == EBusConsts.BROADCAST_ADDRESS) { + if (addr == EBusConsts.BROADCAST_ADDRESS) { return; - } else if (EBusUtils.isMasterAddress(address)) { - Byte result = EBusUtils.getSlaveAddress(address); + } else if (EBusUtils.isMasterAddress(addr)) { + Byte result = EBusUtils.getSlaveAddress(addr); if (result == null) { throw new IllegalArgumentException( - String.format("Given slave address %s is invalid!", EBusUtils.toHexDumpString(address))); + String.format("Given slave address %s is invalid!", EBusUtils.toHexDumpString(addr))); } - address = result; + addr = result; } - if (address == ownAddress) { + if (addr == ownAddress) { // ignore own address return; } - EBusDevice device = deviceTable.get(address); + EBusDevice device = deviceTable.get(addr); if (device == null) { - device = new EBusDevice(address, this); + device = new EBusDevice(addr, this); device.setLastActivity(System.currentTimeMillis()); - deviceTable.put(address, device); + deviceTable.put(addr, device); newDevice = true; } @@ -133,34 +149,44 @@ public void updateDevice(byte address, Map<@NonNull String, @NonNull Object> dat if (data != null && !data.isEmpty()) { - Object obj = data.get("device_id"); - if (obj != null && !obj.equals(device.getDeviceId())) { - device.setDeviceId((byte[]) obj); - updatedDevice = true; + if (data.containsKey("device_id")) { + @Nullable + Object obj = data.get("device_id"); + if (obj != null && !obj.equals(device.getDeviceId())) { + if (obj instanceof byte[]) { + device.setDeviceId((byte[]) obj); + updatedDevice = true; + } + } } - try { - BigDecimal obj2 = EBusTypeUtils.toBigDecimal(data.get("hardware_version")); + @Nullable + Object value = data.get("hardware_version"); + if (value != null) { + BigDecimal obj2 = NumberUtils.toBigDecimal(value); if (obj2 != null && !ObjectUtils.equals(obj2, device.getHardwareVersion())) { device.setHardwareVersion(obj2); updatedDevice = true; } + } - obj2 = EBusTypeUtils.toBigDecimal(data.get("software_version")); + value = data.get("software_version"); + if (value != null) { + BigDecimal obj2 = NumberUtils.toBigDecimal(value); if (obj2 != null && !ObjectUtils.equals(obj2, device.getSoftwareVersion())) { device.setSoftwareVersion(obj2); updatedDevice = true; } + } - obj2 = EBusTypeUtils.toBigDecimal(data.get("vendor")); + value = data.get("vendor"); + if (value != null) { + BigDecimal obj2 = NumberUtils.toBigDecimal(value); if (obj2 != null && !ObjectUtils.equals(obj2.byteValue(), device.getManufacturer())) { int intValue = obj2.intValue(); device.setManufacturer((byte) intValue); updatedDevice = true; } - } catch (EBusTypeException e) { - logger.warn("Unable to update device table entry!", e); - return; } } @@ -173,11 +199,20 @@ public void updateDevice(byte address, Map<@NonNull String, @NonNull Object> dat } } + /** + * + * @return + */ public Collection getDeviceTable() { return Collections.unmodifiableCollection(deviceTable.values()); } - private void fireOnDeviceUpdate(IEBusDeviceTableListener.@NonNull TYPE type, @NonNull EBusDevice device) { + /** + * + * @param type + * @param device + */ + private void fireOnDeviceUpdate(final IEBusDeviceTableListener.@NonNull TYPE type, final @NonNull EBusDevice device) { for (IEBusDeviceTableListener listener : listeners) { try { listener.onEBusDeviceUpdate(type, device); @@ -187,6 +222,10 @@ private void fireOnDeviceUpdate(IEBusDeviceTableListener.@NonNull TYPE type, @No } } + /** + * + * @return + */ public EBusDevice getOwnDevice() { return deviceTable.get(ownAddress); } @@ -196,7 +235,7 @@ public EBusDevice getOwnDevice() { * * @param listener */ - public void addEBusDeviceTableListener(IEBusDeviceTableListener listener) { + public void addEBusDeviceTableListener(final IEBusDeviceTableListener listener) { Objects.requireNonNull(listener); listeners.add(listener); } @@ -207,7 +246,7 @@ public void addEBusDeviceTableListener(IEBusDeviceTableListener listener) { * @param listener * @return */ - public boolean removeEBusDeviceTableListener(IEBusDeviceTableListener listener) { + public boolean removeEBusDeviceTableListener(final IEBusDeviceTableListener listener) { Objects.requireNonNull(listener); return listeners.remove(listener); } diff --git a/src/main/java/de/csdev/ebus/service/device/EBusDeviceTableService.java b/src/main/java/de/csdev/ebus/service/device/EBusDeviceTableService.java index 6afbe0d..7fd0ac1 100644 --- a/src/main/java/de/csdev/ebus/service/device/EBusDeviceTableService.java +++ b/src/main/java/de/csdev/ebus/service/device/EBusDeviceTableService.java @@ -101,12 +101,8 @@ public void inquiryDeviceExistence() { EBusConsts.BROADCAST_ADDRESS, null); scanQueueId = controller.addToSendQueue(EBusUtils.toByteArray(buffer), 2); - } catch (EBusTypeException e) { - logger.error("error!", e); - } catch (EBusControllerException e) { - logger.error("error!", e); - } catch (EBusCommandException e) { - logger.error("error!", e); + } catch (EBusTypeException | EBusControllerException | EBusCommandException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); } } @@ -151,7 +147,9 @@ private synchronized boolean scanDevice2(boolean nextDevice) { scanSlaveAddress = addr; } - logger.debug("Scan address {} ...", EBusUtils.toHexDumpString(scanSlaveAddress)); + if (logger.isDebugEnabled()) { + logger.debug("Scan address {} ...", EBusUtils.toHexDumpString(scanSlaveAddress)); + } byte masterAddress = deviceTable.getOwnDevice().getMasterAddress(); @@ -169,12 +167,8 @@ private synchronized boolean scanDevice2(boolean nextDevice) { return true; - } catch (EBusTypeException e) { - logger.error("error!", e); - } catch (EBusControllerException e) { - logger.error("error!", e); - } catch (EBusCommandException e) { - logger.error("error!", e); + } catch (EBusTypeException | EBusControllerException | EBusCommandException e) { + logger.error(EBusConsts.LOG_ERR_DEF, e); } return false; @@ -218,11 +212,7 @@ private void sendSignOfLife() { EBusConsts.BROADCAST_ADDRESS, null); controller.addToSendQueue(EBusUtils.toByteArray(buffer), 2); - } catch (EBusTypeException e) { - logger.error("error!", e); - } catch (EBusControllerException e) { - logger.error("error!", e); - } catch (EBusCommandException e) { + } catch (EBusTypeException | EBusControllerException | EBusCommandException e) { logger.error("error!", e); } } @@ -255,11 +245,7 @@ public void sendIdentificationRequest(byte slaveAddress) { ByteBuffer buffer = EBusCommandUtils.buildMasterTelegram(command, masterAddress, slaveAddress, null); controller.addToSendQueue(EBusUtils.toByteArray(buffer), 2); - } catch (EBusTypeException e) { - logger.error("error!", e); - } catch (EBusControllerException e) { - logger.error("error!", e); - } catch (EBusCommandException e) { + } catch (EBusTypeException | EBusControllerException | EBusCommandException e) { logger.error("error!", e); } } @@ -323,7 +309,7 @@ public void onTelegramException(@NonNull EBusDataException exception, @Nullable */ @Override public void onTelegramResolved(@NonNull IEBusCommandMethod commandChannel, - @NonNull Map<@NonNull String, @NonNull Object> result, byte @NonNull [] receivedData, + @NonNull Map<@NonNull String, @Nullable Object> result, byte @NonNull [] receivedData, @Nullable Integer sendQueueId) { String id = commandChannel.getParent().getId(); @@ -354,10 +340,8 @@ public void onEBusDeviceUpdate(IEBusDeviceTableListener.@NonNull TYPE type, @Non } // identify new devices - if (type.equals(IEBusDeviceTableListener.TYPE.NEW)) { - if (!disableIdentificationRequests) { - sendIdentificationRequest(device.getSlaveAddress()); - } + if (type.equals(IEBusDeviceTableListener.TYPE.NEW) && !disableIdentificationRequests) { + sendIdentificationRequest(device.getSlaveAddress()); } } diff --git a/src/main/java/de/csdev/ebus/service/device/IEBusDeviceTableListener.java b/src/main/java/de/csdev/ebus/service/device/IEBusDeviceTableListener.java index 891292c..f5d301c 100644 --- a/src/main/java/de/csdev/ebus/service/device/IEBusDeviceTableListener.java +++ b/src/main/java/de/csdev/ebus/service/device/IEBusDeviceTableListener.java @@ -38,6 +38,6 @@ public enum TYPE { * @param type * @param device */ - public void onEBusDeviceUpdate(TYPE type, IEBusDevice device); + public void onEBusDeviceUpdate(final TYPE type, final IEBusDevice device); } diff --git a/src/main/java/de/csdev/ebus/service/metrics/EBusMetricsService.java b/src/main/java/de/csdev/ebus/service/metrics/EBusMetricsService.java index ca2492d..237da7c 100644 --- a/src/main/java/de/csdev/ebus/service/metrics/EBusMetricsService.java +++ b/src/main/java/de/csdev/ebus/service/metrics/EBusMetricsService.java @@ -44,8 +44,7 @@ public class EBusMetricsService extends EBusConnectorEventListener implements IE private BigDecimal receivedAmount = BigDecimal.valueOf(0); - private Map failedMap = new EnumMap( - EBusError.class); + private Map failedMap = new EnumMap<>(EBusError.class); public void clear() { resolved = BigDecimal.valueOf(0); @@ -59,7 +58,7 @@ public void clear() { @Override public void onTelegramResolved(@NonNull IEBusCommandMethod commandChannel, - @NonNull Map<@NonNull String, @NonNull Object> result, byte @NonNull [] receivedData, + @NonNull Map<@NonNull String, @Nullable Object> result, byte @NonNull [] receivedData, @Nullable Integer sendQueueId) { resolved = resolved.add(BigDecimal.ONE); } @@ -81,18 +80,16 @@ public void onTelegramException(@NonNull EBusDataException exception, @Nullable EBusError errorCode = exception.getErrorCode(); - if (errorCode != null) { - if (failedMap.containsKey(errorCode)) { - BigDecimal val = failedMap.get(errorCode); - if (val == null) { - val = BigDecimal.valueOf(0); - } + if (errorCode != null && failedMap.containsKey(errorCode)) { + BigDecimal val = failedMap.get(errorCode); + if (val == null) { + val = BigDecimal.valueOf(0); + } - val = val.add(BigDecimal.ONE); - failedMap.put(errorCode, val); + val = val.add(BigDecimal.ONE); + failedMap.put(errorCode, val); - failed = failed.add(BigDecimal.ONE); - } + failed = failed.add(BigDecimal.ONE); } } diff --git a/src/main/java/de/csdev/ebus/service/parser/EBusParserService.java b/src/main/java/de/csdev/ebus/service/parser/EBusParserService.java index 030b808..cd3584d 100644 --- a/src/main/java/de/csdev/ebus/service/parser/EBusParserService.java +++ b/src/main/java/de/csdev/ebus/service/parser/EBusParserService.java @@ -34,7 +34,7 @@ public class EBusParserService extends EBusConnectorEventListener { private static final Logger logger = LoggerFactory.getLogger(EBusParserService.class); /** the list for listeners */ - private final @NonNull List listeners = new CopyOnWriteArrayList(); + private final @NonNull List listeners = new CopyOnWriteArrayList<>(); /** */ private @NonNull EBusCommandRegistry commandRegistry; @@ -51,9 +51,7 @@ public EBusParserService(@NonNull EBusCommandRegistry configurationProvider) { * */ public void dispose() { - if (listeners != null) { - listeners.clear(); - } + listeners.clear(); } /** @@ -82,13 +80,12 @@ public boolean removeEBusParserListener(@NonNull IEBusParserListener listener) { * * @see de.csdev.ebus.core.EBusConnectorEventListener#onTelegramReceived(byte[], java.lang.Integer) */ - @SuppressWarnings("null") @Override public void onTelegramReceived(byte @NonNull [] receivedData, @Nullable Integer sendQueueId) { final List commandChannelList = commandRegistry.find(receivedData); - if (commandChannelList == null || commandChannelList.isEmpty()) { + if (commandChannelList.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("No command method matches the telegram {} ...", EBusUtils.toHexDumpString(receivedData)); } @@ -122,7 +119,7 @@ public void onTelegramReceived(byte @NonNull [] receivedData, @Nullable Integer * @param sendQueueId */ private void fireOnTelegramResolved(@NonNull IEBusCommandMethod commandChannel, - @NonNull Map<@NonNull String, @NonNull Object> result, byte @NonNull [] receivedData, + @NonNull Map<@NonNull String, @Nullable Object> result, byte @NonNull [] receivedData, @Nullable Integer sendQueueId) { for (IEBusParserListener listener : listeners) { diff --git a/src/main/java/de/csdev/ebus/service/parser/IEBusParserListener.java b/src/main/java/de/csdev/ebus/service/parser/IEBusParserListener.java index 55cfe0f..922b9d0 100644 --- a/src/main/java/de/csdev/ebus/service/parser/IEBusParserListener.java +++ b/src/main/java/de/csdev/ebus/service/parser/IEBusParserListener.java @@ -30,7 +30,7 @@ public interface IEBusParserListener { * @param receivedData The raw data * @param sendQueueId The sendQueue id if available */ - public void onTelegramResolved(IEBusCommandMethod commandChannel, Map result, byte[] receivedData, + public void onTelegramResolved(IEBusCommandMethod commandChannel, Map result, byte[] receivedData, @Nullable Integer sendQueueId); /** diff --git a/src/main/java/de/csdev/ebus/utils/CollectionUtils.java b/src/main/java/de/csdev/ebus/utils/CollectionUtils.java index 2807e3c..53ff1aa 100644 --- a/src/main/java/de/csdev/ebus/utils/CollectionUtils.java +++ b/src/main/java/de/csdev/ebus/utils/CollectionUtils.java @@ -22,6 +22,10 @@ */ public class CollectionUtils { + private CollectionUtils() { + throw new IllegalStateException("Utility class"); + } + /** * A null checked variant of map.get * @@ -55,7 +59,7 @@ public class CollectionUtils { * @return */ public static Map newMapIfNull(@Nullable Map map) { - return map != null ? map : new HashMap(); + return map != null ? map : new HashMap<>(); } /** @@ -66,7 +70,7 @@ public static Map newMapIfNull(@Nullable Map map) { * @return */ public static Map createProperties(Object... args) { - Map properties = new HashMap(); + Map properties = new HashMap<>(); for (int i = 0; i < args.length; i = i + 2) { properties.put(args[i].toString(), args[i + 1]); diff --git a/src/main/java/de/csdev/ebus/utils/EBusConsoleUtils.java b/src/main/java/de/csdev/ebus/utils/EBusConsoleUtils.java index 5278bb0..675534b 100644 --- a/src/main/java/de/csdev/ebus/utils/EBusConsoleUtils.java +++ b/src/main/java/de/csdev/ebus/utils/EBusConsoleUtils.java @@ -51,6 +51,10 @@ public class EBusConsoleUtils { private static final Logger logger = LoggerFactory.getLogger(EBusConsoleUtils.class); + private EBusConsoleUtils() { + throw new IllegalStateException("Utility class"); + } + /** * * @param data diff --git a/src/main/java/de/csdev/ebus/utils/EBusDateTime.java b/src/main/java/de/csdev/ebus/utils/EBusDateTime.java index aba0e37..c999e41 100644 --- a/src/main/java/de/csdev/ebus/utils/EBusDateTime.java +++ b/src/main/java/de/csdev/ebus/utils/EBusDateTime.java @@ -29,11 +29,10 @@ public class EBusDateTime { * @param anyDate Set date part to any date * @param anyTime Set time part to any time */ - public EBusDateTime(Calendar calendar, boolean anyDate, boolean anyTime) { + public EBusDateTime(final Calendar calendar, boolean anyDate, boolean anyTime) { this.calendar = calendar; this.anyDate = anyDate; this.anyTime = anyTime; - } /** @@ -78,9 +77,9 @@ public String toString() { if (anyDate) { format = new SimpleDateFormat("HH:mm:ss"); } else if (anyTime) { - format = new SimpleDateFormat("dd.MM.YYYY"); + format = new SimpleDateFormat("dd.MM.yyyy"); } else { - format = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss"); + format = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); } return format.format(calendar.getTime()); diff --git a/src/main/java/de/csdev/ebus/utils/EBusTelegramWriter.java b/src/main/java/de/csdev/ebus/utils/EBusTelegramWriter.java index d05a9b0..b609943 100644 --- a/src/main/java/de/csdev/ebus/utils/EBusTelegramWriter.java +++ b/src/main/java/de/csdev/ebus/utils/EBusTelegramWriter.java @@ -19,17 +19,20 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.csdev.ebus.command.IEBusCommandMethod; +import de.csdev.ebus.core.EBusConsts; import de.csdev.ebus.service.parser.IEBusParserListener; /** * * @author Christian Sowada - Initial contribution */ +@NonNullByDefault public class EBusTelegramWriter implements IEBusParserListener { private final Logger logger = LoggerFactory.getLogger(EBusTelegramWriter.class); @@ -46,7 +49,7 @@ public EBusTelegramWriter(File loggingDirectory) { @Override public void onTelegramResolved(@NonNull IEBusCommandMethod commandChannel, - @NonNull Map<@NonNull String, @NonNull Object> result, byte @NonNull [] receivedData, + @NonNull Map<@NonNull String, @Nullable Object> result, byte @NonNull [] receivedData, @Nullable Integer sendQueueId) { try { @@ -59,7 +62,7 @@ public void onTelegramResolved(@NonNull IEBusCommandMethod commandChannel, write(writerResolved, receivedData, comment); } catch (IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } } @@ -72,10 +75,13 @@ public void onTelegramResolveFailed(@Nullable IEBusCommandMethod commandChannel, if (writerUnresolved == null) { writerUnresolved = open("ebus-unresolved.csv"); } - write(writerUnresolved, receivedData, ""); + + if (receivedData != null) { + write(writerUnresolved, receivedData, ""); + } } catch (IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } } @@ -85,19 +91,21 @@ public void onTelegramResolveFailed(@Nullable IEBusCommandMethod commandChannel, * @param csvFile The file object * @throws IOException */ - private BufferedWriter open(String filename) throws IOException { + private BufferedWriter open(final String filename) throws IOException { - // File loggingFolder = new File(System.getProperty("openhab.logdir")); File file = new File(loggingDirectory, filename); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); if (!file.exists()) { - file.createNewFile(); + if (logger.isDebugEnabled()) { + logger.debug("Create new file {}", filename); + } + if (!file.createNewFile()) { + throw new IOException("Unable to create file!"); + } } - logger.warn(file.getAbsolutePath()); - writer.write("Date/Time;"); writer.write("SRC;"); writer.write("DST;"); @@ -132,34 +140,34 @@ public void close() { } } - private void write(BufferedWriter writer, byte[] receivedData, String comment) throws IOException { + private void write(final BufferedWriter writer, final byte[] receivedData, final @Nullable String comment) throws IOException { - synchronized (writer) { - DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date date = new Date(); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = new Date(); - writer.write(df.format(date)); - writer.write(";"); + StringBuilder sb = new StringBuilder(); - writer.write('"' + EBusUtils.toHexDumpString(receivedData[0]) + '"'); - writer.write(";"); + sb.append(df.format(date)); + sb.append(";"); - writer.write('"' + EBusUtils.toHexDumpString(receivedData[1]) + '"'); - writer.write(";"); + sb.append('"' + EBusUtils.toHexDumpString(receivedData[0]) + '"'); + sb.append(";"); - byte[] command = Arrays.copyOfRange(receivedData, 2, 4); - writer.write('"' + EBusUtils.toHexDumpString(command).toString() + '"'); - writer.write(";"); + sb.append('"' + EBusUtils.toHexDumpString(receivedData[1]) + '"'); + sb.append(";"); - byte[] rest = Arrays.copyOfRange(receivedData, 4, receivedData.length); - writer.write('"' + EBusUtils.toHexDumpString(rest).toString() + '"'); - writer.write(";"); + byte[] command = Arrays.copyOfRange(receivedData, 2, 4); + sb.append('"' + EBusUtils.toHexDumpString(command).toString() + '"'); + sb.append(";"); - writer.write(comment); + byte[] rest = Arrays.copyOfRange(receivedData, 4, receivedData.length); + sb.append('"' + EBusUtils.toHexDumpString(rest).toString() + '"'); + sb.append(";"); - writer.newLine(); - writer.flush(); - } + sb.append(comment == null ? "" : comment); + + sb.append("\n"); + writer.append(sb).flush(); } } diff --git a/src/main/java/de/csdev/ebus/utils/EBusTypeUtils.java b/src/main/java/de/csdev/ebus/utils/EBusTypeUtils.java deleted file mode 100644 index fb3187a..0000000 --- a/src/main/java/de/csdev/ebus/utils/EBusTypeUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2016-2020 by the respective copyright holders. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package de.csdev.ebus.utils; - -import java.math.BigDecimal; - -import org.eclipse.jdt.annotation.NonNull; -import org.eclipse.jdt.annotation.Nullable; - -import de.csdev.ebus.command.datatypes.EBusTypeException; - -/** - * - * @author Christian Sowada - Initial contribution - */ -public class EBusTypeUtils { - - /** - * - * @param obj - * @return - * @throws EBusTypeException - */ - public static @NonNull BigDecimal toBigDecimal(@Nullable Object obj) throws EBusTypeException { - BigDecimal result = NumberUtils.toBigDecimal(obj); - if (result == null) { - throw new EBusTypeException(); - - } - return result; - } - -} diff --git a/src/main/java/de/csdev/ebus/utils/EBusUtils.java b/src/main/java/de/csdev/ebus/utils/EBusUtils.java index 8db31de..1bd2886 100644 --- a/src/main/java/de/csdev/ebus/utils/EBusUtils.java +++ b/src/main/java/de/csdev/ebus/utils/EBusUtils.java @@ -25,8 +25,12 @@ */ public class EBusUtils { + private EBusUtils() { + throw new IllegalStateException("Utility class"); + } + /** calculated crc values */ - final static public byte CRC_TAB_8_VALUE[] = { (byte) 0x00, (byte) 0x9B, (byte) 0xAD, (byte) 0x36, (byte) 0xC1, + protected static final byte CRC_TAB_8_VALUE[] = { (byte) 0x00, (byte) 0x9B, (byte) 0xAD, (byte) 0x36, (byte) 0xC1, (byte) 0x5A, (byte) 0x6C, (byte) 0xF7, (byte) 0x19, (byte) 0x82, (byte) 0xB4, (byte) 0x2F, (byte) 0xD8, (byte) 0x43, (byte) 0x75, (byte) 0xEE, (byte) 0x32, (byte) 0xA9, (byte) 0x9F, (byte) 0x04, (byte) 0xF3, (byte) 0x68, (byte) 0x5E, (byte) 0xC5, (byte) 0x2B, (byte) 0xB0, (byte) 0x86, (byte) 0x1D, (byte) 0xEA, @@ -67,7 +71,7 @@ public class EBusUtils { * @param size The final byte array size * @return The new byte arrray or null if the source array is to large */ - public static byte @Nullable [] leftPadByteArray(byte @Nullable [] source, int size) { + public static byte @Nullable [] leftPadByteArray(final byte @Nullable [] source, final int size) { byte[] bs = new byte[size]; if (source == null || size < source.length) { @@ -88,13 +92,15 @@ public class EBusUtils { * @param poly The polynom * @return The crc result */ - public static byte crc8(byte data, byte crcInit, byte poly) { + public static byte crc8(final byte data, final byte crcInit, final byte poly) { byte crc; byte polynom; int i; + byte d = data; crc = crcInit; + for (i = 0; i < 8; i++) { if ((uint(crc) & 0x80) != 0) { @@ -104,12 +110,12 @@ public static byte crc8(byte data, byte crcInit, byte poly) { } crc = (byte) ((uint(crc) & ~0x80) << 1); - if ((uint(data) & 0x80) != 0) { + if ((uint(d) & 0x80) != 0) { crc = (byte) (uint(crc) | 1); } crc = (byte) (uint(crc) ^ uint(polynom)); - data = (byte) (uint(data) << 1); + d = (byte) (uint(d) << 1); } return crc; } @@ -119,18 +125,18 @@ public static byte crc8(byte data, byte crcInit, byte poly) { * @param len * @return */ - public static byte crc8(byte @Nullable [] data, int len) { - byte uc_crc = 0; + public static byte crc8(final byte @Nullable [] data, final int len) { + byte ucCrc = 0; if (data == null) { - return uc_crc; + return ucCrc; } for (int i = 0; i < len; i++) { byte b = data[i]; - uc_crc = crc8_tab(b, uc_crc); + ucCrc = crc8_tab(b, ucCrc); } - return uc_crc; + return ucCrc; } /** @@ -140,10 +146,9 @@ public static byte crc8(byte @Nullable [] data, int len) { * @param crcInit The current crc result or another start value * @return The crc result */ - public static byte crc8_tab(byte data, byte crcInit) { + public static byte crc8_tab(final byte data, final byte crcInit) { short ci = (short) (crcInit & 0xFF); - byte crc = (byte) (CRC_TAB_8_VALUE[ci] ^ (data & 0xFF)); - return crc; + return (byte) (CRC_TAB_8_VALUE[ci] ^ (data & 0xFF)); } /** @@ -153,7 +158,7 @@ public static byte crc8_tab(byte data, byte crcInit) { * @param slaveAddress * @return */ - static public @Nullable Byte getMasterAddress(byte slaveAddress) { + public static @Nullable Byte getMasterAddress(final byte slaveAddress) { if (slaveAddress == EBusConsts.ESCAPE || slaveAddress == EBusConsts.SYN) { return null; @@ -175,7 +180,7 @@ public static byte crc8_tab(byte data, byte crcInit) { * @param masterAddress The master address * @return The slave address or null if the master address is invalid */ - static public @Nullable Byte getSlaveAddress(byte masterAddress) { + public static @Nullable Byte getSlaveAddress(final byte masterAddress) { if (isMasterAddress(masterAddress)) { return (byte) (masterAddress == (byte) 0xFF ? (byte) 0x04 : masterAddress + 5); } @@ -189,7 +194,7 @@ public static byte crc8_tab(byte data, byte crcInit) { * @param address * @return */ - public static boolean isMasterAddress(byte address) { + public static boolean isMasterAddress(final byte address) { if (!isValidAddress(address)) { return false; @@ -199,14 +204,11 @@ public static boolean isMasterAddress(byte address) { byte prio = (byte) (address & (byte) 0x0F); if (isValidAddress(address)) { - if (addr == (byte) 0x00 || addr == (byte) 0x01 || addr == (byte) 0x03 || addr == (byte) 0x07 - || addr == (byte) 0x0F) { - if (prio == (byte) 0x00 || prio == (byte) 0x01 || prio == (byte) 0x03 || prio == (byte) 0x07 - || prio == (byte) 0x0F) { - return true; - } - } + boolean addrB = addr == (byte) 0x00 || addr == (byte) 0x01 || addr == (byte) 0x03 || addr == (byte) 0x07 || addr == (byte) 0x0F; + boolean prioB = prio == (byte) 0x00 || prio == (byte) 0x01 || prio == (byte) 0x03 || prio == (byte) 0x07 || prio == (byte) 0x0F; + + return addrB && prioB; } return false; @@ -218,7 +220,7 @@ public static boolean isMasterAddress(byte address) { * @param address * @return */ - public static boolean isSlaveAddress(byte address) { + public static boolean isSlaveAddress(final byte address) { return isValidAddress(address) && !isMasterAddress(address); } @@ -228,11 +230,8 @@ public static boolean isSlaveAddress(byte address) { * @param address * @return */ - public static boolean isValidAddress(byte address) { - if (address == EBusConsts.BROADCAST_ADDRESS || address == EBusConsts.SYN || address == EBusConsts.ESCAPE) { - return false; - } - return true; + public static boolean isValidAddress(final byte address) { + return !(address == EBusConsts.BROADCAST_ADDRESS || address == EBusConsts.SYN || address == EBusConsts.ESCAPE); } /** @@ -241,7 +240,7 @@ public static boolean isValidAddress(byte address) { * @param hexDumpString * @return */ - static public @Nullable Byte toByte(String hexDumpString) { + static public @Nullable Byte toByte(final String hexDumpString) { if (StringUtils.isEmpty(hexDumpString)) { return null; } @@ -282,7 +281,7 @@ public static boolean isValidAddress(byte address) { * @param hexDumpString * @return */ - static public byte @NonNull [] toByteArray(@Nullable String hexDumpString) throws NumberFormatException { + public static byte @NonNull [] toByteArray(final @Nullable String hexDumpString) throws NumberFormatException { if (hexDumpString == null || StringUtils.isEmpty(hexDumpString)) { return new byte[0]; } @@ -304,41 +303,43 @@ public static boolean isValidAddress(byte address) { * @param hexDumpString * @return */ - static public byte @NonNull [] toByteArray2(@Nullable String hexDumpString) throws NumberFormatException { + public static byte @NonNull [] toByteArray2(final @Nullable String hexDumpString) throws NumberFormatException { - if (hexDumpString == null || StringUtils.isEmpty(hexDumpString)) { + String h = hexDumpString; + + if (h == null || StringUtils.isEmpty(h)) { return new byte[0]; } - if (hexDumpString.length() % 2 != 0) { - hexDumpString = "0" + hexDumpString; + if (h.length() % 2 != 0) { + h = "0" + h; } - byte[] result = new byte[hexDumpString.length() / 2]; + byte[] result = new byte[h.length() / 2]; int pos = 0; - for (int i = 0; i < hexDumpString.length(); i = i + 2) { - String val = hexDumpString.substring(i, i + 2); + for (int i = 0; i < h.length(); i = i + 2) { + String val = h.substring(i, i + 2); result[pos++] = Integer.valueOf(val, 16).byteValue(); } return result; } - static public @NonNull String mergeHexDumpStrings(@Nullable String... args) { + public static @NonNull String mergeHexDumpStrings(final @Nullable String... args) { if (args == null) { return ""; } - String merge = ""; + StringBuilder sb = new StringBuilder(); for (String string : args) { if (string != null && StringUtils.isNotEmpty(string)) { - merge += string.length() % 2 == 0 ? string : "0" + string; + sb.append(string.length() % 2 == 0 ? string : "0" + string); } } - StringBuilder sb = toHexDumpString(toByteArray2(merge)); + sb = toHexDumpString(toByteArray2(sb.toString())); return Objects.requireNonNull(sb.toString()); } @@ -348,7 +349,7 @@ public static boolean isValidAddress(byte address) { * @param data The source * @return The hex string */ - static public @NonNull String toHexDumpString(@Nullable Byte data) { + public static @NonNull String toHexDumpString(final @Nullable Byte data) { if (data == null) { return ""; @@ -364,7 +365,7 @@ public static boolean isValidAddress(byte address) { * @param data The source * @return The StringBuilder with hex dump */ - static public @NonNull StringBuilder toHexDumpString(byte @Nullable [] data) { + public static @NonNull StringBuilder toHexDumpString(final byte @Nullable [] data) { StringBuilder sb = new StringBuilder(); if (data != null && data.length > 0) { for (int i = 0; i < data.length; i++) { @@ -385,7 +386,7 @@ public static boolean isValidAddress(byte address) { * @param data The source * @return The StringBuilder with hex dump */ - static public StringBuilder toHexDumpString(@Nullable ByteBuffer data) { + public static StringBuilder toHexDumpString(final @Nullable ByteBuffer data) { StringBuilder sb = new StringBuilder(); if (data == null) { @@ -415,7 +416,7 @@ static public StringBuilder toHexDumpString(@Nullable ByteBuffer data) { * @param data * @return */ - static public String toPrintHexDumpString(@Nullable Byte data) { + public static String toPrintHexDumpString(final @Nullable Byte data) { if (data != null) { return "0x" + String.format("%02X", (0xFF & data)); } @@ -428,7 +429,7 @@ static public String toPrintHexDumpString(@Nullable Byte data) { * @param v * @return */ - public static int uint(byte v) { + public static int uint(final byte v) { return v & 0xFF; } } diff --git a/src/main/java/de/csdev/ebus/utils/Emulator.java b/src/main/java/de/csdev/ebus/utils/Emulator.java index 381e76c..42bd7a5 100644 --- a/src/main/java/de/csdev/ebus/utils/Emulator.java +++ b/src/main/java/de/csdev/ebus/utils/Emulator.java @@ -55,21 +55,15 @@ private void stopAutoSync() { } private void startAutoSync() { - autoSyncFuture = playThreadExecutor.schedule(new Runnable() { - - @Override - public void run() { - write(EBusConsts.SYN); - } - - }, 40 * factor, TimeUnit.MILLISECONDS); + long v = 40 * (long) factor; + autoSyncFuture = playThreadExecutor.schedule(() -> write(EBusConsts.SYN), v, TimeUnit.MILLISECONDS); } public Emulator() { this(1, true); } - public Emulator(int factor, boolean autoSync) { + public Emulator(final int factor, final boolean autoSync) { this.factor = factor; pipeThreadExecutor = Executors.newSingleThreadExecutor(new EBusWorkerThreadFactory("ebus-emu-pipe", false)); @@ -83,7 +77,7 @@ public Emulator(int factor, boolean autoSync) { in = new PipedInputStream(); out = new PipedOutputStream(in); } catch (IOException e) { - logger.error("error!", e); + logger.error(EBusConsts.LOG_ERR_DEF, e); } } @@ -103,31 +97,27 @@ public InputStream getInputStream() { */ public void write(final byte b) { - pipeThreadExecutor.submit(new Runnable() { + pipeThreadExecutor.submit(() -> { + try { + synchronized (out) { - @Override - public void run() { - try { - synchronized (out) { + stopAutoSync(); - stopAutoSync(); + out.write(b); + out.flush(); - out.write(b); - out.flush(); - - // delay for 2400baud - try { - Thread.sleep(4 * factor); - } catch (InterruptedException e) { - // noop, ignore this - } - - startAutoSync(); + // delay for 2400baud + try { + out.wait(4 * factor); + } catch (InterruptedException e1) { + Thread.currentThread().interrupt(); } - } catch (IOException e) { - logger.trace("error!", e); + startAutoSync(); } + + } catch (IOException e2) { + logger.trace(EBusConsts.LOG_ERR_DEF, e2); } }); } @@ -138,16 +128,9 @@ public void run() { * @param byteArray */ public void write(final byte[] byteArray) { - - pipeThreadExecutor.submit(new Runnable() { - - @Override - public void run() { - - for (byte b : byteArray) { - write(b); - } - + pipeThreadExecutor.submit(() -> { + for (byte b : byteArray) { + write(b); } }); } @@ -167,13 +150,15 @@ public void close() { try { this.playThreadExecutor.awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { - logger.trace("error!", e); + logger.trace(EBusConsts.LOG_ERR_DEF, e); + Thread.currentThread().interrupt(); } try { this.pipeThreadExecutor.awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { - logger.trace("error!", e); + logger.trace(EBusConsts.LOG_ERR_DEF, e); + Thread.currentThread().interrupt(); } IOUtils.closeQuietly(in); diff --git a/src/main/java/de/csdev/ebus/utils/EmulatorCapture.java b/src/main/java/de/csdev/ebus/utils/EmulatorCapture.java index 445409b..fd99115 100644 --- a/src/main/java/de/csdev/ebus/utils/EmulatorCapture.java +++ b/src/main/java/de/csdev/ebus/utils/EmulatorCapture.java @@ -31,28 +31,26 @@ public class EmulatorCapture { protected PrintWriter writer; - public EmulatorCapture(File outputFile) { + public EmulatorCapture(final File outputFile) { referenceTime = System.currentTimeMillis(); try { writer = new PrintWriter(outputFile, "UTF-8"); - } catch (FileNotFoundException e) { - logger.error("error!", e); - } catch (UnsupportedEncodingException e) { + } catch (FileNotFoundException | UnsupportedEncodingException e) { logger.error("error!", e); } } - public void write(byte[] buffer, int len) { + public void write(final byte[] buffer, final int len) { byte[] copyOf = Arrays.copyOf(buffer, len); write(copyOf); } - public void write(byte[] buffer, int from, int len) { + public void write(final byte[] buffer, final int from, final int len) { byte[] copyOf = Arrays.copyOfRange(buffer, from, len); write(copyOf); } - public void write(byte[] buffer) { + public void write(final byte[] buffer) { writer.printf("%09d", System.currentTimeMillis() - referenceTime); writer.print(" - "); writer.println(EBusUtils.toHexDumpString(buffer).toString()); diff --git a/src/main/java/de/csdev/ebus/utils/NumberUtils.java b/src/main/java/de/csdev/ebus/utils/NumberUtils.java index d245884..dc53b28 100644 --- a/src/main/java/de/csdev/ebus/utils/NumberUtils.java +++ b/src/main/java/de/csdev/ebus/utils/NumberUtils.java @@ -20,13 +20,17 @@ */ public class NumberUtils { + private NumberUtils() { + throw new IllegalStateException("Utility class"); + } + /** * Convert number object to BigDecimal * * @param obj Any kind of primitive datatype * @return A converted BigDecimal */ - public static @Nullable BigDecimal toBigDecimal(@Nullable Object obj) { + public static @Nullable BigDecimal toBigDecimal(final @Nullable Object obj) { if (obj instanceof Integer) { return BigDecimal.valueOf((Integer) obj); @@ -57,7 +61,7 @@ public class NumberUtils { * @param data * @return */ - public static @Nullable Byte convertDec2Bcd(int data) { + public static @Nullable Byte convertDec2Bcd(final int data) { if (data > 99) { return null; @@ -70,7 +74,7 @@ public class NumberUtils { * @param bcd * @return */ - public static @Nullable Byte convertBcd2Dec(byte bcd) { + public static @Nullable Byte convertBcd2Dec(final byte bcd) { byte high = (byte) (bcd >> 4 & 0x0F); byte low = (byte) (bcd & 0x0F); diff --git a/src/main/resources/.gitignore b/src/main/resources/.gitignore deleted file mode 100644 index 1564b5c..0000000 --- a/src/main/resources/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/capture.txt -/test/ diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml deleted file mode 100644 index 52d2a1b..0000000 --- a/src/main/resources/logback.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%-5level] %logger{30}[:%line] - %msg%n%ex{0} - - - - - - - - - - diff --git a/src/test/java/de/csdev/ebus/TestUtils.java b/src/test/java/de/csdev/ebus/TestUtils.java index f51a1d2..3c9b29d 100644 --- a/src/test/java/de/csdev/ebus/TestUtils.java +++ b/src/test/java/de/csdev/ebus/TestUtils.java @@ -26,7 +26,6 @@ public class TestUtils { private static final Logger logger = LoggerFactory.getLogger(TestUtils.class); - @SuppressWarnings("null") public static boolean canResolve(EBusCommandRegistry commandRegistry, byte[] data) { List list = commandRegistry.find(data); diff --git a/src/test/java/de/csdev/ebus/cfg/EBusCommonTelegramTest.java b/src/test/java/de/csdev/ebus/cfg/EBusCommonTelegramTest.java index b6b90da..5f0184e 100644 --- a/src/test/java/de/csdev/ebus/cfg/EBusCommonTelegramTest.java +++ b/src/test/java/de/csdev/ebus/cfg/EBusCommonTelegramTest.java @@ -9,6 +9,7 @@ package de.csdev.ebus.cfg; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import java.io.IOException; import java.nio.ByteBuffer; @@ -55,9 +56,10 @@ public void testIdentification() { } catch (EBusTypeException e) { logger.error("error!", e); + fail("An exception occured!"); } catch (EBusCommandException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + logger.error("error!", e); + fail("An exception occured!"); } } diff --git a/src/test/java/de/csdev/ebus/cfg/EBusNestedTemplatesTest.java b/src/test/java/de/csdev/ebus/cfg/EBusNestedTemplatesTest.java index 2d9b1e6..012c9ea 100644 --- a/src/test/java/de/csdev/ebus/cfg/EBusNestedTemplatesTest.java +++ b/src/test/java/de/csdev/ebus/cfg/EBusNestedTemplatesTest.java @@ -99,7 +99,6 @@ public void test2() throws EBusTypeException { List<@NonNull IEBusValue> masterTypes = commandMethod.getMasterTypes(); assertNotNull(masterTypes); - @SuppressWarnings("null") IEBusValue value = masterTypes.get(0); IEBusType type = value.getType(); @@ -135,7 +134,7 @@ public void test3() throws EBusTypeException { List<@NonNull IEBusValue> masterTypes = commandMethod.getMasterTypes(); assertNotNull(masterTypes); - @SuppressWarnings("null") + IEBusValue value = masterTypes.get(0); IEBusType type = value.getType(); diff --git a/src/test/java/de/csdev/ebus/core/EBusStateMachineTest.java b/src/test/java/de/csdev/ebus/core/EBusStateMachineTest.java index e9a7e2e..20405d9 100644 --- a/src/test/java/de/csdev/ebus/core/EBusStateMachineTest.java +++ b/src/test/java/de/csdev/ebus/core/EBusStateMachineTest.java @@ -8,19 +8,18 @@ */ package de.csdev.ebus.core; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.csdev.ebus.command.EBusCommandUtils; -import de.csdev.ebus.command.datatypes.EBusTypeException; import de.csdev.ebus.core.EBusDataException.EBusError; import de.csdev.ebus.utils.EBusUtils; @@ -39,9 +38,6 @@ public void init() { machine = new EBusReceiveStateMachine(); } - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testNoAnswer() { @@ -69,9 +65,13 @@ public void testNACK() throws EBusDataException { logger.info("Master/Slave - NACK"); - thrown.expect(EBusDataException.class); + try { + runMachine(EBusUtils.toByteArray("AA 30 08 50 22 03 CC 1A 27 59 FF AA")); + } catch (EBusDataException e) { + // System.out.println("EBusStateMachineTest.testNACK()" + e); + assertTrue(e.getErrorCode().equals(EBusError.SLAVE_ACK_FAIL)); + } - runMachine(EBusUtils.toByteArray("AA 30 08 50 22 03 CC 1A 27 59 FF AA")); } @Test @@ -378,12 +378,6 @@ public void testB() { runMachine(EBusUtils.toByteArray(masterTelegramPart)); - } catch (EBusTypeException e) { - - logger.info(EBusUtils.toHexDumpString(bb).toString()); - logger.info(e.getLocalizedMessage()); - errors++; - } catch (EBusDataException e) { logger.info(EBusUtils.toHexDumpString(bb).toString()); diff --git a/src/test/java/de/csdev/ebus/service/device/DeviceTableTests.java b/src/test/java/de/csdev/ebus/service/device/DeviceTableTests.java new file mode 100644 index 0000000..8f56839 --- /dev/null +++ b/src/test/java/de/csdev/ebus/service/device/DeviceTableTests.java @@ -0,0 +1,65 @@ + +/** + * Copyright (c) 2016-2020 by the respective copyright holders. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package de.csdev.ebus.service.device; + +import static org.junit.Assert.fail; + +import java.util.HashMap; + +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.junit.Test; + +public class DeviceTableTests { + + @Test + public void testMetrics() { + + EBusDeviceTable table = new EBusDeviceTable(); + table.setOwnAddress((byte) 0xFF); + + HashMap<@NonNull String, @Nullable Object> data = new HashMap<>(); + data.put("device_id", null); + data.put("hardware_version", null); + data.put("software_version", null); + data.put("vendor", null); + + table.updateDevice((byte) 0x00, data); + + data.put("device_id", "wrong"); + data.put("hardware_version", "wrong"); + data.put("software_version", "wrong"); + data.put("vendor", "wrong"); + table.updateDevice((byte) 0x00, data); + + data.put("device_id", new byte[] {0x00, 0x00}); + try { + table.updateDevice((byte) 0x00, data); + fail("Should cause an IllegalArgumentException !"); + } catch(IllegalArgumentException e) { + // expected + } + + data.put("device_id", new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); + try { + table.updateDevice((byte) 0x00, data); + fail("Should cause an IllegalArgumentException !"); + } catch(IllegalArgumentException e) { + // expected + } + + data.put("device_id", new byte[] {0x00, 0x00, 0x00, 0x00, 0x00}); + try { + table.updateDevice((byte) 0x00, data); + } catch(IllegalArgumentException e) { + fail("Should NOT cause an IllegalArgumentException !"); + } + } +} diff --git a/src/test/java/de/csdev/ebus/wip/ClientTest.java b/src/test/java/de/csdev/ebus/wip/ClientTest.java index e9fe5ba..ce31fcd 100644 --- a/src/test/java/de/csdev/ebus/wip/ClientTest.java +++ b/src/test/java/de/csdev/ebus/wip/ClientTest.java @@ -51,7 +51,6 @@ public void xxx() throws EBusTypeException, IOException, InterruptedException { EBusCommandRegistry commandRegistry = new EBusCommandRegistry(EBusConfigurationReader.class, true); - @SuppressWarnings("null") EBusLowLevelController controller = new EBusLowLevelController(emulator); EBusClient client = new EBusClient(commandRegistry); @@ -64,7 +63,6 @@ public void xxx() throws EBusTypeException, IOException, InterruptedException { controller.addEBusEventListener(new IEBusConnectorEventListener() { - @SuppressWarnings("null") @Override public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueId) { // noop @@ -91,7 +89,6 @@ public void onConnectionStatusChanged(@NonNull ConnectionStatus status) { client.getResolverService().addEBusParserListener(new IEBusParserListener() { - @SuppressWarnings("null") @Override public void onTelegramResolved(@NonNull IEBusCommandMethod commandChannel, Map result, byte[] receivedData, @Nullable Integer sendQueueId) { diff --git a/src/test/java/de/csdev/ebus/wip/ClientTest2.java b/src/test/java/de/csdev/ebus/wip/ClientTest2.java index dac63c4..7ceccd5 100644 --- a/src/test/java/de/csdev/ebus/wip/ClientTest2.java +++ b/src/test/java/de/csdev/ebus/wip/ClientTest2.java @@ -49,7 +49,6 @@ public void testNoSlaveResponse() EBusCommandRegistry commandRegistry = new EBusCommandRegistry(EBusConfigurationReader.class, true); - @SuppressWarnings("null") EBusLowLevelController controller = new EBusLowLevelController(emulator); EBusClient client = new EBusClient(commandRegistry); @@ -58,27 +57,21 @@ public void testNoSlaveResponse() controller.addEBusEventListener(new IEBusConnectorEventListener() { - @SuppressWarnings("null") @Override public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueId) { logger.error("ClientTest.xxx().new EBusConnectorEventListener() {...}.onTelegramReceived()"); } - @SuppressWarnings("null") @Override public void onTelegramException(EBusDataException exception, @Nullable Integer sendQueueId) { logger.error(exception.getLocalizedMessage()); - // TODO Auto-generated method stub - // logger.error("ClientTest.xxx().new EBusConnectorEventListener() {...}.onTelegramException()"); } - @SuppressWarnings("null") @Override public void onConnectionException(Exception e) { logger.error("ClientTest.xxx().new EBusConnectorEventListener() {...}.onConnectionException()"); } - @SuppressWarnings("null") @Override public void onConnectionStatusChanged(ConnectionStatus status) { logger.error( @@ -88,7 +81,6 @@ public void onConnectionStatusChanged(ConnectionStatus status) { client.getResolverService().addEBusParserListener(new IEBusParserListener() { - @SuppressWarnings("null") @Override public void onTelegramResolved(IEBusCommandMethod commandChannel, Map result, byte[] receivedData, @Nullable Integer sendQueueId) { diff --git a/src/test/java/de/csdev/ebus/wip/ClientTest3.java b/src/test/java/de/csdev/ebus/wip/ClientTest3.java index 159248c..7cb2828 100644 --- a/src/test/java/de/csdev/ebus/wip/ClientTest3.java +++ b/src/test/java/de/csdev/ebus/wip/ClientTest3.java @@ -47,7 +47,6 @@ public void testNoSlaveResponse() EBusCommandRegistry commandRegistry = new EBusCommandRegistry(EBusConfigurationReader.class, true); - @SuppressWarnings("null") EBusLowLevelController controller = new EBusLowLevelController(connection); EBusClient client = new EBusClient(commandRegistry); @@ -56,29 +55,21 @@ public void testNoSlaveResponse() controller.addEBusEventListener(new IEBusConnectorEventListener() { - @SuppressWarnings("null") @Override public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueId) { - // TODO Auto-generated method stub logger.info("Received: " + EBusUtils.toHexDumpString(receivedData).toString()); } - @SuppressWarnings("null") @Override public void onTelegramException(EBusDataException exception, @Nullable Integer sendQueueId) { - System.err.println(exception.getLocalizedMessage()); - // logger.error(exception.getLocalizedMessage()); - // TODO Auto-gen1erated method stub - // logger.error("ClientTest.xxx().new EBusConnectorEventListener() {...}.onTelegramException()"); + logger.error(exception.getLocalizedMessage()); } - @SuppressWarnings("null") @Override public void onConnectionException(Exception e) { logger.info("ClientTest.xxx().new EBusConnectorEventListener() {...}.onConnectionException()"); } - @SuppressWarnings("null") @Override public void onConnectionStatusChanged(ConnectionStatus status) { logger.info( diff --git a/src/test/java/de/csdev/ebus/wip/ConfigurationReaderTest.java b/src/test/java/de/csdev/ebus/wip/ConfigurationReaderTest.java index b88a5a0..abdb87f 100644 --- a/src/test/java/de/csdev/ebus/wip/ConfigurationReaderTest.java +++ b/src/test/java/de/csdev/ebus/wip/ConfigurationReaderTest.java @@ -9,6 +9,7 @@ package de.csdev.ebus.wip; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import java.io.IOException; import java.net.URL; @@ -17,6 +18,9 @@ import java.util.Map; import java.util.Map.Entry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.csdev.ebus.StaticTestTelegrams; import de.csdev.ebus.cfg.EBusConfigurationReaderException; import de.csdev.ebus.cfg.std.EBusConfigurationReader; @@ -35,8 +39,9 @@ */ public class ConfigurationReaderTest { + private final Logger logger = LoggerFactory.getLogger(EBusCustomParserTest.class); + // @Test - @SuppressWarnings("null") public void testIsMasterAddress() throws IOException, EBusTypeException, EBusConfigurationReaderException { URL url = EBusConfigurationReader.class.getResource("/commands/wolf-sm1-configuration.json"); @@ -67,8 +72,8 @@ public void testIsMasterAddress() throws IOException, EBusTypeException, EBusCon System.out.println(xx); } catch (EBusTypeException | EBusCommandException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + logger.error("error!", e); + fail(); } } diff --git a/src/test/java/de/csdev/ebus/wip/EBusCustomParserTest.java b/src/test/java/de/csdev/ebus/wip/EBusCustomParserTest.java index 0257deb..34efdfb 100644 --- a/src/test/java/de/csdev/ebus/wip/EBusCustomParserTest.java +++ b/src/test/java/de/csdev/ebus/wip/EBusCustomParserTest.java @@ -55,11 +55,11 @@ public void test_BuildMasterTelegram() { collection.getId(), EBusUtils.toHexDumpString(masterTelegram))); } catch (EBusTypeException e) { - e.printStackTrace(); + logger.error("error!", e); fail(); } catch (EBusCommandException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + logger.error("error!", e); + fail(); } } diff --git a/src/test/java/de/csdev/ebus/wip/EBusWolfSM1TelegramTest2XXX.java b/src/test/java/de/csdev/ebus/wip/EBusWolfSM1TelegramTest2XXX.java index ffd6e0b..ffdcf36 100644 --- a/src/test/java/de/csdev/ebus/wip/EBusWolfSM1TelegramTest2XXX.java +++ b/src/test/java/de/csdev/ebus/wip/EBusWolfSM1TelegramTest2XXX.java @@ -8,6 +8,8 @@ */ package de.csdev.ebus.wip; +import static org.junit.Assert.fail; + import java.io.IOException; import java.nio.ByteBuffer; @@ -56,12 +58,9 @@ public void testSolarCommands2() { ByteBuffer buildTelegram = client.buildTelegram(method, (byte) 0x08, null); logger.info("{} -> {}", method.getMethod(), EBusUtils.toHexDumpString(buildTelegram)); - } catch (EBusTypeException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (EBusCommandException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (EBusTypeException | EBusCommandException e) { + logger.error("error!", e); + fail(); } } } diff --git a/src/test/java/de/csdev/ebus/wip/EBusdControllerTest.java b/src/test/java/de/csdev/ebus/wip/EBusdControllerTest.java index 5a5082d..fd1acb3 100644 --- a/src/test/java/de/csdev/ebus/wip/EBusdControllerTest.java +++ b/src/test/java/de/csdev/ebus/wip/EBusdControllerTest.java @@ -23,14 +23,13 @@ import de.csdev.ebus.core.EBusControllerException; import de.csdev.ebus.core.EBusDataException; import de.csdev.ebus.core.EBusEbusdController; -import de.csdev.ebus.core.EBusStateMachineTest; import de.csdev.ebus.core.IEBusConnectorEventListener; import de.csdev.ebus.core.IEBusController.ConnectionStatus; import de.csdev.ebus.utils.EBusUtils; public class EBusdControllerTest { - private static final Logger logger = LoggerFactory.getLogger(EBusStateMachineTest.class); + private static final Logger logger = LoggerFactory.getLogger(EBusdControllerTest.class); // private IEBusConnection connection; @@ -55,33 +54,23 @@ public void testNoSlaveResponse() controller.addEBusEventListener(new IEBusConnectorEventListener() { - @SuppressWarnings("null") @Override public void onTelegramReceived(byte[] receivedData, @Nullable Integer sendQueueId) { - // TODO Auto-generated method stub logger.info("Received: " + EBusUtils.toHexDumpString(receivedData).toString()); } - @SuppressWarnings("null") @Override public void onTelegramException(EBusDataException exception, @Nullable Integer sendQueueId) { - System.err.println(exception.getLocalizedMessage()); - // logger.error(exception.getLocalizedMessage()); - // TODO Auto-gen1erated method stub - // logger.error("ClientTest.xxx().new EBusConnectorEventListener() {...}.onTelegramException()"); + logger.error(exception.getLocalizedMessage()); } - @SuppressWarnings("null") @Override public void onConnectionException(Exception e) { - // TODO Auto-generated method stub logger.info("ClientTest.xxx().new EBusConnectorEventListener() {...}.onConnectionException()"); } - @SuppressWarnings("null") @Override public void onConnectionStatusChanged(ConnectionStatus status) { - // TODO Auto-generated method stub logger.info( "EBusdControllerTest.testNoSlaveResponse().new IEBusConnectorEventListener() {...}.onConnectionStatusChanged()"); } diff --git a/src/test/java/de/csdev/ebus/wip/EmulatorTest.java b/src/test/java/de/csdev/ebus/wip/EmulatorTest.java index 887c51f..de89578 100644 --- a/src/test/java/de/csdev/ebus/wip/EmulatorTest.java +++ b/src/test/java/de/csdev/ebus/wip/EmulatorTest.java @@ -8,10 +8,17 @@ */ package de.csdev.ebus.wip; +import static org.junit.Assert.fail; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.csdev.ebus.utils.Emulator; public class EmulatorTest { + private static final Logger logger = LoggerFactory.getLogger(EmulatorTest.class); + // @Test public void xxx() { @@ -25,8 +32,8 @@ public void xxx() { Thread.sleep(5000); } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + logger.error("error!", e); + fail(); } }