Skip to content

Assignment1 abdul azim#10

Open
ImAzimm wants to merge 10 commits intomainfrom
assignment1_AbdulAzim
Open

Assignment1 abdul azim#10
ImAzimm wants to merge 10 commits intomainfrom
assignment1_AbdulAzim

Conversation

@ImAzimm
Copy link
Collaborator

@ImAzimm ImAzimm commented Dec 5, 2025

Title: refactor(core): improve concurrency, clarity and maintainability across multiple bundles

Summary

  • Branch: assignment1_AbdulAzim
  • Base: main (RareZyn/openhab-core)
  • Scope: Multiple refactorings across openHAB core bundles to fix concurrency, reduce duplication, extract constants, and add documentation and logging.
  1. The addressed issue (1 mark)
  • Critical concurrency bug in GenericItemChannelLinkProvider (global transaction state causing cross-context contamination).
  • Thread-safety risks (non-concurrent collections and global locking) in FolderObserver and a non-concurrent live cache in SemanticsMetadataProvider.
  • Maintainability issues: long methods, duplicated logic, and scattered magic strings in YamlItemFileConverter and DslThingFileConverter.
  1. What I reengineered (1.5 marks)
  • DslThingFileConverter: Added class-level constants and ModelThingBuilder (Builder pattern) to reduce parameter coupling and centralize validation.
  • GenericItemChannelLinkProvider: Replaced global transaction maps with per-context maps, hardened parsing, added JavaDoc and 10 unit tests covering parsing and concurrency.
  • FolderObserver: Replaced non-thread-safe collections with concurrent collections, added per-instance repoLock, extracted constants and helper validation.
  • YamlItemFileConverter: Extracted 6 magic strings to constants, added LOGGER, replaced silent exception handling, extracted type/dimension helpers and split buildItemDTO() into focused submethods.
  • SemanticsMetadataProvider: Replaced TreeMap with ConcurrentSkipListMap and returned immutable snapshots; replaced non-standard getFirst() with standard get(0) and extracted common relation logic.
  1. Reengineering strategy / approach used (1.5 marks)
  • Strategy: Implementation-level rework (no public API changes), incremental and test-driven.
  • Techniques: Extract method/constant, Builder pattern, per-context state isolation, use of concurrent collections, add logging and JavaDoc.
  • Verification: Ran bundle-level unit tests and applied Spotless formatting after changes; all affected bundle tests passed locally.
  1. Impact of changes (1 mark)
  • Correctness: Fixed a concurrency bug that could cause data corruption in multi-context updates.
  • Maintainability: Reduced cognitive complexity (shorter methods, helper functions), centralized configuration via constants, and improved documentation.
  • Risk: Low — changes are internal; public behavior preserved and covered by tests.

Files changed (high level)

  • bundles/org.openhab.core.model.thing/.../DslThingFileConverter.java
  • bundles/org.openhab.core.model.thing/.../GenericItemChannelLinkProvider.java (+ tests)
  • bundles/org.openhab.core.model.core/.../FolderObserver.java
  • bundles/org.openhab.core.model.yaml/.../YamlItemFileConverter.java
  • bundles/org.openhab.core.semantics/.../SemanticsMetadataProvider.java

Notes

  • All changes are on branch assignment1_AbdulAzim in this fork (RareZyn/openhab-core).
  • I ran unit tests for affected bundles locally and applied code formatting.
  • If you want, I can squash and rebase before creation, or open the PR as-is for review.

… UIDs containing unnecessary double quotes when a segment includes a hyphen.

The existing implementation removes these quotes using a regex replacement but has several shortcomings:
- Platform-default charset usage may cause inconsistent output on different systems.
- The regex is recompiled on every method call.
- The logic mixes multiple responsibilities in one block, reducing readability.
- Logging suppresses the full stack trace, making debugging harder.
…umentation and error handling

- Extracted ModelThingBuilder to reduce parameter coupling
- Added constants and JavaDoc for clarity
- Improved error handling and UID normalization
- No behavior changes, internal refactor only
…ericItemChannelLinkProvider

Core improvements:
- **Critical Fix**: Replaced global transaction state with per-context maps to fix race condition
  - 'previousItemNames' (global Set)  'previousItemNamesByContext' (Map<String, Set<String>>)
  - 'addedItemChannels' (global Map keyed only by itemName)  'addedItemChannelsByContext' (Map<String, Map<String, Set<ChannelUID>>>)
  - Multiple concurrent contexts can now safely update without cross-contamination

