├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── jmh.yml │ └── publish.yml ├── .gitignore ├── .idea ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── copyright │ ├── ApacheV2.xml │ └── profiles_settings.xml └── markdown.xml ├── LICENSE ├── README.md ├── build.gradle.kts ├── coap-cli ├── README.md ├── build.gradle.kts ├── coap └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mbed │ │ │ └── coap │ │ │ ├── cli │ │ │ ├── DeviceEmulator.java │ │ │ ├── KeystoreUtils.java │ │ │ ├── Main.java │ │ │ ├── SendCommand.java │ │ │ ├── TransportOptions.java │ │ │ ├── TransportProvider.java │ │ │ └── providers │ │ │ │ ├── CoapSerializer.java │ │ │ │ ├── JdkProvider.java │ │ │ │ ├── MbedtlsProvider.java │ │ │ │ ├── OpensslProvider.java │ │ │ │ ├── Pair.java │ │ │ │ ├── PlainTextProvider.java │ │ │ │ └── StandardIoProvider.java │ │ │ └── transport │ │ │ └── stdio │ │ │ ├── OpensslProcessTransport.java │ │ │ └── StreamBlockingTransport.java │ └── resources │ │ └── logback.xml │ └── test │ ├── java │ └── com │ │ └── mbed │ │ └── coap │ │ ├── cli │ │ ├── CoapCliTest.java │ │ └── providers │ │ │ └── PairTest.java │ │ └── transport │ │ └── stdio │ │ └── StreamBlockingTransportTest.java │ └── resources │ └── logback-test.xml ├── coap-core ├── build.gradle.kts ├── diagrams.puml └── src │ ├── jmh │ └── java │ │ └── microbenchmark │ │ ├── CoapSerializerBenchmark.java │ │ ├── ServerBenchmark.java │ │ └── UdpTransportBenchmark.java │ ├── main │ ├── java │ │ └── com │ │ │ └── mbed │ │ │ └── coap │ │ │ ├── CoapConstants.java │ │ │ ├── client │ │ │ ├── CoapClient.java │ │ │ └── RegistrationManager.java │ │ │ ├── exception │ │ │ ├── CoapBlockException.java │ │ │ ├── CoapBlockTooLargeEntityException.java │ │ │ ├── CoapCodeException.java │ │ │ ├── CoapException.java │ │ │ ├── CoapMessageFormatException.java │ │ │ ├── CoapRequestEntityIncomplete.java │ │ │ ├── CoapRequestEntityTooLarge.java │ │ │ ├── CoapTimeoutException.java │ │ │ └── TooManyRequestsForEndpointException.java │ │ │ ├── linkformat │ │ │ ├── LinkFormat.java │ │ │ ├── LinkFormatBuilder.java │ │ │ └── PToken.java │ │ │ ├── packet │ │ │ ├── BasicHeaderOptions.java │ │ │ ├── BlockOption.java │ │ │ ├── BlockSize.java │ │ │ ├── CoapOptionsBuilder.java │ │ │ ├── CoapPacket.java │ │ │ ├── CoapRequest.java │ │ │ ├── CoapResponse.java │ │ │ ├── CoapSerializer.java │ │ │ ├── Code.java │ │ │ ├── DataConvertingUtility.java │ │ │ ├── EofInputStream.java │ │ │ ├── HeaderOptions.java │ │ │ ├── MediaTypes.java │ │ │ ├── MessageType.java │ │ │ ├── Method.java │ │ │ ├── Opaque.java │ │ │ ├── PacketUtils.java │ │ │ ├── RawOption.java │ │ │ └── SeparateResponse.java │ │ │ ├── server │ │ │ ├── CoapRequestId.java │ │ │ ├── CoapServer.java │ │ │ ├── CoapServerBuilder.java │ │ │ ├── CoapServerGroup.java │ │ │ ├── CriticalOptionVerifier.java │ │ │ ├── DefaultDuplicateDetectorCache.java │ │ │ ├── DuplicatedCoapMessageCallback.java │ │ │ ├── NotificationValidator.java │ │ │ ├── ObservationHandler.java │ │ │ ├── ObserveRequestFilter.java │ │ │ ├── PutOnlyMap.java │ │ │ ├── RescueFilter.java │ │ │ ├── RouterService.java │ │ │ ├── block │ │ │ │ ├── BlockRequestId.java │ │ │ │ ├── BlockWiseCallback.java │ │ │ │ ├── BlockWiseIncomingFilter.java │ │ │ │ ├── BlockWiseIncomingTransaction.java │ │ │ │ ├── BlockWiseNotificationFilter.java │ │ │ │ ├── BlockWiseOutgoingFilter.java │ │ │ │ └── BlockWiseTransfer.java │ │ │ ├── filter │ │ │ │ ├── CongestionControlFilter.java │ │ │ │ ├── EchoFilter.java │ │ │ │ ├── EtagGeneratorFilter.java │ │ │ │ ├── EtagValidatorFilter.java │ │ │ │ ├── MaxAllowedPayloadFilter.java │ │ │ │ ├── RequestLoggerFilter.java │ │ │ │ ├── ResponseTimeoutFilter.java │ │ │ │ ├── SequentialTaskRunner.java │ │ │ │ └── TokenGeneratorFilter.java │ │ │ ├── messaging │ │ │ │ ├── Capabilities.java │ │ │ │ ├── CapabilitiesResolver.java │ │ │ │ ├── CoapDispatcher.java │ │ │ │ ├── CoapRequestConverter.java │ │ │ │ ├── DuplicateDetector.java │ │ │ │ ├── ExchangeFilter.java │ │ │ │ ├── MessageIdSupplier.java │ │ │ │ ├── MessageIdSupplierImpl.java │ │ │ │ ├── ObservationMapper.java │ │ │ │ ├── PiggybackedCorrelation.java │ │ │ │ ├── PiggybackedExchangeFilter.java │ │ │ │ ├── RequestTagSupplier.java │ │ │ │ ├── RetransmissionFilter.java │ │ │ │ └── TransactionId.java │ │ │ └── observe │ │ │ │ ├── HashMapObservationsStore.java │ │ │ │ ├── NotificationsReceiver.java │ │ │ │ ├── ObservationsStore.java │ │ │ │ └── ObserversManager.java │ │ │ ├── transmission │ │ │ └── RetransmissionBackOff.java │ │ │ ├── transport │ │ │ ├── BlockingCoapTransport.java │ │ │ ├── CoapTransport.java │ │ │ ├── LoggingCoapTransport.java │ │ │ ├── TransportContext.java │ │ │ └── udp │ │ │ │ └── DatagramSocketTransport.java │ │ │ └── utils │ │ │ ├── ExecutorHelpers.java │ │ │ ├── Filter.java │ │ │ ├── FutureHelpers.java │ │ │ ├── Service.java │ │ │ ├── Timer.java │ │ │ └── Validations.java │ └── resources │ │ └── LICENSE │ ├── test │ ├── java │ │ ├── com │ │ │ └── mbed │ │ │ │ └── coap │ │ │ │ ├── client │ │ │ │ ├── CoapClientTest.java │ │ │ │ └── RegistrationManagerTest.java │ │ │ │ ├── linkformat │ │ │ │ └── LinkFormatTest.java │ │ │ │ ├── packet │ │ │ │ ├── BlockOptionTest.java │ │ │ │ ├── BlockSizeTest.java │ │ │ │ ├── CoapOptionsBuilderTest.java │ │ │ │ ├── CoapPacketTest.java │ │ │ │ ├── CoapPacketToStringTest.java │ │ │ │ ├── CoapRequestTest.java │ │ │ │ ├── CoapResponseTest.java │ │ │ │ ├── CodeTest.java │ │ │ │ ├── DataConvertingUtilityTest.java │ │ │ │ ├── EofInputStreamTest.java │ │ │ │ ├── HeaderOptionsTest.java │ │ │ │ ├── MediaTypesTest.java │ │ │ │ ├── OpaqueTest.java │ │ │ │ ├── RawOptionTest.java │ │ │ │ └── SeparateResponseTest.java │ │ │ │ ├── server │ │ │ │ ├── CoapRequestIdTest.java │ │ │ │ ├── CoapServerBuilderTest.java │ │ │ │ ├── CoapServerGroupTest.java │ │ │ │ ├── CoapServerTest.java │ │ │ │ ├── CriticalOptionVerifierTest.java │ │ │ │ ├── DefaultDuplicateDetectorCacheTest.java │ │ │ │ ├── NotificationValidatorTest.java │ │ │ │ ├── ObservationHandlerTest.java │ │ │ │ ├── ObserveRequestFilterTest.java │ │ │ │ ├── RescueFilterTest.java │ │ │ │ ├── RouterServiceTest.java │ │ │ │ ├── RoutingServiceTest.java │ │ │ │ ├── block │ │ │ │ │ ├── BlockRequestIdTest.java │ │ │ │ │ ├── BlockWiseCallbackTest.java │ │ │ │ │ ├── BlockWiseIncomingFilterTest.java │ │ │ │ │ ├── BlockWiseIncomingTransactionTest.java │ │ │ │ │ ├── BlockWiseNotificationFilterTest.java │ │ │ │ │ ├── BlockWiseOutgoingFilterTest.java │ │ │ │ │ └── BlockWiseTransferTest.java │ │ │ │ ├── filter │ │ │ │ │ ├── CongestionControlFilterTest.java │ │ │ │ │ ├── EchoFilterTest.java │ │ │ │ │ ├── EtagGeneratorFilterTest.java │ │ │ │ │ ├── EtagValidatorFilterTest.java │ │ │ │ │ ├── MaxAllowedPayloadFilterTest.java │ │ │ │ │ ├── RequestLoggerFilterTest.java │ │ │ │ │ ├── ResponseTimeoutFilterTest.java │ │ │ │ │ ├── SequentialTaskRunnerTest.java │ │ │ │ │ └── TokenGeneratorFilterTest.java │ │ │ │ ├── messaging │ │ │ │ │ ├── CapabilitiesTest.java │ │ │ │ │ ├── CoapDispatcherTest.java │ │ │ │ │ ├── CoapRequestConverterTest.java │ │ │ │ │ ├── DuplicateDetectorTest.java │ │ │ │ │ ├── ExchangeFilterTest.java │ │ │ │ │ ├── ObservationMapperTest.java │ │ │ │ │ ├── PiggybackedCorrelationTest.java │ │ │ │ │ ├── PiggybackedExchangeFilterTest.java │ │ │ │ │ ├── RequestTagSupplierTest.java │ │ │ │ │ └── RetransmissionFilterTest.java │ │ │ │ └── observe │ │ │ │ │ ├── NotificationsReceiverTest.java │ │ │ │ │ └── ObserversManagerTest.java │ │ │ │ ├── transmission │ │ │ │ └── RetransmissionBackOffTest.java │ │ │ │ ├── transport │ │ │ │ ├── LoggingCoapTransportTest.java │ │ │ │ ├── TransportContextTest.java │ │ │ │ └── udp │ │ │ │ │ └── DatagramSocketTransportTest.java │ │ │ │ └── utils │ │ │ │ ├── AsyncQueueTest.java │ │ │ │ ├── Exceptions.java │ │ │ │ ├── FilterTest.java │ │ │ │ ├── FutureHelpersTest.java │ │ │ │ ├── FutureQueue.java │ │ │ │ ├── IpPortAddressTest.java │ │ │ │ └── TimerTest.java │ │ └── protocolTests │ │ │ ├── Block1TransferMaxSizeTest.java │ │ │ ├── Block2TransferMaxSizeTest.java │ │ │ ├── BlockTest.java │ │ │ ├── BlockTransferOnDemandTest.java │ │ │ ├── BlockwiseTransferWithTest.java │ │ │ ├── ClientServerWithBlocksTest.java │ │ │ ├── ClientTest.java │ │ │ ├── DuplicateErrorsTest.java │ │ │ ├── DuplicateTest.java │ │ │ ├── ForwardingTransportContextTest.java │ │ │ ├── MalformedPacketTest.java │ │ │ ├── NonConfirmableTransactionsTest.java │ │ │ ├── Observation2Test.java │ │ │ ├── ObservationTest.java │ │ │ ├── QueueRequestsTest.java │ │ │ ├── SeparateResponseTest.java │ │ │ ├── TimeoutTest.java │ │ │ ├── UdpIntegrationTest.java │ │ │ ├── UnreliableTransportTest.java │ │ │ ├── UsageTest.java │ │ │ └── utils │ │ │ └── TransportConnectorMock.java │ └── resources │ │ └── logback-test.xml │ └── testFixtures │ └── java │ ├── com │ └── mbed │ │ └── coap │ │ ├── transport │ │ └── InMemoryCoapTransport.java │ │ └── utils │ │ ├── Assertions.java │ │ ├── AsyncQueue.java │ │ ├── Bytes.java │ │ ├── CoapPacketAssertion.java │ │ ├── CoapRequestBuilderFilter.java │ │ ├── IpPortAddress.java │ │ ├── MockTimer.java │ │ ├── Networks.java │ │ └── ObservableResource.java │ └── protocolTests │ ├── IntegrationTestBase.java │ └── utils │ ├── CoapPacketBuilder.java │ ├── MockCoapTransport.java │ └── StubNotificationsReceiver.java ├── coap-mbedtls ├── build.gradle.kts └── src │ ├── main │ └── java │ │ └── org │ │ └── opencoap │ │ └── transport │ │ └── mbedtls │ │ ├── DtlsSessionSuspensionService.java │ │ ├── DtlsTransportContext.java │ │ └── MbedtlsCoapTransport.java │ └── test │ ├── java │ └── org │ │ └── opencoap │ │ └── transport │ │ └── mbedtls │ │ ├── DtlsSessionSuspensionServiceTest.java │ │ ├── DtlsTransportContextTest.java │ │ ├── MbedtlsCoapTransportTest.java │ │ ├── MbedtlsNettyTest.java │ │ └── MultithreadedMbedtlsNettyTest.java │ └── resources │ └── logback-test.xml ├── coap-metrics ├── build.gradle.kts └── src │ ├── main │ └── java │ │ └── org │ │ └── opencoap │ │ └── coap │ │ └── metrics │ │ └── micrometer │ │ └── MicrometerMetricsFilter.java │ └── test │ └── java │ └── org │ └── opencoap │ └── coap │ └── metrics │ └── micrometer │ └── MicrometerMetricsFilterTest.java ├── coap-netty ├── build.gradle.kts └── src │ ├── jmh │ └── java │ │ └── microbenchmark │ │ └── NettyBenchmark.java │ ├── main │ └── java │ │ └── org │ │ └── opencoap │ │ └── coap │ │ └── netty │ │ ├── CoapCodec.java │ │ ├── NettyCoapTransport.java │ │ └── NettyUtils.java │ └── test │ ├── java │ └── org │ │ └── opencoap │ │ └── coap │ │ └── netty │ │ ├── CoapCodecTest.java │ │ ├── MultiChannelNettyTest.java │ │ ├── NettyCoapTransportTest.java │ │ ├── NettyTest.java │ │ └── NettyUtilsTest.java │ └── resources │ └── logback-test.xml ├── coap-tcp ├── build.gradle.kts └── src │ ├── main │ └── java │ │ └── com │ │ └── mbed │ │ └── coap │ │ ├── packet │ │ ├── CoapTcpPacketConverter.java │ │ ├── CoapTcpPacketSerializer.java │ │ ├── SignalingOptions.java │ │ └── SignallingHeaderOptions.java │ │ ├── server │ │ ├── CoapServerBuilderForTcp.java │ │ ├── TcpCoapServer.java │ │ └── messaging │ │ │ ├── CapabilitiesStorage.java │ │ │ ├── CapabilitiesStorageImpl.java │ │ │ ├── CoapTcpDispatcher.java │ │ │ ├── PayloadSizeVerifier.java │ │ │ └── TcpExchangeFilter.java │ │ └── transport │ │ ├── CoapTcpListener.java │ │ ├── CoapTcpTransport.java │ │ └── javassl │ │ ├── SSLSocketClientTransport.java │ │ └── SocketClientTransport.java │ └── test │ ├── java │ ├── com │ │ └── mbed │ │ │ └── coap │ │ │ ├── packet │ │ │ ├── CoapPacketWithSignToStringTest.java │ │ │ ├── CoapTcpPacketConverterTest.java │ │ │ ├── CoapTcpPacketSerializerTest.java │ │ │ ├── SignalingOptionsTest.java │ │ │ └── SignallingHeaderOptionsTest.java │ │ │ ├── server │ │ │ └── messaging │ │ │ │ ├── CapabilitiesStorageImplTest.java │ │ │ │ ├── CoapTcpDispatcherTest.java │ │ │ │ ├── PayloadSizeVerifierTest.java │ │ │ │ └── TcpExchangeFilterTest.java │ │ │ └── transport │ │ │ └── javassl │ │ │ ├── SSLSocketClientTransportTest.java │ │ │ ├── SSLUtils.java │ │ │ ├── SingleConnectionSSLSocketServerTransport.java │ │ │ └── SingleConnectionSocketServerTransport.java │ └── protocolTests │ │ ├── CoapServerBlocksTest.java │ │ ├── TcpIntegrationTest.java │ │ └── utils │ │ └── MockCoapTcpTransport.java │ └── resources │ ├── regenerate-keystores.sh │ ├── test-client.jks │ └── test-server.jks ├── codecov.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── license-header.txt ├── lwm2m ├── build.gradle.kts └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mbed │ │ │ └── lwm2m │ │ │ ├── LWM2MID.java │ │ │ ├── LWM2MObject.java │ │ │ ├── LWM2MObjectInstance.java │ │ │ ├── LWM2MResource.java │ │ │ ├── LWM2MResourceInstance.java │ │ │ ├── LWM2MResourceType.java │ │ │ ├── json │ │ │ ├── JsonDeserializer.java │ │ │ ├── JsonResource.java │ │ │ ├── JsonResourceArray.java │ │ │ ├── JsonSerializer.java │ │ │ └── NumberTypeAdapter.java │ │ │ ├── model │ │ │ ├── DefaultResourceValidator.java │ │ │ ├── Instances.java │ │ │ ├── IntegerResourceValidator.java │ │ │ ├── InvalidResourceURIException.java │ │ │ ├── NotFoundException.java │ │ │ ├── ObjectModel.java │ │ │ ├── ObjectRegistry.java │ │ │ ├── OpaqueResourceValidator.java │ │ │ ├── ResourceModel.java │ │ │ ├── ResourceValidator.java │ │ │ ├── StringResourceValidator.java │ │ │ └── Type.java │ │ │ ├── tlv │ │ │ ├── TLV.java │ │ │ ├── TLVDeserializer.java │ │ │ └── TLVSerializer.java │ │ │ ├── transport │ │ │ ├── TransportBinding.java │ │ │ └── TransportBindingParseException.java │ │ │ └── utils │ │ │ └── HexArray.java │ └── resources │ │ ├── LICENSE │ │ └── com │ │ └── mbed │ │ └── lwm2m │ │ └── model │ │ └── lwm2m-objects.json │ └── test │ ├── java │ └── com │ │ └── mbed │ │ └── lwm2m │ │ ├── LWM2MIDTest.java │ │ ├── LWM2MObjectInstanceTest.java │ │ ├── LWM2MObjectTest.java │ │ ├── LWM2MResourceInstanceTest.java │ │ ├── LWM2MResourceTest.java │ │ ├── json │ │ ├── JsonDeserializerTest.java │ │ ├── JsonResourceArrayTest.java │ │ ├── JsonResourceTest.java │ │ └── JsonSerializerTest.java │ │ ├── model │ │ ├── ObjectRegistryTest.java │ │ └── ResourceModelTest.java │ │ ├── tlv │ │ ├── TLVDeserializerTest.java │ │ └── TLVSerializerTest.java │ │ └── transport │ │ └── TransportBindingTest.java │ └── resources │ ├── com │ └── mbed │ │ └── lwm2m │ │ ├── json │ │ ├── custom-object.json │ │ ├── device-object.json │ │ └── notification.json │ │ └── model │ │ └── lwm2m-test-objects.json │ └── logback-test.xml ├── pmd-rules.xml ├── settings.gradle.kts └── spotbugs-exlude.xml /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: / 5 | schedule: 6 | interval: "monthly" 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | schedule: 6 | - cron: '0 0 * * *' 7 | 8 | jobs: 9 | build: 10 | timeout-minutes: 5 11 | runs-on: ubuntu-latest 12 | strategy: 13 | fail-fast: false 14 | matrix: 15 | java: [ '8', '17', '21' ] 16 | permissions: 17 | contents: read 18 | packages: write 19 | 20 | steps: 21 | - uses: actions/checkout@v4 22 | - name: Set up JDK 23 | uses: actions/setup-java@v4 24 | with: 25 | java-version: ${{ matrix.java }} 26 | distribution: 'corretto' 27 | - name: Set up Gradle 28 | uses: gradle/actions/setup-gradle@v4 29 | 30 | - name: Build with Gradle 31 | run: ./gradlew build jacocoTestReport javadoc -i 32 | - uses: codecov/codecov-action@v5 33 | if: matrix.java == '21' 34 | env: 35 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 36 | -------------------------------------------------------------------------------- /.github/workflows/jmh.yml: -------------------------------------------------------------------------------- 1 | name: benchmark 2 | 3 | on: 4 | push: 5 | 6 | jobs: 7 | benchmark: 8 | timeout-minutes: 10 9 | if: github.repository == 'open-coap/java-coap' 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - name: Set up JDK 15 | uses: actions/setup-java@v4 16 | with: 17 | java-version: 17 18 | distribution: 'temurin' 19 | - name: Set up Gradle 20 | uses: gradle/actions/setup-gradle@v4 21 | - name: Build 22 | run: ./gradlew jmhJar 23 | - name: Run benchmarks 24 | run: ./gradlew jmh 25 | - name: print summary 26 | run: | 27 | echo '### JMH report' >> $GITHUB_STEP_SUMMARY 28 | echo '```' >> $GITHUB_STEP_SUMMARY 29 | find . -path '*/results/jmh/*.txt' -type f | xargs cat >> $GITHUB_STEP_SUMMARY 30 | echo '```' >> $GITHUB_STEP_SUMMARY 31 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | jobs: 9 | build: 10 | timeout-minutes: 5 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Set up JDK 8 16 | uses: actions/setup-java@v4 17 | with: 18 | java-version: '8' 19 | distribution: 'temurin' 20 | - name: Set up Gradle 21 | uses: gradle/actions/setup-gradle@v4 22 | - name: Publish with Gradle 23 | run: ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository -i 24 | env: 25 | ORG_GRADLE_PROJECT_signingKeyId: ${{ secrets.SIGNING_KEY_ID }} 26 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }} 27 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }} 28 | ORG_GRADLE_PROJECT_ossrhUserName: ${{ secrets.OSSRH_USERNAME }} 29 | ORG_GRADLE_PROJECT_ossrhPassword: ${{ secrets.OSSRH_PASSWORD }} 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | classes/ 5 | build/ 6 | nbactions.xml 7 | nb-configuration.xml 8 | *.iml 9 | .idea/ 10 | !.idea/copyright 11 | !.idea/codeStyles 12 | !.idea/markdown.xml 13 | .DS_Store 14 | coap-cli/*.pem 15 | coap-cli/*.jks 16 | *.tmp 17 | .gradle/ 18 | out/ 19 | *.session 20 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 40 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/copyright/ApacheV2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 10 | 11 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/markdown.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /coap-cli/README.md: -------------------------------------------------------------------------------- 1 | Coap command line tool 2 | ====================== 3 | 4 | Usage 5 | ----- 6 | 7 | ``` 8 | Usage: coap [COMMAND] 9 | Commands: 10 | send Send CoAP requests 11 | register Register to LwM2M server and simulate some simple resources 12 | ``` 13 | 14 | ### Supported schemes 15 | 16 | - `coap://` (RFC 7252) 17 | - `coaps://` (RFC 7252) 18 | - `coap+tcp://` (RFC 8323) 19 | - `coaps+tcp://` (RFC 8323) 20 | 21 | ### Examples 22 | 23 | - `./coap send GET coap://coap.me/.well-known/core` 24 | - `./coap register 'coap://leshan.eclipseprojects.io:5683/rd?ep=device007<=3600&b=U'` 25 | 26 | #### Running with openssl: 27 | 28 | coap register -k device01.jks -s openssl 'coaps://localhost:5684/rd?ep=device001' 29 | 30 | _Note:_ 31 | 32 | This requires `openssl` version that supports dtls. Use environment variable `COAPCLI_OPENSSL` to point to specific location of `openssl` binary. 33 | 34 | For example: `export COAPCLI_OPENSSL=/usr/local/opt/openssl@1.1/bin/openssl` 35 | 36 | #### Running with standard io (bidirectional pipe): 37 | 38 | mkfifo fifo 39 | coap register -s stdio "coaps://127.0.0.1:5683/rd?ep=test&aid=dm<=60" < fifo | \ 40 | socat -d -d - udp-sendto:localhost:5683 > fifo 41 | 42 | or 43 | 44 | coap register -s stdio "coaps://127.0.0.1:5683/rd?ep=test&aid=dm<=60" < fifo | \ 45 | openssl s_client -connect localhost:5684 -cipher PSK-AES128-CBC-SHA -psk 01010101010101010101010101010101 -psk_identity device-0000000001 -quiet > fifo 46 | 47 | Build distribution (zip) 48 | ------------------------ 49 | 50 | ./gradlew coap-cli:distZip 51 | -------------------------------------------------------------------------------- /coap-cli/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("application") 3 | } 4 | 5 | description = "coap-cli" 6 | 7 | dependencies { 8 | implementation(project(":coap-core")) 9 | implementation(project(":coap-tcp")) 10 | implementation(project(":lwm2m")) 11 | implementation(project(":coap-mbedtls")) 12 | implementation("org.slf4j:slf4j-api:2.0.17") 13 | implementation("ch.qos.logback:logback-classic:1.3.15") 14 | implementation("info.picocli:picocli:4.7.7") 15 | 16 | testImplementation("org.mockito:mockito-core:4.11.0") 17 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.13.0") 18 | testImplementation("org.awaitility:awaitility:4.3.0") 19 | testImplementation(testFixtures(project(":coap-core"))) 20 | } 21 | 22 | tasks { 23 | withType { enabled = false } 24 | withType { enabled = false } 25 | } 26 | 27 | application { 28 | mainClass.set("com.mbed.coap.cli.Main") 29 | } 30 | 31 | distributions { 32 | application.applicationName = "coap" 33 | main { 34 | distributionBaseName.set("coap-cli") 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /coap-cli/coap: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ../gradlew :coap-cli:installDist -q 4 | ./build/install/coap-cli/bin/coap $@ 5 | -------------------------------------------------------------------------------- /coap-cli/src/main/java/com/mbed/coap/cli/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.cli; 17 | 18 | import com.mbed.coap.packet.BlockSize; 19 | import picocli.CommandLine; 20 | import picocli.CommandLine.Command; 21 | 22 | @Command(name = "coap", subcommands = {SendCommand.class, DeviceEmulator.class}) 23 | public class Main { 24 | 25 | public static void main(String[] args) { 26 | int exitCode = createCommandLine().execute(args); 27 | if (exitCode >= 0) { 28 | System.exit(exitCode); 29 | } 30 | } 31 | 32 | static CommandLine createCommandLine() { 33 | return new CommandLine(new Main()) 34 | .registerConverter(BlockSize.class, s -> BlockSize.valueOf("S_" + s)); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /coap-cli/src/main/java/com/mbed/coap/cli/TransportProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.cli; 18 | 19 | import com.mbed.coap.cli.providers.Pair; 20 | import com.mbed.coap.packet.Opaque; 21 | import com.mbed.coap.transport.CoapTcpTransport; 22 | import com.mbed.coap.transport.CoapTransport; 23 | import java.io.IOException; 24 | import java.net.InetSocketAddress; 25 | import java.security.GeneralSecurityException; 26 | import java.security.KeyStore; 27 | 28 | public interface TransportProvider { 29 | 30 | default CoapTcpTransport createTCP(InetSocketAddress destAdr, KeyStore ks) throws GeneralSecurityException, IOException { 31 | throw new IllegalArgumentException("Not supported"); 32 | } 33 | 34 | default CoapTransport createUDP(InetSocketAddress destAdr, KeyStore ks, Pair psk) throws GeneralSecurityException, IOException { 35 | throw new IllegalArgumentException("Not supported"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /coap-cli/src/main/java/com/mbed/coap/cli/providers/Pair.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.cli.providers; 17 | 18 | import static java.util.Objects.requireNonNull; 19 | import java.util.Objects; 20 | import java.util.function.Function; 21 | 22 | public class Pair { 23 | public final K key; 24 | public final V value; 25 | 26 | private Pair(K key, V value) { 27 | this.key = requireNonNull(key); 28 | this.value = requireNonNull(value); 29 | } 30 | 31 | public static Pair of(K key, V value) { 32 | return new Pair<>(key, value); 33 | } 34 | 35 | public static Pair split(String text, char delimiter) { 36 | int splitIndex = text.lastIndexOf(delimiter); 37 | 38 | return new Pair<>(text.substring(0, splitIndex), text.substring(splitIndex + 1)); 39 | } 40 | 41 | public Pair mapValue(Function f) { 42 | return new Pair<>(key, f.apply(value)); 43 | } 44 | 45 | @Override 46 | public boolean equals(Object o) { 47 | if (this == o) { 48 | return true; 49 | } 50 | if (o == null || getClass() != o.getClass()) { 51 | return false; 52 | } 53 | Pair pair = (Pair) o; 54 | return Objects.equals(key, pair.key) && Objects.equals(value, pair.value); 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | return Objects.hash(key, value); 60 | } 61 | 62 | @Override 63 | public String toString() { 64 | return "Pair{" + 65 | "key=" + key + 66 | ", value=" + value + 67 | '}'; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /coap-cli/src/main/java/com/mbed/coap/cli/providers/PlainTextProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.cli.providers; 18 | 19 | import com.mbed.coap.cli.TransportProvider; 20 | import com.mbed.coap.packet.Opaque; 21 | import com.mbed.coap.transport.CoapTcpTransport; 22 | import com.mbed.coap.transport.CoapTransport; 23 | import com.mbed.coap.transport.javassl.SocketClientTransport; 24 | import com.mbed.coap.transport.udp.DatagramSocketTransport; 25 | import java.net.InetSocketAddress; 26 | import java.security.KeyStore; 27 | import javax.net.SocketFactory; 28 | 29 | public class PlainTextProvider implements TransportProvider { 30 | private final int bindPort; 31 | 32 | public PlainTextProvider(int bindPort) { 33 | this.bindPort = bindPort; 34 | } 35 | 36 | @Override 37 | public CoapTransport createUDP(InetSocketAddress destAdr, KeyStore ks, Pair psk) { 38 | return new DatagramSocketTransport(bindPort); 39 | } 40 | 41 | @Override 42 | public CoapTcpTransport createTCP(InetSocketAddress destAdr, KeyStore ks) { 43 | return new SocketClientTransport(destAdr, SocketFactory.getDefault(), true); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /coap-cli/src/main/java/com/mbed/coap/cli/providers/StandardIoProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.cli.providers; 18 | 19 | import com.mbed.coap.cli.TransportProvider; 20 | import com.mbed.coap.packet.Opaque; 21 | import com.mbed.coap.transport.CoapTcpTransport; 22 | import com.mbed.coap.transport.CoapTransport; 23 | import com.mbed.coap.transport.stdio.StreamBlockingTransport; 24 | import java.net.InetSocketAddress; 25 | import java.security.KeyStore; 26 | 27 | public class StandardIoProvider implements TransportProvider { 28 | 29 | @Override 30 | public CoapTcpTransport createTCP(InetSocketAddress destAdr, KeyStore ks) { 31 | return create(CoapSerializer.TCP, destAdr); 32 | } 33 | 34 | @Override 35 | public CoapTransport createUDP(InetSocketAddress destAdr, KeyStore ks, Pair psk) { 36 | return create(CoapSerializer.UDP, destAdr); 37 | } 38 | 39 | private CoapTcpTransport create(CoapSerializer coapSerializer, InetSocketAddress destAdr) { 40 | return StreamBlockingTransport.forStandardIO(destAdr, coapSerializer); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /coap-cli/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | System.err 9 | 10 | 11 | %d{HH:mm:ss} %-5p %m%n 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /coap-cli/src/test/java/com/mbed/coap/cli/providers/PairTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.cli.providers; 17 | 18 | import static com.mbed.coap.packet.Opaque.*; 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import com.mbed.coap.packet.Opaque; 21 | import org.junit.jupiter.api.Test; 22 | 23 | class PairTest { 24 | @Test 25 | void createFromString() { 26 | assertEquals(Pair.of("aaa", "1010"), Pair.split("aaa:1010", ':')); 27 | assertEquals(Pair.of("aaa", ""), Pair.split("aaa:", ':')); 28 | assertEquals(Pair.of("", "1010"), Pair.split(":1010", ':')); 29 | assertEquals(Pair.of("", ""), Pair.split(":", ':')); 30 | } 31 | 32 | @Test 33 | void mapValue() { 34 | assertEquals(Pair.of("aaa", ofBytes(1, 2)), Pair.of("aaa", "0102").mapValue(Opaque::decodeHex)); 35 | } 36 | } -------------------------------------------------------------------------------- /coap-cli/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | %d{HH:mm:ss} %-5p %m%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /coap-core/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java-library") 3 | id("java-test-fixtures") 4 | id("me.champeau.jmh") version "0.7.3" 5 | } 6 | 7 | description = "coap-core" 8 | 9 | dependencies { 10 | api("org.slf4j:slf4j-api:2.0.17") 11 | 12 | testFixturesApi("org.junit.jupiter:junit-jupiter-api:5.13.0") 13 | testFixturesApi("org.assertj:assertj-core:3.27.3") 14 | testFixturesApi("org.awaitility:awaitility:4.3.0") 15 | 16 | testImplementation("ch.qos.logback:logback-classic:1.3.15") 17 | testImplementation("org.mockito:mockito-core:4.11.0") 18 | testImplementation("nl.jqno.equalsverifier:equalsverifier:3.19.4") 19 | testImplementation("io.github.artsok:rerunner-jupiter:2.1.6") 20 | 21 | jmh("org.openjdk.jmh:jmh-core:1.37") 22 | jmh("org.openjdk.jmh:jmh-generator-bytecode:1.37") 23 | } 24 | 25 | tasks { 26 | named("pmdTestFixtures").get().enabled = false 27 | named("pmdJmh").get().enabled = false 28 | named("spotbugsJmh").get().enabled = false 29 | } 30 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/CoapConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap; 18 | 19 | import java.nio.charset.Charset; 20 | import java.nio.charset.StandardCharsets; 21 | import java.time.Duration; 22 | 23 | /** 24 | * CoAP constants that are defined in RFC 7252 document 25 | */ 26 | public final class CoapConstants { 27 | 28 | public static final int DEFAULT_PORT = 5683; 29 | public static final String WELL_KNOWN_CORE = "/.well-known/core"; 30 | public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; 31 | public static final Duration ACK_TIMEOUT = Duration.ofSeconds(2); 32 | public static final float ACK_RANDOM_FACTOR = 1.5f; 33 | public static final Short MAX_RETRANSMIT = 4; 34 | 35 | private CoapConstants() { 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapBlockException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.exception; 17 | 18 | public class CoapBlockException extends CoapException { 19 | public CoapBlockException(String message) { 20 | super(message); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapBlockTooLargeEntityException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.exception; 17 | 18 | /** 19 | * Too large entity received 20 | */ 21 | public class CoapBlockTooLargeEntityException extends CoapBlockException { 22 | public CoapBlockTooLargeEntityException(String message) { 23 | super(message); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapCodeException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.exception; 18 | 19 | import static com.mbed.coap.packet.CoapResponse.coapResponse; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.Code; 22 | 23 | 24 | public class CoapCodeException extends CoapException { 25 | 26 | private final Code code; 27 | 28 | public CoapCodeException(Code code) { 29 | super(code.toString().substring(1).replace("_", " ")); 30 | this.code = code; 31 | } 32 | 33 | public CoapCodeException(Code code, Throwable throwable) { 34 | super(code.toString().substring(1).replace("_", " "), throwable); 35 | this.code = code; 36 | } 37 | 38 | public CoapCodeException(Code code, String message) { 39 | super(message); 40 | this.code = code; 41 | } 42 | 43 | /** 44 | * @return the code 45 | */ 46 | public Code getCode() { 47 | return code; 48 | } 49 | 50 | public CoapResponse.Builder toResponse() { 51 | return coapResponse(code).payload(getMessage()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.exception; 18 | 19 | 20 | public class CoapException extends Exception { 21 | 22 | public static CoapException wrap(Exception ex) { 23 | if (ex.getCause() instanceof CoapException) { 24 | return (CoapException) ex.getCause(); 25 | } else { 26 | return new CoapException(ex.getCause()); 27 | } 28 | } 29 | 30 | public CoapException(Throwable cause) { 31 | super(cause); 32 | } 33 | 34 | public CoapException(String message) { 35 | super(message); 36 | } 37 | 38 | public CoapException(String message, Throwable cause) { 39 | super(message, cause); 40 | } 41 | 42 | public CoapException(String format, Object... args) { 43 | super(String.format(format, args)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapMessageFormatException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.exception; 17 | 18 | 19 | public class CoapMessageFormatException extends CoapException { 20 | 21 | public CoapMessageFormatException(String message) { 22 | super(message); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapRequestEntityIncomplete.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.exception; 17 | 18 | import com.mbed.coap.packet.Code; 19 | 20 | public class CoapRequestEntityIncomplete extends CoapCodeException { 21 | 22 | public CoapRequestEntityIncomplete() { 23 | super(Code.C408_REQUEST_ENTITY_INCOMPLETE); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapRequestEntityTooLarge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.exception; 18 | 19 | import com.mbed.coap.packet.BlockOption; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.Code; 22 | 23 | public class CoapRequestEntityTooLarge extends CoapCodeException { 24 | 25 | private final int maxSize; 26 | private final BlockOption blockOptionHint; 27 | 28 | public CoapRequestEntityTooLarge(int maxSize, String message) { 29 | super(Code.C413_REQUEST_ENTITY_TOO_LARGE, message); 30 | this.maxSize = maxSize; 31 | this.blockOptionHint = null; 32 | } 33 | 34 | public CoapRequestEntityTooLarge(BlockOption blockOptionHint, String message) { 35 | super(Code.C413_REQUEST_ENTITY_TOO_LARGE, message); 36 | this.maxSize = 0; 37 | this.blockOptionHint = blockOptionHint; 38 | } 39 | 40 | @Override 41 | public CoapResponse.Builder toResponse() { 42 | return super.toResponse() 43 | .options(o -> { 44 | if (maxSize > 0) { 45 | o.size1(maxSize); 46 | } 47 | if (blockOptionHint != null) { 48 | o.block1Req(blockOptionHint); 49 | } 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/CoapTimeoutException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.exception; 18 | 19 | public class CoapTimeoutException extends CoapException { 20 | 21 | public CoapTimeoutException() { 22 | super("Timeout"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/exception/TooManyRequestsForEndpointException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.exception; 17 | 18 | public class TooManyRequestsForEndpointException extends CoapException { 19 | 20 | public TooManyRequestsForEndpointException(String message) { 21 | super(message); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/packet/BlockSize.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.packet; 17 | 18 | 19 | public enum BlockSize { 20 | 21 | S_16(4, false), S_32(5, false), S_64(6, false), S_128(7, false), S_256(8, false), S_512(9, false), S_1024(10, false), S_1024_BERT(10, true); 22 | byte szx; 23 | boolean bert; 24 | 25 | BlockSize(int szx, boolean bert) { 26 | this.szx = (byte) (szx - 4); 27 | this.bert = bert; 28 | } 29 | 30 | public int getSize() { 31 | return 1 << (szx + 4); 32 | } 33 | 34 | public int numberOfBlocksPerMessage(int totalSize) { 35 | return bert ? totalSize / getSize() : 1; 36 | } 37 | 38 | 39 | public static BlockSize fromRawSzx(byte rawSzx) { 40 | return values()[rawSzx]; 41 | } 42 | 43 | public byte toRawSzx() { 44 | if (bert) { 45 | return 7; 46 | } else { 47 | return szx; 48 | } 49 | } 50 | 51 | public boolean isBert() { 52 | return bert; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/packet/EofInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import java.io.EOFException; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | 23 | /** 24 | * InputStream decorator that throws EOFException if data in not available. 25 | */ 26 | class EofInputStream extends InputStream { 27 | private final InputStream inputStream; 28 | 29 | private EofInputStream(InputStream inputStream) { 30 | this.inputStream = inputStream; 31 | } 32 | 33 | @Override 34 | public int read(byte[] b, int off, int len) throws IOException { 35 | int ret = inputStream.read(b, off, len); 36 | if (ret == -1) { 37 | throw new EOFException(); 38 | } 39 | return ret; 40 | } 41 | 42 | @Override 43 | public int read() throws IOException { 44 | int val = inputStream.read(); 45 | if (val < 0) { 46 | throw new EOFException(); 47 | } 48 | return val; 49 | } 50 | 51 | @Override 52 | public int available() throws IOException { 53 | return inputStream.available(); 54 | } 55 | 56 | static EofInputStream wrap(InputStream inputStream) { 57 | if (inputStream instanceof EofInputStream) { 58 | return (EofInputStream) inputStream; 59 | } else { 60 | return new EofInputStream(inputStream); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/packet/MessageType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.packet; 17 | 18 | import com.mbed.coap.exception.CoapException; 19 | 20 | 21 | public enum MessageType { 22 | 23 | Confirmable, NonConfirmable, Acknowledgement, Reset; 24 | 25 | public static MessageType valueOf(int transactionMessage) throws CoapException { 26 | switch (transactionMessage) { 27 | case 0: 28 | return Confirmable; 29 | case 1: 30 | return NonConfirmable; 31 | case 2: 32 | return Acknowledgement; 33 | case 3: 34 | return Reset; 35 | default: 36 | throw new CoapException("Wrong transaction message code"); 37 | } 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return super.toString().substring(0, 3).toUpperCase(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/packet/Method.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import com.mbed.coap.exception.CoapException; 20 | 21 | 22 | public enum Method { 23 | 24 | GET, POST, PUT, DELETE, FETCH, PATCH, iPATCH; 25 | 26 | public static Method valueOf(int methodCode) throws CoapException { 27 | switch (methodCode) { 28 | case 1: 29 | return GET; 30 | case 2: 31 | return POST; 32 | case 3: 33 | return PUT; 34 | case 4: 35 | return DELETE; 36 | case 5: 37 | return FETCH; 38 | case 6: 39 | return PATCH; 40 | case 7: 41 | return iPATCH; 42 | default: 43 | throw new CoapException("Wrong method code"); 44 | } 45 | } 46 | 47 | public int getCode() { 48 | return this.ordinal() + 1; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/packet/PacketUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | 22 | /** 23 | * Minor CoapPacket binary read/write utility methods with specific optional checks. 24 | */ 25 | class PacketUtils { 26 | 27 | static int read16(InputStream is) throws IOException { 28 | int ret = is.read() << 8; 29 | ret |= is.read(); 30 | return ret; 31 | } 32 | 33 | static int read8(InputStream is) throws IOException { 34 | return is.read(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/CoapRequestId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server; 18 | 19 | import java.net.InetSocketAddress; 20 | import java.util.Objects; 21 | 22 | public class CoapRequestId { 23 | 24 | private final int mid; 25 | private final InetSocketAddress sourceAddress; 26 | private final transient long createdTimestampMillis; 27 | 28 | public CoapRequestId(int mid, InetSocketAddress sourceAddress) { 29 | this.mid = mid; 30 | this.sourceAddress = sourceAddress; 31 | this.createdTimestampMillis = System.currentTimeMillis(); 32 | } 33 | 34 | public long getCreatedTimestampMillis() { 35 | return createdTimestampMillis; 36 | } 37 | 38 | public int getMid() { 39 | return mid; 40 | } 41 | 42 | public InetSocketAddress getSourceAddress() { 43 | return sourceAddress; 44 | } 45 | 46 | @Override 47 | public boolean equals(Object obj) { 48 | if (this == obj) { 49 | return true; 50 | } 51 | if (obj == null || getClass() != obj.getClass()) { 52 | return false; 53 | } 54 | 55 | CoapRequestId objRequestId = (CoapRequestId) obj; 56 | 57 | if (mid != objRequestId.mid) { 58 | return false; 59 | } 60 | return Objects.equals(sourceAddress, objRequestId.sourceAddress); 61 | } 62 | 63 | @Override 64 | public int hashCode() { 65 | int result = mid; 66 | result = 31 * result + (sourceAddress != null ? sourceAddress.hashCode() : 0); 67 | return result; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/CoapServerGroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2024 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server; 17 | 18 | import static com.mbed.coap.utils.Validations.require; 19 | import static java.util.stream.Collectors.toList; 20 | import com.mbed.coap.transport.CoapTransport; 21 | import java.io.IOException; 22 | import java.util.List; 23 | 24 | public class CoapServerGroup { 25 | private final List servers; 26 | 27 | CoapServerGroup(List servers) { 28 | require(!servers.isEmpty(), "At least one server required"); 29 | this.servers = servers; 30 | } 31 | 32 | public CoapServerGroup start() throws IOException { 33 | for (CoapServer server : servers) { 34 | server.start(); 35 | } 36 | return this; 37 | } 38 | 39 | public void stop() { 40 | for (CoapServer server : servers) { 41 | server.stop(); 42 | } 43 | } 44 | 45 | public boolean isRunning() { 46 | return servers.stream().allMatch(CoapServer::isRunning); 47 | } 48 | 49 | public List getLocalPorts() { 50 | return servers.stream().map(server -> server.getLocalSocketAddress().getPort()).collect(toList()); 51 | } 52 | 53 | public List getTransports() { 54 | return servers.stream().map(CoapServer::getTransport).collect(toList()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/CriticalOptionVerifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server; 18 | 19 | import static com.mbed.coap.packet.CoapResponse.coapResponse; 20 | import com.mbed.coap.packet.CoapRequest; 21 | import com.mbed.coap.packet.CoapResponse; 22 | import com.mbed.coap.packet.Code; 23 | import com.mbed.coap.utils.Filter; 24 | import com.mbed.coap.utils.Service; 25 | import java.util.concurrent.CompletableFuture; 26 | 27 | class CriticalOptionVerifier implements Filter.SimpleFilter { 28 | 29 | @Override 30 | public CompletableFuture apply(CoapRequest request, Service service) { 31 | if (request.options().containsUnrecognisedCriticalOption()) { 32 | return coapResponse(Code.C402_BAD_OPTION).toFuture(); 33 | } 34 | return service.apply(request); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/DuplicatedCoapMessageCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server; 17 | 18 | import com.mbed.coap.packet.CoapPacket; 19 | 20 | public interface DuplicatedCoapMessageCallback { 21 | DuplicatedCoapMessageCallback NULL = request -> { 22 | //ignore 23 | }; 24 | 25 | void duplicated(CoapPacket request); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/NotificationValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server; 18 | 19 | import com.mbed.coap.packet.SeparateResponse; 20 | import com.mbed.coap.utils.Filter; 21 | import com.mbed.coap.utils.Service; 22 | import java.util.concurrent.CompletableFuture; 23 | 24 | class NotificationValidator implements Filter.SimpleFilter { 25 | 26 | @Override 27 | public CompletableFuture apply(SeparateResponse obs, Service service) { 28 | if (obs.options().getObserve() == null) { 29 | throw new IllegalArgumentException("Notification packet should have observation header set"); 30 | } 31 | if (obs.getToken().isEmpty()) { 32 | throw new IllegalArgumentException("Notification packet should have non-empty token"); 33 | } 34 | return service.apply(obs); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/PutOnlyMap.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server; 17 | 18 | public interface PutOnlyMap { 19 | V putIfAbsent(K key, V value); 20 | 21 | void put(K key, V value); 22 | 23 | void stop(); 24 | } 25 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/RescueFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server; 17 | 18 | import com.mbed.coap.exception.CoapCodeException; 19 | import com.mbed.coap.packet.CoapRequest; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.Code; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.concurrent.CompletableFuture; 25 | import java.util.concurrent.CompletionException; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | 29 | class RescueFilter implements Filter.SimpleFilter { 30 | private static final Logger LOGGER = LoggerFactory.getLogger(RescueFilter.class); 31 | 32 | @Override 33 | public CompletableFuture apply(CoapRequest request, Service service) { 34 | try { 35 | return service.apply(request).exceptionally(this::rescue); 36 | } catch (Exception ex) { 37 | return CompletableFuture.completedFuture(rescue(ex)); 38 | } 39 | } 40 | 41 | private CoapResponse rescue(Throwable ex) { 42 | if (ex instanceof CompletionException) { 43 | return rescue(ex.getCause()); 44 | } 45 | if (ex instanceof CoapCodeException) { 46 | return ((CoapCodeException) ex).toResponse().build(); 47 | } 48 | 49 | LOGGER.error("Unexpected exception: {}", ex.getMessage(), ex); 50 | return CoapResponse.of(Code.C500_INTERNAL_SERVER_ERROR); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/block/BlockRequestId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.block; 18 | 19 | import com.mbed.coap.packet.CoapRequest; 20 | import java.net.InetSocketAddress; 21 | import java.util.Objects; 22 | 23 | class BlockRequestId { 24 | 25 | private final String uriPath; 26 | private final InetSocketAddress sourceAddress; 27 | 28 | static BlockRequestId from(CoapRequest request) { 29 | return new BlockRequestId(request.options().getUriPath(), request.getPeerAddress()); 30 | } 31 | 32 | private BlockRequestId(String uriPath, InetSocketAddress sourceAddress) { 33 | this.uriPath = uriPath; 34 | this.sourceAddress = sourceAddress; 35 | } 36 | 37 | @Override 38 | public int hashCode() { 39 | int hash = 3; 40 | hash = 73 * hash + (this.uriPath != null ? this.uriPath.hashCode() : 0); 41 | hash = 73 * hash + (this.sourceAddress != null ? this.sourceAddress.hashCode() : 0); 42 | return hash; 43 | } 44 | 45 | @Override 46 | public boolean equals(Object obj) { 47 | if (obj == null) { 48 | return false; 49 | } 50 | if (getClass() != obj.getClass()) { 51 | return false; 52 | } 53 | final BlockRequestId other = (BlockRequestId) obj; 54 | if (!Objects.equals(this.uriPath, other.uriPath)) { 55 | return false; 56 | } 57 | return Objects.equals(this.sourceAddress, other.sourceAddress); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/block/BlockWiseNotificationFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.block; 18 | 19 | import com.mbed.coap.packet.Opaque; 20 | import com.mbed.coap.packet.SeparateResponse; 21 | import com.mbed.coap.server.messaging.Capabilities; 22 | import com.mbed.coap.server.messaging.CapabilitiesResolver; 23 | import com.mbed.coap.utils.Filter; 24 | import com.mbed.coap.utils.Service; 25 | import java.util.concurrent.CompletableFuture; 26 | 27 | public class BlockWiseNotificationFilter implements Filter.SimpleFilter { 28 | private final CapabilitiesResolver capabilities; 29 | 30 | public BlockWiseNotificationFilter(CapabilitiesResolver capabilities) { 31 | this.capabilities = capabilities; 32 | } 33 | 34 | @Override 35 | public CompletableFuture apply(SeparateResponse blockObs, Service service) { 36 | SeparateResponse obs = blockObs; 37 | Capabilities csm = capabilities.getOrDefault(obs.getPeerAddress()); 38 | if (csm.useBlockTransfer(obs.getPayload())) { 39 | //request that needs to use blocks 40 | obs = obs.duplicate(); 41 | Opaque newPayload = BlockWiseTransfer.updateWithFirstBlock(obs, csm); 42 | obs = obs.withPayload(newPayload); 43 | } 44 | return service.apply(obs); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/block/BlockWiseOutgoingFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.block; 18 | 19 | import static com.mbed.coap.utils.FutureHelpers.*; 20 | import com.mbed.coap.exception.CoapException; 21 | import com.mbed.coap.packet.CoapRequest; 22 | import com.mbed.coap.packet.CoapResponse; 23 | import com.mbed.coap.server.messaging.CapabilitiesResolver; 24 | import com.mbed.coap.utils.Filter; 25 | import com.mbed.coap.utils.Service; 26 | import java.util.concurrent.CompletableFuture; 27 | 28 | public class BlockWiseOutgoingFilter implements Filter.SimpleFilter { 29 | private final CapabilitiesResolver capabilities; 30 | private final int maxIncomingBlockTransferSize; 31 | 32 | public BlockWiseOutgoingFilter(CapabilitiesResolver capabilities, int maxIncomingBlockTransferSize) { 33 | this.capabilities = capabilities; 34 | this.maxIncomingBlockTransferSize = maxIncomingBlockTransferSize; 35 | } 36 | 37 | 38 | @Override 39 | public CompletableFuture apply(CoapRequest request, Service service) { 40 | 41 | try { 42 | BlockWiseCallback blockCallback = new BlockWiseCallback( 43 | service, 44 | capabilities.getOrDefault(request.getPeerAddress()), 45 | request, 46 | maxIncomingBlockTransferSize 47 | ); 48 | 49 | return service.apply(blockCallback.request) 50 | .thenCompose(blockCallback::receive); 51 | 52 | } catch (CoapException e) { 53 | return failedFuture(e); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/EchoFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import static java.util.concurrent.CompletableFuture.completedFuture; 19 | import com.mbed.coap.packet.CoapRequest; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.Code; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.concurrent.CompletableFuture; 25 | 26 | public class EchoFilter implements Filter.SimpleFilter { 27 | 28 | @Override 29 | public CompletableFuture apply(CoapRequest request, Service service) { 30 | return service 31 | .apply(request) 32 | .thenCompose(resp -> { 33 | if (resp.getCode() == Code.C401_UNAUTHORIZED && resp.options().getEcho() != null) { 34 | // server required freshness verification, retry with echo 35 | 36 | CoapRequest requestWithEcho = request.modify().options(it -> it.echo(resp.options().getEcho())).build(); 37 | return service.apply(requestWithEcho); 38 | } else { 39 | return completedFuture(resp); 40 | } 41 | }); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/EtagGeneratorFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import com.mbed.coap.packet.CoapRequest; 19 | import com.mbed.coap.packet.CoapResponse; 20 | import com.mbed.coap.packet.HeaderOptions; 21 | import com.mbed.coap.packet.Opaque; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.Arrays; 25 | import java.util.Objects; 26 | import java.util.concurrent.CompletableFuture; 27 | import java.util.function.Function; 28 | 29 | public class EtagGeneratorFilter implements Filter.SimpleFilter { 30 | 31 | private final Function etagGenerator; 32 | 33 | public final static EtagGeneratorFilter PAYLOAD_HASHING = new EtagGeneratorFilter(payload -> Opaque.variableUInt(Arrays.hashCode(payload.getBytes()))); 34 | 35 | public EtagGeneratorFilter(Function etagGenerator) { 36 | this.etagGenerator = Objects.requireNonNull(etagGenerator); 37 | } 38 | 39 | @Override 40 | public CompletableFuture apply(CoapRequest request, Service service) { 41 | return service 42 | .apply(request) 43 | .thenApply(this::updateEtag); 44 | } 45 | 46 | private CoapResponse updateEtag(CoapResponse resp) { 47 | return resp.withOptions(o -> 48 | o.ifNull(HeaderOptions::getEtagArray, __ -> 49 | o.etag(etagGenerator.apply(resp.getPayload())) 50 | ) 51 | ); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/EtagValidatorFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import com.mbed.coap.packet.CoapRequest; 19 | import com.mbed.coap.packet.CoapResponse; 20 | import com.mbed.coap.packet.Code; 21 | import com.mbed.coap.packet.Method; 22 | import com.mbed.coap.packet.Opaque; 23 | import com.mbed.coap.utils.Filter; 24 | import com.mbed.coap.utils.Service; 25 | import java.util.concurrent.CompletableFuture; 26 | 27 | public class EtagValidatorFilter implements Filter.SimpleFilter { 28 | 29 | @Override 30 | public CompletableFuture apply(CoapRequest request, Service service) { 31 | return service 32 | .apply(request) 33 | .thenApply(resp -> { 34 | if (request.getMethod() == Method.GET) { 35 | return validateEtag(request, resp); 36 | } else { 37 | return resp; 38 | } 39 | }); 40 | } 41 | 42 | private CoapResponse validateEtag(CoapRequest request, CoapResponse resp) { 43 | if (request.options().getEtagArray() != null && resp.options().getEtag() != null) { 44 | for (Opaque etag : request.options().getEtagArray()) { 45 | if (etag.equals(resp.options().getEtag())) { 46 | return CoapResponse.of(Code.C203_VALID, Opaque.EMPTY, resp.options()); 47 | } 48 | } 49 | } 50 | return resp; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/MaxAllowedPayloadFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import static com.mbed.coap.packet.CoapResponse.coapResponse; 19 | import com.mbed.coap.packet.CoapRequest; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.Code; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.concurrent.CompletableFuture; 25 | 26 | public class MaxAllowedPayloadFilter implements Filter.SimpleFilter { 27 | private final int max; 28 | private final String msg; 29 | 30 | public MaxAllowedPayloadFilter(int max, String msg) { 31 | this.max = max; 32 | this.msg = msg; 33 | } 34 | 35 | @Override 36 | public CompletableFuture apply(CoapRequest request, Service service) { 37 | 38 | if (request.getPayload().size() > max) { 39 | return coapResponse(Code.C413_REQUEST_ENTITY_TOO_LARGE) 40 | .options(o -> o.size1(max)) 41 | .payload(msg) 42 | .toFuture(); 43 | } else { 44 | return service.apply(request); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/ResponseTimeoutFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import com.mbed.coap.exception.CoapTimeoutException; 19 | import com.mbed.coap.utils.Filter.SimpleFilter; 20 | import com.mbed.coap.utils.Service; 21 | import com.mbed.coap.utils.Timer; 22 | import java.time.Duration; 23 | import java.util.concurrent.CompletableFuture; 24 | import java.util.function.Function; 25 | 26 | public class ResponseTimeoutFilter implements SimpleFilter { 27 | 28 | private final Timer timer; 29 | private final Function timeoutResolver; 30 | 31 | public ResponseTimeoutFilter(Timer timer, Function timeoutResolver) { 32 | this.timer = timer; 33 | this.timeoutResolver = timeoutResolver; 34 | } 35 | 36 | @Override 37 | public CompletableFuture apply(REQ request, Service service) { 38 | CompletableFuture promise = service.apply(request); 39 | 40 | Runnable cancel = timer.schedule(timeoutResolver.apply(request), () -> 41 | promise.completeExceptionally(new CoapTimeoutException()) 42 | ); 43 | 44 | promise.whenComplete((__, err) -> cancel.run()); 45 | return promise; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/SequentialTaskRunner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import static com.mbed.coap.utils.FutureHelpers.*; 19 | import com.mbed.coap.exception.TooManyRequestsForEndpointException; 20 | import java.util.concurrent.CompletableFuture; 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | import java.util.concurrent.atomic.AtomicReference; 23 | import java.util.function.Supplier; 24 | 25 | class SequentialTaskRunner { 26 | private final int max; 27 | private final AtomicReference> last = new AtomicReference<>(); 28 | private final AtomicInteger counter = new AtomicInteger(0); 29 | 30 | public SequentialTaskRunner(int max) { 31 | this.max = max; 32 | } 33 | 34 | public CompletableFuture add(Supplier> task) { 35 | if (counter.incrementAndGet() > max) { 36 | counter.decrementAndGet(); 37 | return failedFuture(new TooManyRequestsForEndpointException("")); 38 | } 39 | CompletableFuture promise = new CompletableFuture<>(); 40 | 41 | CompletableFuture prev = last.getAndSet(promise); 42 | if (prev == null) { 43 | become(promise, task.get()); 44 | } else { 45 | prev.whenComplete((__, err) -> 46 | become(promise, task.get()) 47 | ); 48 | } 49 | 50 | promise.thenRun(counter::decrementAndGet) 51 | .thenRun(() -> last.compareAndSet(promise, null)); 52 | 53 | return promise; 54 | } 55 | 56 | boolean isEmpty() { 57 | return last.get() == null; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/filter/TokenGeneratorFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import static java.util.Objects.requireNonNull; 19 | import com.mbed.coap.packet.CoapRequest; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.Opaque; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.Random; 25 | import java.util.concurrent.CompletableFuture; 26 | import java.util.concurrent.atomic.AtomicLong; 27 | import java.util.function.Supplier; 28 | 29 | public class TokenGeneratorFilter implements Filter.SimpleFilter { 30 | 31 | final Supplier tokenGenerator; 32 | 33 | private static final Random random = new Random(); 34 | public static final TokenGeneratorFilter RANDOM = new TokenGeneratorFilter(() -> 35 | Opaque.variableUInt(random.nextLong()) 36 | ); 37 | 38 | public static TokenGeneratorFilter sequential(long startToken) { 39 | final AtomicLong current = new AtomicLong(startToken); 40 | 41 | return new TokenGeneratorFilter(() -> Opaque.variableUInt(current.incrementAndGet())); 42 | } 43 | 44 | public TokenGeneratorFilter(Supplier tokenGenerator) { 45 | this.tokenGenerator = requireNonNull(tokenGenerator); 46 | } 47 | 48 | @Override 49 | public CompletableFuture apply(CoapRequest request, Service service) { 50 | if (!request.isPing() && request.getToken().isEmpty()) { 51 | return service.apply(request.modify().token(tokenGenerator.get()).build()); 52 | } 53 | 54 | return service.apply(request); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/CapabilitiesResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | @FunctionalInterface 21 | public interface CapabilitiesResolver { 22 | Capabilities getOrDefault(InetSocketAddress address); 23 | } 24 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/CoapRequestConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import com.mbed.coap.packet.CoapPacket; 19 | import com.mbed.coap.packet.CoapRequest; 20 | import com.mbed.coap.packet.CoapResponse; 21 | import com.mbed.coap.packet.MessageType; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.concurrent.CompletableFuture; 25 | 26 | public class CoapRequestConverter implements Filter { 27 | 28 | private final MessageIdSupplier midSupplier; 29 | 30 | public CoapRequestConverter(MessageIdSupplier midSupplier) { 31 | this.midSupplier = midSupplier; 32 | } 33 | 34 | @Override 35 | public CompletableFuture apply(CoapPacket packet, Service service) { 36 | return service 37 | .apply(packet.toCoapRequest()) 38 | .thenApply(coapResponse -> { 39 | CoapPacket responsePacket = packet.createResponseFrom(coapResponse); 40 | 41 | if (responsePacket.getMessageType() == MessageType.NonConfirmable) { 42 | //Non-confirmable messages must also use mid for deduplication purpose 43 | midSupplier.update(responsePacket); 44 | } 45 | return responsePacket; 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/MessageIdSupplier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import com.mbed.coap.packet.CoapPacket; 20 | 21 | /** 22 | * Interface for generating CoAP message ID. 23 | */ 24 | @FunctionalInterface 25 | public interface MessageIdSupplier { 26 | 27 | /** 28 | * Gets next unique coap message identifier, limited to values from 0 to 29 | * 65535 (0xFFFF) 30 | * 31 | * @return next unique message id 32 | */ 33 | int getNextMID(); 34 | 35 | default CoapPacket update(CoapPacket packet) { 36 | packet.setMessageId(getNextMID()); 37 | return packet; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/MessageIdSupplierImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import java.util.Random; 20 | import java.util.concurrent.atomic.AtomicInteger; 21 | 22 | public final class MessageIdSupplierImpl implements MessageIdSupplier { 23 | 24 | private final AtomicInteger globalMid; 25 | 26 | public MessageIdSupplierImpl() { 27 | this(new Random().nextInt(0xFFFF)); 28 | } 29 | 30 | public MessageIdSupplierImpl(int initMid) { 31 | this.globalMid = new AtomicInteger(initMid); 32 | } 33 | 34 | @Override 35 | public int getNextMID() { 36 | return 0xFFFF & (globalMid.incrementAndGet()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/ObservationMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import static com.mbed.coap.packet.MessageType.Acknowledgement; 19 | import static com.mbed.coap.packet.MessageType.Reset; 20 | import com.mbed.coap.packet.CoapPacket; 21 | import com.mbed.coap.packet.SeparateResponse; 22 | import com.mbed.coap.utils.Filter; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.concurrent.CompletableFuture; 25 | 26 | public class ObservationMapper implements Filter { 27 | 28 | @Override 29 | public CompletableFuture apply(CoapPacket obsPacket, Service service) { 30 | SeparateResponse obs = obsPacket.toSeparateResponse(); 31 | 32 | return service.apply(obs).thenApply(ack -> { 33 | if (obsPacket.isConfirmable()) { 34 | CoapPacket coapAck = new CoapPacket(obsPacket.getRemoteAddress()); 35 | coapAck.setMessageType(ack ? Acknowledgement : Reset); 36 | coapAck.setMessageId(obsPacket.getMessageId()); 37 | return coapAck; 38 | } else { 39 | return null; 40 | } 41 | }); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/PiggybackedCorrelation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import com.mbed.coap.packet.CoapPacket; 20 | import java.net.InetSocketAddress; 21 | import java.util.Objects; 22 | 23 | class PiggybackedCorrelation { 24 | 25 | private final int messageId; 26 | protected InetSocketAddress address; 27 | 28 | public PiggybackedCorrelation(CoapPacket packet) { 29 | messageId = packet.getMessageId(); 30 | address = packet.getRemoteAddress(); 31 | } 32 | 33 | @Override 34 | public int hashCode() { 35 | int hash = 7; 36 | hash = 67 * hash + this.messageId; 37 | hash = 67 * hash + (this.address != null ? this.address.hashCode() : 0); 38 | return hash; 39 | } 40 | 41 | @Override 42 | public boolean equals(Object obj) { 43 | if (obj == null) { 44 | return false; 45 | } 46 | if (getClass() != obj.getClass()) { 47 | return false; 48 | } 49 | final PiggybackedCorrelation other = (PiggybackedCorrelation) obj; 50 | if (this.messageId != other.messageId) { 51 | return false; 52 | } 53 | return Objects.equals(this.address, other.address); 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return messageId + "#" + address.toString(); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/RequestTagSupplier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import com.mbed.coap.packet.Opaque; 19 | import java.util.Random; 20 | import java.util.concurrent.atomic.AtomicInteger; 21 | 22 | @FunctionalInterface 23 | public interface RequestTagSupplier { 24 | RequestTagSupplier NULL = () -> null; 25 | 26 | Opaque next(); 27 | 28 | static RequestTagSupplier createSequential() { 29 | return createSequential(new Random().nextInt(0xFFFF)); 30 | } 31 | 32 | static RequestTagSupplier createSequential(int init) { 33 | final AtomicInteger current = new AtomicInteger(init); 34 | 35 | return () -> Opaque.variableUInt(current.incrementAndGet()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/messaging/TransactionId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import com.mbed.coap.packet.Opaque; 20 | import java.net.InetSocketAddress; 21 | import java.util.Objects; 22 | 23 | 24 | public class TransactionId { 25 | private final Opaque token; 26 | private final InetSocketAddress source; 27 | 28 | public TransactionId(Opaque token, InetSocketAddress source) { 29 | this.token = token; 30 | this.source = source; 31 | } 32 | 33 | public boolean hasRemoteAddress(InetSocketAddress adr) { 34 | return source.equals(adr); 35 | } 36 | 37 | @Override 38 | public boolean equals(Object obj) { 39 | if (obj == null) { 40 | return false; 41 | } 42 | if (getClass() != obj.getClass()) { 43 | return false; 44 | } 45 | final TransactionId other = (TransactionId) obj; 46 | if (!Objects.equals(this.token, other.token)) { 47 | return false; 48 | } 49 | return Objects.equals(this.source, other.source); 50 | } 51 | 52 | @Override 53 | public int hashCode() { 54 | int hash = 7; 55 | hash = 41 * hash + Objects.hashCode(this.token); 56 | hash = 41 * hash + (this.source != null ? this.source.hashCode() : 0); 57 | return hash; 58 | } 59 | 60 | @Override 61 | public String toString() { 62 | return token + "#" + source.toString(); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/observe/HashMapObservationsStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.observe; 17 | 18 | import com.mbed.coap.packet.CoapRequest; 19 | import com.mbed.coap.packet.Opaque; 20 | import com.mbed.coap.packet.SeparateResponse; 21 | import java.util.Map; 22 | import java.util.Optional; 23 | import java.util.concurrent.ConcurrentHashMap; 24 | 25 | public final class HashMapObservationsStore implements ObservationsStore { 26 | private final Map obsMap = new ConcurrentHashMap<>(); 27 | 28 | @Override 29 | public void add(CoapRequest obsReq) { 30 | obsMap.put(obsReq.getToken(), obsReq.options().getUriPath()); 31 | } 32 | 33 | @Override 34 | public Optional resolveUriPath(SeparateResponse obs) { 35 | return Optional.ofNullable(obsMap.get(obs.getToken())); 36 | } 37 | 38 | @Override 39 | public void remove(SeparateResponse obs) { 40 | obsMap.remove(obs.getToken()); 41 | } 42 | 43 | public boolean contains(Opaque token) { 44 | return obsMap.containsKey(token); 45 | } 46 | 47 | public boolean isEmpty() { 48 | return obsMap.isEmpty(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/server/observe/ObservationsStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.observe; 17 | 18 | import com.mbed.coap.packet.CoapRequest; 19 | import com.mbed.coap.packet.SeparateResponse; 20 | import java.util.Optional; 21 | 22 | public interface ObservationsStore { 23 | 24 | void add(CoapRequest obsReq); 25 | 26 | Optional resolveUriPath(SeparateResponse obs); 27 | 28 | void remove(SeparateResponse obs); 29 | 30 | static ObservationsStore inMemory() { 31 | return new HashMapObservationsStore(); 32 | } 33 | 34 | ObservationsStore ALWAYS_EMPTY = new ObservationsStore() { 35 | @Override 36 | public void add(CoapRequest obsReq) { 37 | } 38 | 39 | @Override 40 | public Optional resolveUriPath(SeparateResponse obs) { 41 | return Optional.empty(); 42 | } 43 | 44 | @Override 45 | public void remove(SeparateResponse obs) { 46 | } 47 | }; 48 | } 49 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/transport/BlockingCoapTransport.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.transport; 17 | 18 | import com.mbed.coap.exception.CoapException; 19 | import com.mbed.coap.packet.CoapPacket; 20 | import java.io.IOException; 21 | import java.util.concurrent.CompletableFuture; 22 | 23 | public abstract class BlockingCoapTransport implements CoapTransport { 24 | 25 | @Override 26 | public final CompletableFuture sendPacket(CoapPacket coapPacket) { 27 | CompletableFuture objectCompletableFuture = new CompletableFuture<>(); 28 | 29 | try { 30 | sendPacket0(coapPacket); 31 | objectCompletableFuture.complete(true); 32 | } catch (Exception ex) { 33 | objectCompletableFuture.completeExceptionally(ex); 34 | } 35 | 36 | return objectCompletableFuture; 37 | } 38 | 39 | public abstract void sendPacket0(CoapPacket coapPacket) throws CoapException, IOException; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/transport/CoapTransport.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.transport; 17 | 18 | import com.mbed.coap.packet.CoapPacket; 19 | import java.io.IOException; 20 | import java.net.InetSocketAddress; 21 | import java.util.concurrent.CompletableFuture; 22 | 23 | public interface CoapTransport { 24 | void start() throws IOException; 25 | 26 | void stop(); 27 | 28 | CompletableFuture sendPacket(CoapPacket coapPacket); 29 | 30 | CompletableFuture receive(); 31 | 32 | InetSocketAddress getLocalSocketAddress(); 33 | } 34 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/utils/ExecutorHelpers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.utils; 18 | 19 | import java.util.concurrent.ExecutorService; 20 | import java.util.concurrent.Executors; 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | 23 | /* 24 | Helper class for running blocking operation for transport reading. 25 | */ 26 | public class ExecutorHelpers { 27 | private static final AtomicInteger POOL_NUMBER = new AtomicInteger(0); 28 | 29 | public static ExecutorService newSingleThreadExecutor(String namePrefix) { 30 | return Executors.newSingleThreadExecutor(r -> new Thread(r, namePrefix + "-" + POOL_NUMBER.incrementAndGet())); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/utils/Service.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import java.util.concurrent.CompletableFuture; 19 | import java.util.function.Function; 20 | 21 | @FunctionalInterface 22 | public interface Service extends Function> { 23 | 24 | } 25 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/utils/Timer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import java.time.Duration; 19 | import java.util.concurrent.ScheduledExecutorService; 20 | import java.util.concurrent.ScheduledFuture; 21 | import java.util.concurrent.TimeUnit; 22 | 23 | /* 24 | Simple timer interface, helps with testing 25 | */ 26 | @FunctionalInterface 27 | public interface Timer { 28 | Runnable schedule(Duration delay, Runnable task); 29 | 30 | static Timer toTimer(ScheduledExecutorService executorService) { 31 | return (delay, task) -> { 32 | ScheduledFuture scheduled = executorService.schedule(task, delay.toMillis(), TimeUnit.MILLISECONDS); 33 | return () -> scheduled.cancel(true); 34 | }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /coap-core/src/main/java/com/mbed/coap/utils/Validations.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.utils; 18 | 19 | /** 20 | * Minor utilities for Protocol CoAP servers 21 | */ 22 | public class Validations { 23 | public static void assume(boolean assumeCondition, String errorMessage) { 24 | if (!assumeCondition) { 25 | throw new IllegalStateException(errorMessage); 26 | } 27 | } 28 | 29 | public static void assume(boolean assumeCondition) { 30 | if (!assumeCondition) { 31 | throw new IllegalStateException(); 32 | } 33 | } 34 | 35 | public static void require(boolean requireCondition, String errorMessage) { 36 | if (!requireCondition) { 37 | throw new IllegalArgumentException(errorMessage); 38 | } 39 | } 40 | 41 | public static void require(boolean requireCondition) { 42 | require(requireCondition, null); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/packet/BlockOptionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import org.junit.jupiter.api.Test; 21 | 22 | public class BlockOptionTest { 23 | 24 | @Test 25 | public void testBlock() { 26 | BlockOption bo = new BlockOption(16, BlockSize.S_16, false); 27 | BlockOption bo2 = new BlockOption(bo.toBytes()); 28 | assertEquals(bo, bo2); 29 | 30 | bo = new BlockOption(16, BlockSize.S_16, true); 31 | bo2 = new BlockOption(bo.toBytes()); 32 | assertEquals(bo, bo2); 33 | 34 | bo = new BlockOption(15, BlockSize.S_16, false); 35 | bo2 = new BlockOption(bo.toBytes()); 36 | assertEquals(bo, bo2); 37 | } 38 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/packet/BlockSizeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import org.junit.jupiter.api.Test; 21 | 22 | public class BlockSizeTest { 23 | 24 | @Test 25 | public void number_of_blocks_per_message() { 26 | assertEquals(1, BlockSize.S_16.numberOfBlocksPerMessage(102)); 27 | assertEquals(1, BlockSize.S_1024.numberOfBlocksPerMessage(10_000)); 28 | 29 | assertEquals(1, BlockSize.S_1024_BERT.numberOfBlocksPerMessage(1024)); 30 | assertEquals(1, BlockSize.S_1024_BERT.numberOfBlocksPerMessage(2000)); 31 | assertEquals(1, BlockSize.S_1024_BERT.numberOfBlocksPerMessage(2047)); 32 | assertEquals(2, BlockSize.S_1024_BERT.numberOfBlocksPerMessage(2048)); 33 | 34 | assertEquals(9, BlockSize.S_1024_BERT.numberOfBlocksPerMessage(10_000)); 35 | } 36 | 37 | @Test 38 | void serializeSize() { 39 | assertEquals(0, BlockSize.S_16.toRawSzx()); 40 | assertEquals(1, BlockSize.S_32.toRawSzx()); 41 | assertEquals(2, BlockSize.S_64.toRawSzx()); 42 | assertEquals(3, BlockSize.S_128.toRawSzx()); 43 | assertEquals(4, BlockSize.S_256.toRawSzx()); 44 | assertEquals(5, BlockSize.S_512.toRawSzx()); 45 | assertEquals(6, BlockSize.S_1024.toRawSzx()); 46 | assertEquals(7, BlockSize.S_1024_BERT.toRawSzx()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/packet/EofInputStreamTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import static org.assertj.core.api.Assertions.*; 20 | import static org.junit.jupiter.api.Assertions.*; 21 | import java.io.ByteArrayInputStream; 22 | import java.io.EOFException; 23 | import java.io.IOException; 24 | import org.junit.jupiter.api.Test; 25 | 26 | 27 | public class EofInputStreamTest { 28 | 29 | @Test 30 | void shouldNotWrapWhenAlreadyStrictInputStream() { 31 | EofInputStream in = EofInputStream.wrap(new ByteArrayInputStream(new byte[]{1, 2})); 32 | 33 | assertSame(in, EofInputStream.wrap(in)); 34 | } 35 | 36 | @Test 37 | public void should_thrown_eof_when_end_of_stream() throws IOException { 38 | EofInputStream in = EofInputStream.wrap(new ByteArrayInputStream(new byte[]{1, 2})); 39 | 40 | assertEquals(1, in.read()); 41 | assertEquals(1, in.available()); 42 | assertEquals(2, in.read()); 43 | assertEquals(0, in.available()); 44 | 45 | assertThatThrownBy(in::read).isExactlyInstanceOf(EOFException.class); 46 | } 47 | 48 | @Test 49 | public void should_thrown_eof_when_reading_bytes() throws IOException { 50 | EofInputStream in = EofInputStream.wrap(new ByteArrayInputStream("testtest".getBytes())); 51 | 52 | assertEquals(5, in.read(new byte[6], 0, 5)); 53 | assertEquals(3, in.read(new byte[6], 0, 5)); 54 | 55 | assertThrows(EOFException.class, () -> in.read(new byte[6], 0, 5)); 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/packet/RawOptionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import nl.jqno.equalsverifier.EqualsVerifier; 20 | import nl.jqno.equalsverifier.Warning; 21 | import org.junit.jupiter.api.Test; 22 | 23 | public class RawOptionTest { 24 | 25 | @Test 26 | public void equalsAndHashTest() throws Exception { 27 | EqualsVerifier.forClass(RawOption.class).suppress(Warning.NONFINAL_FIELDS).verify(); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/packet/SeparateResponseTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.packet; 18 | 19 | import com.mbed.coap.transport.TransportContext; 20 | import java.util.concurrent.CompletableFuture; 21 | import java.util.function.Supplier; 22 | import nl.jqno.equalsverifier.EqualsVerifier; 23 | import nl.jqno.equalsverifier.Func; 24 | import org.junit.jupiter.api.Test; 25 | 26 | class SeparateResponseTest { 27 | 28 | @Test 29 | public void equalsAndHashTest() { 30 | EqualsVerifier.forClass(SeparateResponse.class) 31 | .withGenericPrefabValues(Supplier.class, (Func.Func1, Supplier>) o -> () -> o) 32 | .withGenericPrefabValues(CompletableFuture.class, (Func.Func1) coapResponse -> new CompletableFuture<>()) 33 | .withPrefabValues(CoapResponse.class, CoapResponse.badRequest().build(), CoapResponse.ok().build()) 34 | .withPrefabValues(TransportContext.class, TransportContext.EMPTY, TransportContext.of(TransportContext.NON_CONFIRMABLE, true)) 35 | .usingGetClass() 36 | .verify(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/server/CoapRequestIdTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server; 18 | 19 | import java.net.InetSocketAddress; 20 | import nl.jqno.equalsverifier.EqualsVerifier; 21 | import nl.jqno.equalsverifier.Warning; 22 | import org.junit.jupiter.api.Test; 23 | 24 | public class CoapRequestIdTest { 25 | 26 | CoapRequestId requestId = new CoapRequestId(5000, new InetSocketAddress("127.0.0.1", 20000)); 27 | CoapRequestId requestId2 = new CoapRequestId(5000, new InetSocketAddress("127.0.0.1", 20000)); 28 | CoapRequestId requestId3 = new CoapRequestId(5002, new InetSocketAddress("127.0.0.1", 20000)); 29 | CoapRequestId requestId4 = new CoapRequestId(5000, new InetSocketAddress("192.168.0.1", 20000)); 30 | 31 | @Test 32 | public void testGetCreatedTimestampMillis() { 33 | assert (Math.abs(System.currentTimeMillis() - requestId.getCreatedTimestampMillis()) < 1000); 34 | } 35 | 36 | @Test 37 | public void testGetMid() { 38 | assert (requestId.getMid() == 5000); 39 | } 40 | 41 | @Test 42 | public void testGetSourceAddress() { 43 | assert (requestId.getSourceAddress().equals(new InetSocketAddress("127.0.0.1", 20000))); 44 | } 45 | 46 | @Test 47 | public void equalsAndHashTest() throws Exception { 48 | EqualsVerifier.forClass(CoapRequestId.class).suppress(Warning.NONFINAL_FIELDS).usingGetClass().verify(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/server/CriticalOptionVerifierTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server; 17 | 18 | import static com.mbed.coap.packet.CoapRequest.get; 19 | import static com.mbed.coap.packet.CoapResponse.of; 20 | import static org.junit.jupiter.api.Assertions.assertEquals; 21 | import com.mbed.coap.packet.CoapRequest; 22 | import com.mbed.coap.packet.CoapResponse; 23 | import com.mbed.coap.packet.Code; 24 | import com.mbed.coap.packet.Opaque; 25 | import java.util.concurrent.CompletableFuture; 26 | import org.junit.jupiter.api.Test; 27 | 28 | class CriticalOptionVerifierTest { 29 | 30 | private final CriticalOptionVerifier filter = new CriticalOptionVerifier(); 31 | 32 | @Test 33 | void shouldReturnBadOptionWhenUnrecognizedCriticalOption() { 34 | CoapRequest req = get("/test").options(o -> o.custom(1001, Opaque.of("foo"))).build(); 35 | 36 | CompletableFuture resp = filter.apply(req, null); 37 | 38 | assertEquals(of(Code.C402_BAD_OPTION), resp.join()); 39 | } 40 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/server/block/BlockRequestIdTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.block; 17 | 18 | import nl.jqno.equalsverifier.EqualsVerifier; 19 | import nl.jqno.equalsverifier.Warning; 20 | import org.junit.jupiter.api.Test; 21 | 22 | class BlockRequestIdTest { 23 | 24 | @Test 25 | public void equalsAndHashTest() throws Exception { 26 | EqualsVerifier.forClass(BlockRequestId.class).suppress(Warning.NONFINAL_FIELDS).usingGetClass().verify(); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/server/filter/EtagGeneratorFilterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.filter; 17 | 18 | import static com.mbed.coap.packet.CoapRequest.get; 19 | import static com.mbed.coap.packet.CoapResponse.ok; 20 | import static com.mbed.coap.packet.Opaque.ofBytes; 21 | import static org.junit.jupiter.api.Assertions.assertEquals; 22 | import com.mbed.coap.packet.CoapRequest; 23 | import com.mbed.coap.packet.CoapResponse; 24 | import com.mbed.coap.utils.Filter; 25 | import com.mbed.coap.utils.Service; 26 | import org.junit.jupiter.api.Test; 27 | 28 | class EtagGeneratorFilterTest { 29 | private final Filter.SimpleFilter filter = new EtagGeneratorFilter(__ -> ofBytes(1, 2)); 30 | 31 | @Test 32 | void shouldAddEtagToResponse() { 33 | Service service = filter.then(req -> ok("ok").toFuture()); 34 | 35 | assertEquals(ofBytes(1, 2), service.apply(get("/test").build()).join().options().getEtag()); 36 | } 37 | 38 | @Test 39 | void shouldNotChangeEtagToResponseWhenExists() { 40 | Service service = filter.then(req -> ok("ok").etag(ofBytes(99)).toFuture()); 41 | 42 | assertEquals(ofBytes(99), service.apply(get("/test").build()).join().options().getEtag()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/server/messaging/PiggybackedCorrelationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import nl.jqno.equalsverifier.EqualsVerifier; 20 | import nl.jqno.equalsverifier.Warning; 21 | import org.junit.jupiter.api.Test; 22 | 23 | 24 | public class PiggybackedCorrelationTest { 25 | 26 | @Test 27 | public void equalsAndHashTest() throws Exception { 28 | EqualsVerifier.forClass(PiggybackedCorrelation.class).suppress(Warning.NONFINAL_FIELDS).usingGetClass().verify(); 29 | 30 | EqualsVerifier.forClass(TransactionId.class).suppress(Warning.NONFINAL_FIELDS).usingGetClass().verify(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/server/messaging/RequestTagSupplierTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import org.junit.jupiter.api.Test; 20 | 21 | public class RequestTagSupplierTest { 22 | 23 | @Test 24 | void shouldGeneratedSequentialRequestTags() { 25 | RequestTagSupplier requestTagSupplier = RequestTagSupplier.createSequential(0); 26 | 27 | assertEquals("01", requestTagSupplier.next().toHex()); 28 | assertEquals("02", requestTagSupplier.next().toHex()); 29 | assertEquals("03", requestTagSupplier.next().toHex()); 30 | } 31 | 32 | @Test 33 | void shouldGeneratedSequentialRequestTags_lardInit() { 34 | RequestTagSupplier requestTagSupplier = RequestTagSupplier.createSequential(0x7ffffffd); 35 | 36 | assertEquals("7ffffffe", requestTagSupplier.next().toHex()); 37 | assertEquals("7fffffff", requestTagSupplier.next().toHex()); 38 | assertEquals("00", requestTagSupplier.next().toHex()); 39 | assertEquals("01", requestTagSupplier.next().toHex()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/transport/LoggingCoapTransportTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2024 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.transport; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import org.junit.jupiter.api.Test; 20 | import org.mockito.Mockito; 21 | 22 | class LoggingCoapTransportTest { 23 | 24 | @Test 25 | void shouldUnwrapTransport() { 26 | CoapTransport transport = Mockito.mock(CoapTransport.class); 27 | LoggingCoapTransport loggingCoapTransport = LoggingCoapTransport.wrap(transport); 28 | 29 | assertEquals(transport, LoggingCoapTransport.unwrap(loggingCoapTransport)); 30 | assertEquals(transport, LoggingCoapTransport.unwrap(transport)); 31 | } 32 | 33 | @Test 34 | void shouldNotWrapTransportWhenAlreadyLoggingCoapTransport() { 35 | CoapTransport transport = Mockito.mock(CoapTransport.class); 36 | LoggingCoapTransport loggingCoapTransport = LoggingCoapTransport.wrap(transport); 37 | 38 | // when 39 | LoggingCoapTransport wrapped = LoggingCoapTransport.wrap(loggingCoapTransport); 40 | 41 | // then 42 | assertEquals(loggingCoapTransport, wrapped); 43 | assertEquals(transport, loggingCoapTransport.getTransport()); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/utils/AsyncQueueTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import static org.junit.jupiter.api.Assertions.*; 19 | import java.util.concurrent.CompletableFuture; 20 | import org.junit.jupiter.api.BeforeEach; 21 | import org.junit.jupiter.api.Test; 22 | 23 | public class AsyncQueueTest { 24 | 25 | private final AsyncQueue queue = new AsyncQueue<>(); 26 | 27 | @BeforeEach 28 | void setUp() { 29 | queue.removeAll(); 30 | } 31 | 32 | @Test 33 | public void addFirst() { 34 | queue.add("1"); 35 | queue.add("2"); 36 | queue.add("3"); 37 | 38 | assertEquals("1", queue.poll().join()); 39 | assertEquals("2", queue.poll().join()); 40 | assertEquals("3", queue.poll().join()); 41 | assertFalse(queue.poll().isDone()); 42 | } 43 | 44 | @Test 45 | public void pollFirst() { 46 | CompletableFuture resp1 = queue.poll(); 47 | CompletableFuture resp2 = queue.poll(); 48 | CompletableFuture resp3 = queue.poll(); 49 | 50 | queue.add("1"); 51 | queue.add("2"); 52 | queue.add("3"); 53 | 54 | assertEquals("1", resp1.join()); 55 | assertEquals("2", resp2.join()); 56 | assertEquals("3", resp3.join()); 57 | } 58 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/utils/Exceptions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import java.util.concurrent.CompletionException; 19 | 20 | public class Exceptions { 21 | 22 | public static T reThrow(CheckExceptionSupplier f) { 23 | try { 24 | return f.get(); 25 | } catch (Exception ex) { 26 | throw new CompletionException(ex); 27 | } 28 | } 29 | 30 | @FunctionalInterface 31 | public interface CheckExceptionSupplier { 32 | T get() throws Exception; 33 | } 34 | } -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/utils/FutureHelpersTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import static com.mbed.coap.utils.FutureHelpers.failedFuture; 19 | import static java.util.concurrent.CompletableFuture.*; 20 | import static org.assertj.core.api.Assertions.*; 21 | import static org.junit.jupiter.api.Assertions.*; 22 | import java.io.IOException; 23 | import java.util.concurrent.CompletableFuture; 24 | import org.junit.jupiter.api.Test; 25 | 26 | class FutureHelpersTest { 27 | 28 | @Test 29 | void shouldBecome() { 30 | CompletableFuture promise = new CompletableFuture<>(); 31 | CompletableFuture future = completedFuture("dupa"); 32 | 33 | FutureHelpers.become(promise, future); 34 | 35 | assertEquals("dupa", promise.join()); 36 | } 37 | 38 | @Test 39 | void shouldBecome_exception() { 40 | CompletableFuture promise = new CompletableFuture<>(); 41 | CompletableFuture future = failedFuture(new IOException()); 42 | 43 | FutureHelpers.become(promise, future); 44 | 45 | assertTrue(promise.isCompletedExceptionally()); 46 | assertThatThrownBy(promise::join).hasCauseExactlyInstanceOf(IOException.class); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/utils/FutureQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.utils; 18 | 19 | import java.util.concurrent.CompletableFuture; 20 | import java.util.function.Supplier; 21 | 22 | public class FutureQueue implements Supplier> { 23 | public volatile CompletableFuture promise = null; 24 | 25 | @Override 26 | public CompletableFuture get() { 27 | if (promise != null) { 28 | throw new IllegalStateException(); 29 | } 30 | promise = new CompletableFuture<>(); 31 | return promise; 32 | } 33 | 34 | public boolean cancel() { 35 | if (promise != null) { 36 | CompletableFuture tmpPromise = this.promise; 37 | this.promise = null; 38 | return tmpPromise.cancel(false); 39 | } 40 | return false; 41 | } 42 | 43 | public boolean put(T obj) { 44 | if (promise != null) { 45 | CompletableFuture tmpPromise = this.promise; 46 | this.promise = null; 47 | return tmpPromise.complete(obj); 48 | } 49 | return false; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /coap-core/src/test/java/com/mbed/coap/utils/TimerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2025 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import static org.mockito.Mockito.never; 19 | import static org.mockito.Mockito.timeout; 20 | import static org.mockito.Mockito.verify; 21 | import java.time.Duration; 22 | import java.util.concurrent.Executors; 23 | import org.junit.jupiter.api.Test; 24 | import org.mockito.Mockito; 25 | 26 | class TimerTest { 27 | 28 | private final Timer timer = Timer.toTimer(Executors.newSingleThreadScheduledExecutor()); 29 | 30 | @Test 31 | void shouldSchedule() { 32 | Runnable task = Mockito.mock(Runnable.class); 33 | Runnable task2 = Mockito.mock(Runnable.class); 34 | 35 | timer.schedule(Duration.ofMillis(3), task); 36 | timer.schedule(Duration.ofMillis(1), task2); 37 | 38 | verify(task, timeout(200)).run(); 39 | verify(task2, timeout(200)).run(); 40 | } 41 | 42 | @Test 43 | void shouldCancel() throws InterruptedException { 44 | Runnable task = Mockito.mock(Runnable.class); 45 | 46 | Runnable cancel = timer.schedule(Duration.ofMillis(10), task); 47 | cancel.run(); 48 | 49 | Thread.sleep(11); 50 | verify(task, never()).run(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /coap-core/src/test/java/protocolTests/UdpIntegrationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package protocolTests; 17 | 18 | import static com.mbed.coap.transport.udp.DatagramSocketTransport.udp; 19 | import static com.mbed.coap.utils.Networks.localhost; 20 | import com.mbed.coap.client.CoapClient; 21 | import com.mbed.coap.packet.BlockSize; 22 | import com.mbed.coap.packet.CoapRequest; 23 | import com.mbed.coap.packet.CoapResponse; 24 | import com.mbed.coap.server.CoapServer; 25 | import com.mbed.coap.server.filter.TokenGeneratorFilter; 26 | import com.mbed.coap.utils.Filter; 27 | import com.mbed.coap.utils.Service; 28 | import java.io.IOException; 29 | 30 | public class UdpIntegrationTest extends IntegrationTestBase { 31 | 32 | @Override 33 | protected CoapClient buildClient(int port) throws IOException { 34 | return CoapServer.builder() 35 | .transport(udp()) 36 | .notificationsReceiver(receiver) 37 | .blockSize(BlockSize.S_1024) 38 | .outboundFilter(TokenGeneratorFilter.sequential(1)) 39 | .buildClient(localhost(port)); 40 | } 41 | 42 | @Override 43 | protected CoapServer buildServer(int port, Filter.SimpleFilter routeFilter, Service route) { 44 | return CoapServer.builder() 45 | .blockSize(BlockSize.S_1024) 46 | .transport(udp(port)) 47 | .routeFilter(routeFilter) 48 | .route(route) 49 | .build(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /coap-core/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | %d{HH:mm:ss} %.-1level %m %n 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/Assertions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import com.mbed.coap.packet.CoapRequest; 19 | import com.mbed.coap.packet.CoapResponse; 20 | 21 | public class Assertions { 22 | 23 | public static void assertEquals(CoapResponse.Builder expected, CoapResponse actual) { 24 | org.junit.jupiter.api.Assertions.assertEquals(expected.build(), actual); 25 | } 26 | 27 | public static void assertEquals(CoapRequest.Builder expected, CoapRequest actual) { 28 | org.junit.jupiter.api.Assertions.assertEquals(expected.build(), actual); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/AsyncQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import static com.mbed.coap.utils.FutureHelpers.failedFuture; 19 | import static java.util.concurrent.CompletableFuture.*; 20 | import java.util.LinkedList; 21 | import java.util.concurrent.CompletableFuture; 22 | 23 | public class AsyncQueue { 24 | 25 | private final LinkedList> queue = new LinkedList<>(); 26 | 27 | public synchronized void add(T obj) { 28 | if (!queue.isEmpty() && !queue.getFirst().isDone()) { 29 | queue.removeFirst().complete(obj); 30 | } else { 31 | queue.addLast(completedFuture(obj)); 32 | } 33 | } 34 | 35 | public synchronized void addException(Exception ex) { 36 | if (!queue.isEmpty() && !queue.getFirst().isDone()) { 37 | queue.removeFirst().completeExceptionally(ex); 38 | } else { 39 | queue.addLast(failedFuture(ex)); 40 | } 41 | } 42 | 43 | public synchronized CompletableFuture poll() { 44 | if (!queue.isEmpty() && queue.getFirst().isDone()) { 45 | return queue.removeFirst(); 46 | } 47 | 48 | CompletableFuture promise = new CompletableFuture<>(); 49 | queue.addLast(promise); 50 | return promise; 51 | } 52 | 53 | public synchronized void removeAll() { 54 | while (!queue.isEmpty()) { 55 | queue.removeFirst().cancel(false); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/Bytes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.utils; 18 | 19 | import com.mbed.coap.packet.Opaque; 20 | import java.util.Arrays; 21 | import java.util.Random; 22 | 23 | public class Bytes { 24 | 25 | public static Opaque opaqueOfSize(int newSize) { 26 | return new Opaque(new byte[newSize]); 27 | } 28 | 29 | public static Opaque opaqueOfRandom(int size) { 30 | byte[] randomData = new byte[size]; 31 | new Random().nextBytes(randomData); 32 | return new Opaque(randomData); 33 | } 34 | 35 | public static Opaque opaqueOfSize(int val, int size) { 36 | byte[] result = new byte[size]; 37 | Arrays.fill(result, (byte) val); 38 | return Opaque.of(result); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/CoapRequestBuilderFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import com.mbed.coap.packet.CoapRequest; 19 | import com.mbed.coap.packet.CoapResponse; 20 | 21 | public class CoapRequestBuilderFilter { 22 | 23 | public static final Filter REQUEST_BUILDER_FILTER = (request, service) -> { 24 | return service.apply(request.build()); 25 | }; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/MockTimer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import java.time.Duration; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | public class MockTimer implements Timer { 23 | 24 | private final List tasks = new ArrayList<>(); 25 | private Duration lastScheduledDelay = null; 26 | 27 | @Override 28 | public Runnable schedule(Duration delay, Runnable task) { 29 | lastScheduledDelay = delay; 30 | tasks.add(task); 31 | return () -> tasks.removeIf(entry -> task == entry); 32 | } 33 | 34 | public void runAll() { 35 | List tmp = new ArrayList<>(tasks); 36 | tasks.clear(); 37 | tmp.forEach(Runnable::run); 38 | } 39 | 40 | public int size() { 41 | return tasks.size(); 42 | } 43 | 44 | public boolean isEmpty() { 45 | return tasks.isEmpty(); 46 | } 47 | 48 | public Duration getLastScheduledDelay() { 49 | return lastScheduledDelay; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/Networks.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import static com.mbed.coap.utils.FutureHelpers.wrapExceptions; 19 | import java.net.InetAddress; 20 | import java.net.InetSocketAddress; 21 | 22 | public final class Networks { 23 | public static InetSocketAddress localhost(int localPort) { 24 | return wrapExceptions(() -> 25 | new InetSocketAddress(InetAddress.getLocalHost(), localPort) 26 | ); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/com/mbed/coap/utils/ObservableResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.utils; 17 | 18 | import static com.mbed.coap.packet.CoapResponse.coapResponse; 19 | import static java.util.Objects.requireNonNull; 20 | import static java.util.concurrent.CompletableFuture.completedFuture; 21 | import com.mbed.coap.packet.CoapRequest; 22 | import com.mbed.coap.packet.CoapResponse; 23 | import com.mbed.coap.packet.Code; 24 | import com.mbed.coap.packet.Opaque; 25 | import com.mbed.coap.server.observe.ObserversManager; 26 | import java.util.concurrent.CompletableFuture; 27 | 28 | public class ObservableResource implements Service { 29 | 30 | private final ObserversManager observersManager; 31 | private CoapResponse current; 32 | private final String uriPath; 33 | 34 | public ObservableResource(String uriPath, CoapResponse.Builder current, ObserversManager observersManager) { 35 | this.current = current.observe(0).build(); 36 | this.observersManager = observersManager; 37 | this.uriPath = uriPath; 38 | } 39 | 40 | @Override 41 | public CompletableFuture apply(CoapRequest req) { 42 | return completedFuture(observersManager.subscribe(req, current)); 43 | } 44 | 45 | public void putPayload(Opaque payload) { 46 | put(current.withPayload(payload)); 47 | } 48 | 49 | public void terminate(Code code) { 50 | requireNonNull(code); 51 | put(coapResponse(code).observe(current.options().getObserve()).build()); 52 | } 53 | 54 | public void put(CoapResponse obs) { 55 | observersManager.sendObservation(uriPath, __ -> completedFuture(obs)); 56 | current = obs; 57 | } 58 | 59 | public int observationRelations() { 60 | return observersManager.size(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /coap-core/src/testFixtures/java/protocolTests/utils/StubNotificationsReceiver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package protocolTests.utils; 17 | 18 | import static com.mbed.coap.utils.Assertions.assertEquals; 19 | import com.mbed.coap.packet.CoapResponse; 20 | import com.mbed.coap.packet.SeparateResponse; 21 | import com.mbed.coap.server.observe.NotificationsReceiver; 22 | import java.util.concurrent.BlockingQueue; 23 | import java.util.concurrent.LinkedBlockingQueue; 24 | import java.util.concurrent.TimeUnit; 25 | 26 | public class StubNotificationsReceiver implements NotificationsReceiver { 27 | 28 | final BlockingQueue queue = new LinkedBlockingQueue<>(); 29 | 30 | @Override 31 | public boolean onObservation(String resourceUriPath, SeparateResponse obs) { 32 | queue.add(obs); 33 | return true; 34 | } 35 | 36 | public SeparateResponse take() throws InterruptedException { 37 | return queue.poll(5, TimeUnit.SECONDS); 38 | } 39 | 40 | public void verifyReceived(CoapResponse.Builder obs) throws InterruptedException { 41 | CoapResponse received = queue.poll(1, TimeUnit.SECONDS).asResponse(); 42 | assertEquals(obs, received); 43 | } 44 | 45 | public boolean noMoreReceived() { 46 | return queue.isEmpty(); 47 | } 48 | 49 | public void clear() { 50 | queue.clear(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /coap-mbedtls/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java-library") 3 | } 4 | 5 | description = "coap-mbedtls" 6 | 7 | dependencies { 8 | api(project(":coap-core")) 9 | api("io.github.open-coap:kotlin-mbedtls:1.30.0") 10 | api("io.github.open-coap:kotlin-mbedtls-netty:1.30.0") 11 | 12 | testImplementation(project(":coap-netty")) 13 | 14 | testImplementation(testFixtures(project(":coap-core"))) 15 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.13.0") 16 | testImplementation("io.netty:netty-transport-native-epoll:4.2.1.Final:linux-x86_64") 17 | testImplementation("ch.qos.logback:logback-classic:1.3.15") 18 | testImplementation("org.awaitility:awaitility:4.3.0") 19 | } 20 | -------------------------------------------------------------------------------- /coap-mbedtls/src/main/java/org/opencoap/transport/mbedtls/DtlsSessionSuspensionService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2024 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.opencoap.transport.mbedtls; 17 | 18 | import static com.mbed.coap.transport.TransportContext.NON_CONFIRMABLE; 19 | import static org.opencoap.transport.mbedtls.DtlsTransportContext.DTLS_SESSION_SUSPENSION_HINT; 20 | import com.mbed.coap.packet.CoapRequest; 21 | import com.mbed.coap.packet.CoapResponse; 22 | import com.mbed.coap.transport.TransportContext; 23 | import com.mbed.coap.utils.Service; 24 | import java.util.concurrent.CompletableFuture; 25 | 26 | public class DtlsSessionSuspensionService implements Service { 27 | @Override 28 | public CompletableFuture apply(CoapRequest request) { 29 | if (!request.getTransContext(NON_CONFIRMABLE)) { 30 | return CoapResponse.badRequest().toFuture(); 31 | } 32 | 33 | return CoapResponse.ok().addContext(TransportContext.of(DTLS_SESSION_SUSPENSION_HINT, true)).toFuture(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /coap-mbedtls/src/test/java/org/opencoap/transport/mbedtls/DtlsSessionSuspensionServiceTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2024 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.opencoap.transport.mbedtls; 17 | 18 | import static com.mbed.coap.packet.CoapResponse.of; 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import com.mbed.coap.packet.CoapRequest; 21 | import com.mbed.coap.packet.CoapResponse; 22 | import com.mbed.coap.packet.Code; 23 | import com.mbed.coap.transport.TransportContext; 24 | import com.mbed.coap.utils.Service; 25 | import org.junit.jupiter.api.Test; 26 | 27 | class DtlsSessionSuspensionServiceTest { 28 | private final Service service = new DtlsSessionSuspensionService(); 29 | 30 | @Test 31 | void shouldReturnBadRequestWhenRequestIsConfirmable() { 32 | assertEquals(of(Code.C400_BAD_REQUEST), service.apply(CoapRequest.get("/test").build()).join()); 33 | } 34 | 35 | @Test 36 | void shouldReturnResponseWithExpirationHint() { 37 | CoapResponse resp = service.apply(CoapRequest.get("/test").context(TransportContext.of(TransportContext.NON_CONFIRMABLE, true)).build()).join(); 38 | assertEquals(Code.C205_CONTENT, resp.getCode()); 39 | assertTrue(resp.getTransContext().get(DtlsTransportContext.DTLS_SESSION_SUSPENSION_HINT)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /coap-mbedtls/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d{HH:mm:ss} [tid:%10.10thread] %-5level %-80msg [%logger]%n 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /coap-metrics/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java-library") 3 | } 4 | 5 | description = "coap-metrics" 6 | 7 | dependencies { 8 | api(project(":coap-core")) 9 | 10 | implementation("io.micrometer:micrometer-core:1.15.0") 11 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.13.0") 12 | testImplementation(testFixtures(project(":coap-core"))) 13 | } 14 | -------------------------------------------------------------------------------- /coap-netty/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java-library") 3 | id("me.champeau.jmh") version "0.7.3" 4 | } 5 | 6 | description = "coap-netty" 7 | 8 | dependencies { 9 | api(project(":coap-core")) 10 | api("io.netty:netty-handler:4.2.1.Final") 11 | 12 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.13.0") 13 | 14 | testImplementation(testFixtures(project(":coap-core"))) 15 | testImplementation("ch.qos.logback:logback-classic:1.3.15") 16 | testImplementation("io.netty:netty-transport-native-epoll:4.2.1.Final:linux-x86_64") 17 | 18 | jmhImplementation("io.netty:netty-all:4.2.1.Final") 19 | jmh("org.openjdk.jmh:jmh-core:1.37") 20 | jmh("org.openjdk.jmh:jmh-generator-bytecode:1.37") 21 | } 22 | 23 | tasks { 24 | named("pmdJmh").get().enabled = false 25 | named("spotbugsJmh").get().enabled = false 26 | } 27 | -------------------------------------------------------------------------------- /coap-netty/src/main/java/org/opencoap/coap/netty/NettyUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.opencoap.coap.netty; 17 | 18 | import static java.util.concurrent.CompletableFuture.completedFuture; 19 | import io.netty.util.concurrent.Promise; 20 | import java.util.concurrent.CompletableFuture; 21 | 22 | public class NettyUtils { 23 | 24 | public static CompletableFuture toCompletableFuture(Promise nettyPromise) { 25 | 26 | if (nettyPromise.isSuccess()) { 27 | return completedFuture(nettyPromise.getNow()); 28 | } 29 | 30 | CompletableFuture promise = new CompletableFuture<>(); 31 | nettyPromise.addListener(future -> { 32 | if (future.cause() != null) { 33 | promise.completeExceptionally(future.cause()); 34 | } else { 35 | promise.complete(nettyPromise.getNow()); 36 | } 37 | }); 38 | 39 | return promise; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /coap-netty/src/test/java/org/opencoap/coap/netty/NettyCoapTransportTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.opencoap.coap.netty; 17 | 18 | import static com.mbed.coap.utils.Networks.localhost; 19 | import static org.junit.jupiter.api.Assertions.assertEquals; 20 | import static org.junit.jupiter.api.Assertions.assertFalse; 21 | import static org.opencoap.coap.netty.CoapCodec.EMPTY_RESOLVER; 22 | import static org.opencoap.coap.netty.CoapCodecTest.encodeToBuf; 23 | import static protocolTests.utils.CoapPacketBuilder.newCoapPacket; 24 | import com.mbed.coap.packet.CoapPacket; 25 | import io.netty.channel.embedded.EmbeddedChannel; 26 | import io.netty.channel.socket.DatagramPacket; 27 | import java.util.concurrent.CompletableFuture; 28 | import java.util.concurrent.ExecutionException; 29 | import org.junit.jupiter.api.Test; 30 | 31 | public class NettyCoapTransportTest { 32 | 33 | private EmbeddedChannel channel = new EmbeddedChannel(); 34 | 35 | @Test 36 | void should_receive() throws ExecutionException, InterruptedException { 37 | NettyCoapTransport transport = new NettyCoapTransport(null, EMPTY_RESOLVER); 38 | transport.init(channel); 39 | 40 | // when 41 | CompletableFuture receive = transport.receive(); 42 | CoapPacket coap = newCoapPacket(123).get().uriPath("/test").build(); 43 | channel.writeInbound(new DatagramPacket(encodeToBuf(coap), localhost(5684))); 44 | 45 | // then 46 | assertEquals(coap, receive.get()); 47 | // and 48 | assertFalse(transport.receive().isDone()); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /coap-netty/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %d{HH:mm:ss} %.-1level %m [%10.10thread]%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /coap-tcp/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java-library") 3 | } 4 | 5 | description = "coap-tcp" 6 | 7 | dependencies { 8 | api(project(":coap-core")) 9 | api("org.slf4j:slf4j-api:2.0.17") 10 | 11 | testImplementation(testFixtures(project(":coap-core"))) 12 | 13 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.13.0") 14 | testImplementation("ch.qos.logback:logback-classic:1.3.15") 15 | testImplementation("org.mockito:mockito-core:4.11.0") 16 | testImplementation("org.assertj:assertj-core:3.27.3") 17 | testImplementation("nl.jqno.equalsverifier:equalsverifier:3.19.4") 18 | testImplementation("org.awaitility:awaitility:4.3.0") 19 | } 20 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/packet/CoapTcpPacketConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.packet; 17 | 18 | public class CoapTcpPacketConverter { 19 | 20 | public static CoapPacket toCoapPacket(CoapRequest request) { 21 | CoapPacket packet = new CoapPacket(request.getPeerAddress()); 22 | packet.setMessageType(null); 23 | 24 | if (request.isPing()) { 25 | packet.setCode(Code.C702_PING); 26 | } else { 27 | packet.setMethod(request.getMethod()); 28 | packet.setToken(request.getToken()); 29 | packet.setHeaderOptions(request.options()); 30 | packet.setPayload(request.getPayload()); 31 | } 32 | 33 | return packet; 34 | } 35 | 36 | public static CoapPacket toCoapPacket(SeparateResponse resp) { 37 | CoapPacket packet = new CoapPacket(resp.getPeerAddress()); 38 | packet.setMessageType(null); 39 | packet.setCode(resp.getCode()); 40 | packet.setToken(resp.getToken()); 41 | packet.setHeaderOptions(resp.options().duplicate()); 42 | packet.setPayload(resp.getPayload()); 43 | return packet; 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/server/TcpCoapServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server; 17 | 18 | public class TcpCoapServer { 19 | 20 | public static CoapServerBuilderForTcp builder() { 21 | return new CoapServerBuilderForTcp(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/server/messaging/CapabilitiesStorage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import java.net.InetSocketAddress; 20 | 21 | /** 22 | * CoAP over TCP capabilities and settings storage interface 23 | */ 24 | public interface CapabilitiesStorage extends CapabilitiesResolver { 25 | void put(InetSocketAddress address, Capabilities capabilities); 26 | 27 | void remove(InetSocketAddress address); 28 | } 29 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/server/messaging/CapabilitiesStorageImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import java.net.InetSocketAddress; 20 | import java.util.concurrent.ConcurrentHashMap; 21 | 22 | /** 23 | * Per-connection CSM storage 24 | */ 25 | public class CapabilitiesStorageImpl implements CapabilitiesStorage { 26 | //package local for tests 27 | final ConcurrentHashMap capabilitiesMap = new ConcurrentHashMap<>(); 28 | private final Capabilities defaultCapability; 29 | 30 | public CapabilitiesStorageImpl(Capabilities defaultCapability) { 31 | this.defaultCapability = defaultCapability; 32 | } 33 | 34 | public CapabilitiesStorageImpl() { 35 | this(Capabilities.BASE); 36 | } 37 | 38 | @Override 39 | public void put(InetSocketAddress address, Capabilities newCapabilities) { 40 | if (Capabilities.BASE.equals(newCapabilities)) { 41 | capabilitiesMap.remove(address); 42 | } else { 43 | capabilitiesMap.put(address, newCapabilities); 44 | } 45 | } 46 | 47 | @Override 48 | public Capabilities getOrDefault(InetSocketAddress address) { 49 | return capabilitiesMap.getOrDefault(address, defaultCapability); 50 | } 51 | 52 | @Override 53 | public void remove(InetSocketAddress address) { 54 | capabilitiesMap.remove(address); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/server/messaging/PayloadSizeVerifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import static com.mbed.coap.utils.FutureHelpers.*; 19 | import com.mbed.coap.exception.CoapException; 20 | import com.mbed.coap.packet.CoapPacket; 21 | import com.mbed.coap.utils.Filter; 22 | import com.mbed.coap.utils.Service; 23 | import java.util.concurrent.CompletableFuture; 24 | 25 | public class PayloadSizeVerifier implements Filter.SimpleFilter { 26 | private final CapabilitiesResolver capabilitiesResolver; 27 | 28 | public PayloadSizeVerifier(CapabilitiesResolver capabilitiesResolver) { 29 | this.capabilitiesResolver = capabilitiesResolver; 30 | } 31 | 32 | @Override 33 | public CompletableFuture apply(CoapPacket packet, Service service) { 34 | if (verifyPayloadSize(packet)) { 35 | return failedFuture(new CoapException("Request payload size is too big and no block transfer support is enabled for " + packet.getRemoteAddress() + ": " + packet.getPayload().size())); 36 | } 37 | return service.apply(packet); 38 | } 39 | 40 | private boolean verifyPayloadSize(CoapPacket packet) { 41 | int payloadLen = packet.getPayload().size(); 42 | int maxMessageSize = capabilitiesResolver.getOrDefault(packet.getRemoteAddress()).getMaxMessageSizeInt(); 43 | 44 | return payloadLen > maxMessageSize; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/transport/CoapTcpListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.transport; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | public interface CoapTcpListener { 21 | void onDisconnected(InetSocketAddress remoteAddress); 22 | 23 | void onConnected(InetSocketAddress remoteAddress); 24 | } 25 | -------------------------------------------------------------------------------- /coap-tcp/src/main/java/com/mbed/coap/transport/CoapTcpTransport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.transport; 17 | 18 | public interface CoapTcpTransport extends CoapTransport { 19 | void setListener(CoapTcpListener listener); 20 | } 21 | -------------------------------------------------------------------------------- /coap-tcp/src/test/java/com/mbed/coap/packet/CoapPacketWithSignToStringTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.packet; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import org.junit.jupiter.api.Test; 20 | 21 | 22 | public class CoapPacketWithSignToStringTest { 23 | 24 | @Test 25 | public void toString_withCapabilities() { 26 | CoapPacket cp = new CoapPacket(Code.C701_CSM, null, null); 27 | SignallingHeaderOptions headers = new SignallingHeaderOptions(cp.getCode()); 28 | cp.setHeaderOptions(headers); 29 | 30 | headers.putSignallingOptions(SignalingOptions.capabilities(2000, true)); 31 | assertEquals("701 MID:0 MaxMsgSz:2000 Blocks", cp.toString()); 32 | 33 | headers.putSignallingOptions(SignalingOptions.capabilities(2000, false)); 34 | assertEquals("701 MID:0 MaxMsgSz:2000", cp.toString()); 35 | 36 | 37 | SignalingOptions signalingOptions = new SignalingOptions(); 38 | signalingOptions.setBlockWiseTransfer(true); 39 | headers.putSignallingOptions(signalingOptions); 40 | assertEquals("701 MID:0 Blocks", cp.toString()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /coap-tcp/src/test/java/com/mbed/coap/packet/SignallingHeaderOptionsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.packet; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import static org.junit.jupiter.api.Assertions.assertThrows; 20 | import nl.jqno.equalsverifier.EqualsVerifier; 21 | import nl.jqno.equalsverifier.Warning; 22 | import org.junit.jupiter.api.Test; 23 | 24 | class SignallingHeaderOptionsTest { 25 | 26 | @Test 27 | void duplicate() { 28 | SignallingHeaderOptions signOpts = new SignallingHeaderOptions(Code.C701_CSM); 29 | signOpts.putSignallingOptions(SignalingOptions.capabilities(100, true)); 30 | 31 | assertEquals(signOpts, signOpts.duplicate()); 32 | } 33 | 34 | @Test 35 | public void failWhenNotCSMCode() { 36 | assertThrows(IllegalArgumentException.class, () -> new SignallingHeaderOptions(Code.C205_CONTENT)); 37 | } 38 | 39 | @Test 40 | public void equalsAndHashTest() throws Exception { 41 | EqualsVerifier.forClass(SignallingHeaderOptions.class).suppress(Warning.NONFINAL_FIELDS).usingGetClass().verify(); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /coap-tcp/src/test/java/com/mbed/coap/server/messaging/CapabilitiesStorageImplTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.server.messaging; 18 | 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import static protocolTests.utils.CoapPacketBuilder.*; 21 | import org.junit.jupiter.api.Test; 22 | 23 | 24 | public class CapabilitiesStorageImplTest { 25 | 26 | @Test 27 | public void test() { 28 | CapabilitiesStorageImpl capabilities = new CapabilitiesStorageImpl(); 29 | 30 | assertEquals(Capabilities.BASE, capabilities.getOrDefault(LOCAL_5683)); 31 | 32 | capabilities.put(LOCAL_5683, new Capabilities(1001, true)); 33 | 34 | assertEquals(1001, capabilities.getOrDefault(LOCAL_5683).getMaxMessageSizeInt()); 35 | assertEquals(1001, capabilities.getOrDefault(LOCAL_5683).getMaxMessageSize()); 36 | 37 | capabilities.put(LOCAL_5683, Capabilities.BASE); // remove from storage 38 | assertNull(capabilities.capabilitiesMap.get(LOCAL_1_5683)); // should be removed 39 | 40 | assertEquals(Capabilities.BASE, capabilities.getOrDefault(LOCAL_5683)); 41 | } 42 | } -------------------------------------------------------------------------------- /coap-tcp/src/test/java/com/mbed/coap/server/messaging/PayloadSizeVerifierTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.server.messaging; 17 | 18 | import static com.mbed.coap.utils.Bytes.*; 19 | import static java.util.concurrent.CompletableFuture.*; 20 | import static org.assertj.core.api.Assertions.*; 21 | import static org.junit.jupiter.api.Assertions.*; 22 | import static protocolTests.utils.CoapPacketBuilder.*; 23 | import com.mbed.coap.exception.CoapException; 24 | import com.mbed.coap.packet.CoapPacket; 25 | import com.mbed.coap.utils.Service; 26 | import java.util.concurrent.CompletableFuture; 27 | import org.junit.jupiter.api.Test; 28 | 29 | class PayloadSizeVerifierTest { 30 | 31 | private final CapabilitiesStorageImpl csmStorage = new CapabilitiesStorageImpl(); 32 | private PayloadSizeVerifier verifier = new PayloadSizeVerifier<>(csmStorage); 33 | private final Service service = __ -> completedFuture(true); 34 | 35 | @Test 36 | public void shouldThrowExceptionWhenTooLargePayload() { 37 | CompletableFuture resp = verifier.apply(newCoapPacket(LOCAL_5683).post().uriPath("/").payload(opaqueOfSize(2000)).build(), service); 38 | 39 | assertTrue(resp.isCompletedExceptionally()); 40 | assertThatThrownBy(resp::get).hasCauseExactlyInstanceOf(CoapException.class); 41 | } 42 | 43 | @Test 44 | public void shouldForwardWhenPayloadSizeIsOK() { 45 | csmStorage.put(LOCAL_5683, new Capabilities(2000, true)); 46 | 47 | CompletableFuture resp = verifier.apply(newCoapPacket(LOCAL_5683).post().uriPath("/").payload(opaqueOfSize(2000)).build(), service); 48 | 49 | assertTrue(resp.join()); 50 | } 51 | 52 | 53 | } -------------------------------------------------------------------------------- /coap-tcp/src/test/java/com/mbed/coap/transport/javassl/SSLUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.coap.transport.javassl; 17 | 18 | import java.security.GeneralSecurityException; 19 | import java.security.KeyStore; 20 | import javax.net.ssl.KeyManagerFactory; 21 | import javax.net.ssl.SSLContext; 22 | import javax.net.ssl.TrustManagerFactory; 23 | 24 | public class SSLUtils { 25 | public static KeyStore ksFrom(String resource, char[] secret) { 26 | try { 27 | KeyStore keystore = KeyStore.getInstance("JKS"); 28 | keystore.load(SingleConnectionSSLSocketServerTransport.class.getResourceAsStream(resource), secret); 29 | return keystore; 30 | } catch (Exception e) { 31 | throw new RuntimeException(e); 32 | } 33 | } 34 | 35 | public static SSLContext sslContext(KeyStore ks, char[] secret) { 36 | try { 37 | final KeyManagerFactory kmf; 38 | kmf = KeyManagerFactory.getInstance("SunX509"); 39 | kmf.init(ks, secret); 40 | TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); 41 | tmf.init(ks); 42 | 43 | SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); 44 | 45 | sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); 46 | 47 | return sslContext; 48 | } catch (GeneralSecurityException e) { 49 | throw new RuntimeException(e); 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /coap-tcp/src/test/java/com/mbed/coap/transport/javassl/SingleConnectionSSLSocketServerTransport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.coap.transport.javassl; 18 | 19 | import java.io.IOException; 20 | import javax.net.ssl.SSLContext; 21 | import javax.net.ssl.SSLServerSocket; 22 | 23 | public class SingleConnectionSSLSocketServerTransport extends SingleConnectionSocketServerTransport { 24 | 25 | public SingleConnectionSSLSocketServerTransport(SSLContext sslContext, int port) throws IOException { 26 | super(sslContext.getServerSocketFactory().createServerSocket(port)); 27 | ((SSLServerSocket) serverSocket).setNeedClientAuth(true); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /coap-tcp/src/test/java/protocolTests/utils/MockCoapTcpTransport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package protocolTests.utils; 17 | 18 | import com.mbed.coap.transport.CoapTcpListener; 19 | import com.mbed.coap.transport.CoapTcpTransport; 20 | 21 | public class MockCoapTcpTransport extends MockCoapTransport implements CoapTcpTransport { 22 | public CoapTcpListener listener; 23 | 24 | @Override 25 | public void setListener(CoapTcpListener listener) { 26 | this.listener = listener; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /coap-tcp/src/test/resources/regenerate-keystores.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | SRV_KS="-keystore test-server.jks -storepass secret" 4 | CLI_KS="-keystore test-client.jks -storepass secret" 5 | 6 | mkdir -p target 7 | 8 | # server 9 | keytool $SRV_KS -genkey -keyalg EC -keysize 256 -alias server-ca -validity 3600 -keypass secret -dname "CN=server-ca" -ext bc=ca:true -deststoretype pkcs12 10 | keytool $SRV_KS -genkeypair -keyalg EC -keysize 256 -alias server -validity 3600 -dname "CN=server" -keypass secret 11 | keytool $SRV_KS -certreq -alias server -file target/server.csr 12 | keytool $SRV_KS -gencert -alias server-ca -infile target/server.csr -outfile target/server.cer -validity 3600 13 | keytool $SRV_KS -importcert -file target/server.cer -alias server 14 | keytool $SRV_KS -export -alias server-ca -file target/server-ca.cer 15 | 16 | 17 | # client 18 | keytool $CLI_KS -genkey -keyalg EC -keysize 256 -alias client-ca -validity 3600 -keypass secret -dname "CN=client-ca" -ext bc=ca:true -deststoretype pkcs12 19 | keytool $CLI_KS -genkeypair -keyalg EC -keysize 256 -alias client -validity 3600 -dname "CN=client" -keypass secret 20 | keytool $CLI_KS -certreq -alias client -file target/client.csr 21 | keytool $CLI_KS -gencert -alias client-ca -infile target/client.csr -outfile target/client.cer -validity 3600 22 | keytool $CLI_KS -importcert -file target/client.cer -alias client 23 | keytool $CLI_KS -export -alias client-ca -file target/client-ca.cer 24 | 25 | # add trusted 26 | 27 | keytool $SRV_KS -import -alias client-ca -file target/client-ca.cer -noprompt 28 | keytool $CLI_KS -import -alias server-ca -file target/server-ca.cer -noprompt 29 | -------------------------------------------------------------------------------- /coap-tcp/src/test/resources/test-client.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-coap/java-coap/71a934b84d7aa1d48f6908a6071962f535408126/coap-tcp/src/test/resources/test-client.jks -------------------------------------------------------------------------------- /coap-tcp/src/test/resources/test-server.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-coap/java-coap/71a934b84d7aa1d48f6908a6071962f535408126/coap-tcp/src/test/resources/test-server.jks -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | branch: master 3 | coverage: 4 | status: 5 | project: 6 | default: 7 | target: auto 8 | threshold: 1% 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-coap/java-coap/71a934b84d7aa1d48f6908a6071962f535408126/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /license-header.txt: -------------------------------------------------------------------------------- 1 | Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 2 | Copyright (C) 2011-2021 ARM Limited. All rights reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. -------------------------------------------------------------------------------- /lwm2m/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java-library") 3 | } 4 | 5 | description = "lwm2m" 6 | 7 | dependencies { 8 | api("com.google.code.gson:gson:2.13.1") 9 | api("org.slf4j:slf4j-api:2.0.17") 10 | 11 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.13.0") 12 | testImplementation("commons-io:commons-io:2.19.0") 13 | testImplementation("ch.qos.logback:logback-classic:1.3.15") 14 | testImplementation("org.mockito:mockito-core:4.11.0") 15 | testImplementation("org.hamcrest:hamcrest-all:1.3") 16 | testImplementation("nl.jqno.equalsverifier:equalsverifier:3.19.4") 17 | } 18 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/LWM2MResourceType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m; 17 | 18 | @Deprecated 19 | public enum LWM2MResourceType { 20 | 21 | STRING, INTEGER, FLOAT, BOOLEAN, OPAQUE, TIME, OBJECTLINK 22 | } 23 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/json/NumberTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.json; 17 | 18 | import com.google.gson.TypeAdapter; 19 | import com.google.gson.stream.JsonReader; 20 | import com.google.gson.stream.JsonWriter; 21 | import java.io.IOException; 22 | 23 | class NumberTypeAdapter extends TypeAdapter { 24 | 25 | @Override 26 | public void write(JsonWriter writer, Number value) throws IOException { 27 | if (value != null) { 28 | writer.value(value.toString() ); 29 | } else { 30 | writer.nullValue(); 31 | } 32 | } 33 | 34 | @Override 35 | public Number read(JsonReader reader) throws IOException { 36 | String string = reader.nextString(); 37 | Number number; 38 | 39 | if (string.indexOf('.') == -1) { 40 | number = Integer.parseInt(string); 41 | } else { 42 | number = Double.parseDouble(string); 43 | } 44 | 45 | return number; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/model/DefaultResourceValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.model; 17 | 18 | class DefaultResourceValidator implements ResourceValidator { 19 | 20 | private final boolean verdict; 21 | 22 | public DefaultResourceValidator (boolean verdict) { 23 | this.verdict = verdict; 24 | } 25 | 26 | @Override 27 | public boolean isValid(String value) { 28 | return verdict; 29 | } 30 | 31 | @Override 32 | public boolean isValid(int value) { 33 | return verdict; 34 | } 35 | 36 | @Override 37 | public boolean isValid(byte[] value) { 38 | return verdict; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/model/Instances.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.model; 17 | 18 | public enum Instances { 19 | 20 | SINGLE, MULTIPLE 21 | 22 | } 23 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/model/InvalidResourceURIException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.model; 17 | 18 | public class InvalidResourceURIException extends Exception { 19 | 20 | InvalidResourceURIException() { 21 | super(); 22 | } 23 | 24 | InvalidResourceURIException(String message) { 25 | super(message); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/model/NotFoundException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.model; 17 | 18 | public class NotFoundException extends Exception { 19 | 20 | NotFoundException() { 21 | super(); 22 | } 23 | 24 | NotFoundException(String message) { 25 | super(message); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/model/ResourceValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.model; 17 | 18 | interface ResourceValidator { 19 | 20 | boolean isValid (byte[] value); 21 | 22 | boolean isValid (int value); 23 | 24 | boolean isValid (String value); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/model/Type.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.model; 17 | 18 | public enum Type { 19 | 20 | STRING, INTEGER, FLOAT, BOOLEAN, OPAQUE, TIME, EXECUTABLE 21 | 22 | } 23 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/tlv/TLV.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.tlv; 17 | 18 | public class TLV { 19 | 20 | /** HTTP Media type for OMA TLV content. */ 21 | public static final String CT_APPLICATION_LWM2M_TLV = "application/vnd.oma.lwm2m+tlv"; 22 | 23 | static final byte TYPE_RESOURCE = (byte) 0b11_000000; 24 | static final byte TYPE_MULTIPLE_RESOURCE = (byte) 0b10_000000; 25 | static final byte TYPE_RESOURCE_INSTANCE = (byte) 0b01_000000; 26 | static final byte TYPE_OBJECT_INSTANCE = (byte) 0b00_000000; 27 | 28 | static final int ID8 = 0b00_000000; 29 | static final int ID16 = 0b00_1_00000; 30 | 31 | static final int LENGTH8 = 0b000_01_000; 32 | static final int LENGTH16 = 0b000_10_000; 33 | static final int LENGTH24 = 0b000_11_000; 34 | 35 | private TLV() { 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/transport/TransportBindingParseException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.transport; 17 | 18 | public class TransportBindingParseException extends Exception { 19 | 20 | public TransportBindingParseException() { 21 | super("Malformed transport binding"); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /lwm2m/src/main/java/com/mbed/lwm2m/utils/HexArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2011-2018 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.mbed.lwm2m.utils; 17 | 18 | /** 19 | * Utility class to convert byte array to string. 20 | */ 21 | public final class HexArray { 22 | 23 | private final static String HEX_DIGIT_STRING = "0123456789abcdef"; 24 | private final static char[] HEX_DIGITS = HEX_DIGIT_STRING.toCharArray(); 25 | 26 | /** 27 | * Converts byte array to hex string. 28 | * 29 | * @param data byte array data 30 | * @return hex string 31 | */ 32 | public static String toHex(final byte[] data) { 33 | return data != null ? toHex(data, data.length) : null; 34 | } 35 | 36 | /** 37 | * Converts byte array to hex string. 38 | * 39 | * @param data byte array data 40 | * @param len byte array length 41 | * @return hex string 42 | */ 43 | public static String toHex(final byte[] data, final int len) { 44 | final char[] retVal = new char[len * 2]; 45 | int k = 0; 46 | for (int i = 0; i < len; i++) { 47 | retVal[k++] = HEX_DIGITS[(data[i] & 0xf0) >>> 4]; 48 | retVal[k++] = HEX_DIGITS[data[i] & 0x0f]; 49 | } 50 | return new String(retVal); 51 | } 52 | 53 | /** 54 | * Converts hex string to byte array. 55 | * 56 | * @param hex hex string 57 | * @return byte array 58 | */ 59 | public static byte[] fromHex(String hex) { 60 | byte[] b = new byte[hex.length() / 2]; 61 | for (int i = 0; i < hex.length(); i += 2) { 62 | b[i / 2] = (byte) (HEX_DIGIT_STRING.indexOf(hex.charAt(i)) * 16 + HEX_DIGIT_STRING.indexOf(hex.charAt(i + 1))); 63 | } 64 | 65 | return b; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /lwm2m/src/test/java/com/mbed/lwm2m/LWM2MIDTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.lwm2m; 18 | 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import java.util.Objects; 21 | import org.junit.jupiter.api.Test; 22 | 23 | public class LWM2MIDTest { 24 | 25 | @Test 26 | public void testEquals() { 27 | assertFalse(new LWM2MID(null).equals(null)); 28 | assertTrue(Objects.equals(new LWM2MID(null), new LWM2MID(null))); 29 | assertTrue(Objects.equals(new LWM2MID(1), new LWM2MID(1))); 30 | assertTrue(Objects.equals(new LWM2MID("alma"), new LWM2MID("alma"))); 31 | assertFalse(Objects.equals(new LWM2MID("alma"), new LWM2MID("korte"))); 32 | } 33 | 34 | @Test 35 | public void testCompareTo() throws Exception { 36 | assertEquals(0, new LWM2MID(null).compareTo(new LWM2MID(null))); 37 | assertEquals(-1, new LWM2MID(null).compareTo(new LWM2MID("alma"))); 38 | assertEquals(1, new LWM2MID("alma").compareTo(new LWM2MID(null))); 39 | assertEquals(-10, new LWM2MID("alma").compareTo(new LWM2MID("korte"))); 40 | assertEquals(10, new LWM2MID("korte").compareTo(new LWM2MID("alma"))); 41 | } 42 | 43 | @Test 44 | public void testCompareToNull() throws Exception { 45 | assertThrows(NullPointerException.class, () -> 46 | new LWM2MID(null).compareTo(null) 47 | ); 48 | } 49 | 50 | @Test 51 | public void testHashCode() throws Exception { 52 | assertEquals(Objects.hashCode(-1), new LWM2MID(null).hashCode()); 53 | assertEquals(Objects.hashCode(42), new LWM2MID("42").hashCode()); 54 | assertEquals(Objects.hashCode(new LWM2MID("alma").intValue()), new LWM2MID("alma").hashCode()); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /lwm2m/src/test/java/com/mbed/lwm2m/json/JsonResourceArrayTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap) 3 | * Copyright (C) 2011-2021 ARM Limited. All rights reserved. 4 | * SPDX-License-Identifier: Apache-2.0 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.mbed.lwm2m.json; 18 | 19 | import static org.hamcrest.MatcherAssert.*; 20 | import static org.hamcrest.Matchers.*; 21 | import static org.junit.jupiter.api.Assertions.*; 22 | import org.junit.jupiter.api.Test; 23 | 24 | public class JsonResourceArrayTest { 25 | 26 | @Test 27 | public void testBaseTime() { 28 | JsonResourceArray array = new JsonResourceArray(); 29 | int bt = (int) (System.currentTimeMillis() / 1000); 30 | 31 | assertNull(array.getBaseTime()); 32 | assertEquals("", array.toString()); 33 | array.setBaseTime(bt); 34 | assertEquals(bt, array.getBaseTime().intValue()); 35 | 36 | System.out.println(array); 37 | assertTrue(array.toString().indexOf(String.valueOf(bt)) > 0); 38 | } 39 | 40 | @Test 41 | public void testBaseName() throws Exception { 42 | JsonResourceArray array = new JsonResourceArray(); 43 | assertNull(array.getBaseName()); 44 | assertEquals("", array.toString()); 45 | array.setBaseName("/"); 46 | assertEquals("/", array.getBaseName()); 47 | 48 | System.out.println(array); 49 | assertThat(array.toString(), containsString("\"/\"")); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /lwm2m/src/test/resources/com/mbed/lwm2m/json/custom-object.json: -------------------------------------------------------------------------------- 1 | {"e":[ 2 | {"n":"temp/0","v":"19.5"}, 3 | {"n":"temp/1","v":"19.7"}, 4 | {"n":"temp/max","v":"30.0"}, 5 | {"n":"hum/0","v":"34"}, 6 | {"n":"hum/1","v":"45"}, 7 | {"n":"hum/max","v":"100"}] 8 | } -------------------------------------------------------------------------------- /lwm2m/src/test/resources/com/mbed/lwm2m/json/device-object.json: -------------------------------------------------------------------------------- 1 | {"e":[ 2 | {"n":"0","sv":"Open Mobile Alliance"}, 3 | {"n":"1","sv":"Lightweight M2M Client"}, 4 | {"n":"2","sv":"345000123"}, 5 | {"n":"3","sv":"1.0"}, 6 | {"n":"6/0","v":"1"}, 7 | {"n":"6/1","v":"5"}, 8 | {"n":"7/0","v":"3800"}, 9 | {"n":"7/1","v":"5000"}, 10 | {"n":"8/0","v":"125"}, 11 | {"n":"8/1","v":"900"}, 12 | {"n":"9","v":"100"}, 13 | {"n":"10","v":"15"}, 14 | {"n":"11/0","v":"0"}, 15 | {"n":"13","v":"1367491215"}, 16 | {"n":"14","sv":"+02:00"}, 17 | {"n":"15","sv":"U"}] 18 | } -------------------------------------------------------------------------------- /lwm2m/src/test/resources/com/mbed/lwm2m/json/notification.json: -------------------------------------------------------------------------------- 1 | {"e":[ 2 | {"n":"1/2","v":"22.4","t":"-5"}, 3 | {"n":"1/2","v":"22.9","t":"-30"}, 4 | {"n":"1/2","v":"24.1","t":"-50"}], 5 | "bt":"25462634" 6 | } -------------------------------------------------------------------------------- /lwm2m/src/test/resources/com/mbed/lwm2m/model/lwm2m-test-objects.json: -------------------------------------------------------------------------------- 1 | { 2 | "lwm2m-objects": [ 3 | { 4 | "object-id": "test", 5 | "object-name": "LWM2M Test Object", 6 | "description": "", 7 | "instances": MULTIPLE, 8 | "resources": [ 9 | { 10 | "resource-id": 0, 11 | "resource-name": "test0", 12 | "operations": "R", 13 | "instances": SINGLE, 14 | "type": STRING, 15 | "range": "{0,255}", 16 | "description": "" 17 | }, 18 | { 19 | "resource-id": 1, 20 | "resource-name": "test1", 21 | "operations": "R", 22 | "instances": SINGLE, 23 | "type": BOOLEAN, 24 | "range": "", 25 | "description": "" 26 | } 27 | ] 28 | }, 29 | { 30 | "object-id": "try", 31 | "object-name": "LWM2M Try Object", 32 | "description": "", 33 | "instances": SINGLE, 34 | "resources": [ 35 | { 36 | "resource-id": 0, 37 | "resource-name": "try", 38 | "operations": "R", 39 | "instances": SINGLE, 40 | "type": STRING, 41 | "range": "", 42 | "description": "" 43 | } 44 | ] 45 | } 46 | ] } -------------------------------------------------------------------------------- /lwm2m/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | %d{HH:mm:ss} %.-1level %m%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | include(":coap-core") 2 | include(":coap-tcp") 3 | include(":coap-mbedtls") 4 | include(":lwm2m") 5 | include(":coap-cli") 6 | include(":coap-metrics") 7 | include(":coap-netty") 8 | --------------------------------------------------------------------------------