- Enhanced binding configuration parsing
  - Added robust filtering of empty/whitespace-only tokens
  - Improved error handling and validation

- Added comprehensive JavaDoc to all public methods
  - processBindingConfiguration: explains format and error cases
  - createItemChannelLink: clarifies per-context link creation
  - startConfigurationUpdate: documents transaction semantics
  - stopConfigurationUpdate: explains cleanup and per-context state management
  - getAll() and getAllFromContext(): clarifies filtering and isolation

- Code clarity improvements
  - Changed indexOf check to contains() for better readability
  - Improved streaming code (entrySet vs keySet)
  - Better variable naming in map operations

Tests added:
- 10 comprehensive unit tests covering:
  - Single and multiple channel UID parsing
  - Empty/invalid binding config handling
  - Profile scope normalization
  - Concurrent context transaction isolation (validates core fix)
  - Channel lifecycle management during updates

All tests passing (10/10). Verified no breaking changes to existing tests.
…e clarity

Core improvements:
- **Thread Safety Fix**: Replaced non-concurrent collections with thread-safe variants
  - parsers (HashSet) -> ConcurrentHashMap.newKeySet()
  - missingParsers (HashSet) -> ConcurrentHashMap.newKeySet()
  - ignoredPaths (HashSet) -> ConcurrentHashMap.newKeySet()
  - namePathMap (HashMap) -> ConcurrentHashMap
  - Added dedicated repoLock object for coordinated repository operations
  - Replaced global class-level synchronization with instance-level repoLock

- **Code Clarity**: Introduced constants for magic values
  - EXPECTED_RELATIVE_NAME_COUNT = 2 (replaces hardcoded path depth)
  - EXTENSION_SEPARATOR = dot (replaces inline string literals)

- **Helper Methods**: Added isValidFolderName() to centralize folder name validation
  - Improves readability and reduces duplication

- **Documentation**: Added comprehensive JavaDoc to public API methods
  - addModelParser: explains registration and ready markers
  - removeModelParser: clarifies removal and model cleanup
  - activate: documents folder watching and initialization
  - deactivate: explains cleanup sequence
  - processWatchEvent: clarifies event handling and validation

Benefits:
- Multiple FolderObserver instances now share concurrent state safely
- Repository lock is isolated per instance, reducing contention
- Code is more maintainable with constants and helper methods
- API behavior is clearly documented

All tests pass (5/5). No breaking changes.
…ity and documentation

Extract 6 magic string constants (autoupdate, unit, stateDescription, pattern, profile) to class-level for single source of truth and reduced magic string usage.

Add logger field for proper error handling with debug logging on URISyntaxException instead of silent ignoring.

Extract dimension handling logic to helper methods:
- extractMainTypeAndDimension(): Centralize type/dimension parsing
- applyTypeAndDimensionToDTO(): Apply extracted type info to both Item and Group DTOs
Eliminates duplicate code that appeared twice in buildItemDTO().

Split long buildItemDTO() method (120 lines) into focused submethods:
- setGroupInfo(): Extract group-specific configuration
- setChannelInfo(): Extract channel link processing
- setMetadataInfo(): Extract metadata (unit, autoupdate, stateDescription) processing
Improves code readability and testability by following Single Responsibility Principle.

Add comprehensive JavaDoc to all 8 public methods:
- getFileFormatGenerator(), setItemsToBeGenerated(), generateFileFormat()
- getFileFormatParser(), startParsingFileFormat(), getParsedItems(), getParsedMetadata()
- getParsedStateFormatters(), finishParsingFileFormat()
Clarifies API intent, parameters, and return values.

Testing: All existing unit tests pass (8/8), no regressions.
Code quality: Applied spotless formatting for consistency.

This refactoring reduces cognitive complexity, improves maintainability through extraction and documentation, and addresses error handling gaps.
… relation helper

- Use ConcurrentSkipListMap for semantics to provide thread-safe ordered cache and return immutable snapshot from getAll()
- Replace non-standard getFirst() calls with get(0) to use standard List API
- Extract common parent/member processing into processRelations() helper to remove duplication

Runs tests: all semantics tests pass.
@RareZyn RareZyn requested a review from suhadaudd11 December 5, 2025 14:00
Copy link
Collaborator

@suhadaudd11 suhadaudd11 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants