Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use builder pattern for CoapRequest and CoapResponse #68

Merged
merged 2 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions coap-cli/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.0")
testImplementation("org.awaitility:awaitility:4.2.0")
testImplementation(testFixtures(project(":coap-core")))
}

tasks {
Expand Down
11 changes: 5 additions & 6 deletions coap-cli/src/main/java/com/mbed/coap/cli/DeviceEmulator.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/
package com.mbed.coap.cli;

import static java.util.concurrent.CompletableFuture.completedFuture;
import com.mbed.coap.client.RegistrationManager;
import com.mbed.coap.packet.CoapRequest;
import com.mbed.coap.packet.CoapResponse;
Expand Down Expand Up @@ -77,20 +76,20 @@ public Integer call() throws Exception {
}

protected Service<CoapRequest, CoapResponse> createRouting() {
Service<CoapRequest, CoapResponse> timeResource = __ -> completedFuture(CoapResponse.ok(Instant.now().toString()));
Service<CoapRequest, CoapResponse> timeResource = __ -> CoapResponse.ok(Instant.now().toString()).toFuture();

scheduledExecutor.scheduleAtFixedRate(() ->
obsManager.sendObservation("/time", timeResource),
30, 30, TimeUnit.SECONDS
);

return RouterService.builder()
.get("/3/0/1", __ -> completedFuture(CoapResponse.ok("Acme")))
.get("/3/0/2", __ -> completedFuture(CoapResponse.ok("Emulator")))
.get("/3/0/3", __ -> completedFuture(CoapResponse.ok("0.0.1")))
.get("/3/0/1", __ -> CoapResponse.ok("Acme").toFuture())
.get("/3/0/2", __ -> CoapResponse.ok("Emulator").toFuture())
.get("/3/0/3", __ -> CoapResponse.ok("0.0.1").toFuture())
.get("/delayed-10s", __ -> {
CompletableFuture<CoapResponse> promise = new CompletableFuture<>();
scheduledExecutor.schedule(() -> promise.complete(CoapResponse.ok("OK")), 10, TimeUnit.SECONDS);
scheduledExecutor.schedule(() -> promise.complete(CoapResponse.ok("OK").build()), 10, TimeUnit.SECONDS);
return promise;
})
.get("/time", obsManager.then(timeResource))
Expand Down
10 changes: 6 additions & 4 deletions coap-cli/src/main/java/com/mbed/coap/cli/SendCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.mbed.coap.cli;

import static com.mbed.coap.cli.TransportOptions.addressFromUri;
import static com.mbed.coap.packet.CoapRequest.request;
import com.mbed.coap.CoapConstants;
import com.mbed.coap.client.CoapClient;
import com.mbed.coap.packet.BlockSize;
Expand Down Expand Up @@ -82,15 +83,16 @@ public Integer call() throws Exception {
Thread.sleep(200);

String uriPath = uri.getPath().isEmpty() ? CoapConstants.WELL_KNOWN_CORE : uri.getPath();
request = CoapRequest.of(null, method, uriPath)
request = request(method, uriPath)
.query(uri.getQuery() == null ? "" : uri.getQuery())
.blockSize(blockSize)
.payload(hexPayload ? Opaque.decodeHex(payload) : Opaque.of(payload))
.contentFormat(contentFormat)
.accept(accept)
.options(o -> o
.contentFormat(contentFormat)
.proxyUri(proxyUri)
.accept(accept)
);
)
.build();
CoapResponse resp = cli.sendSync(request);

if (resp.getPayload().nonEmpty()) {
Expand Down
19 changes: 10 additions & 9 deletions coap-cli/src/test/java/com/mbed/coap/cli/CoapCliTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@
package com.mbed.coap.cli;

import static com.mbed.coap.packet.BlockSize.S_16;
import static com.mbed.coap.packet.CoapRequest.get;
import static com.mbed.coap.packet.CoapResponse.coapResponse;
import static com.mbed.coap.packet.CoapResponse.ok;
import static com.mbed.coap.transport.udp.DatagramSocketTransport.udp;
import static com.mbed.coap.utils.Assertions.assertEquals;
import static java.lang.String.format;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.mbed.coap.packet.CoapRequest;
import com.mbed.coap.packet.CoapResponse;
import com.mbed.coap.packet.Code;
import com.mbed.coap.packet.MediaTypes;
import com.mbed.coap.packet.Opaque;
Expand Down Expand Up @@ -54,10 +55,10 @@ void beforeAll() throws IOException {
.route(RouterService.builder()
.post("/rd", req -> {
String epName = req.options().getUriQueryMap().get("ep");
return completedFuture(CoapResponse.of(Code.C201_CREATED, Opaque.EMPTY, o -> o.locationPath("/rd/" + epName)));
return coapResponse(Code.C201_CREATED).locationPath("/rd/" + epName).toFuture();
})
.get("/test", __ -> completedFuture(ok("Dziala!")))
.post("/test", req -> completedFuture(ok("Received " + req.getPayload().size())))
.get("/test", __ -> ok("Dziala!").toFuture())
.post("/test", req -> ok("Received " + req.getPayload().size()).toFuture())

)
.build()
Expand Down Expand Up @@ -92,7 +93,7 @@ void simplestRequest() {
// then
assertEquals(0, exitCode);
assertEquals("\nDziala!\n", sw.toString().replace("\r", ""));
assertEquals(CoapRequest.get("/test"), sendCommand.request);
assertEquals(get("/test"), sendCommand.request);
}

@Test
Expand All @@ -108,10 +109,10 @@ void requestWithAllCoapParameters() {
assertEquals(0, exitCode);
assertEquals("\nReceived 29\n", sw.toString().replace("\r", ""));

CoapRequest expected = CoapRequest.post("/test")
CoapRequest.Builder expected = CoapRequest.post("/test")
.options(it -> it
.query("par1", "val1")
.block1Req(1, S_16, false)
.block1Req(0, S_16, true)
.proxyUri("http://another-uri")
.requestTag(sendCommand.request.options().getRequestTag()) // it's random
)
Expand All @@ -128,7 +129,7 @@ public void requestWithHexPayload() {
assertEquals(0, exitCode);
assertEquals("\nReceived 27\n", sw.toString().replace("\r", ""));

CoapRequest expected = CoapRequest.post("/test")
CoapRequest.Builder expected = CoapRequest.post("/test")
.payload(Opaque.decodeHex("a16e626573745f6775697461726973746a476172795f4d6f6f7265"), MediaTypes.CT_APPLICATION_CBOR)
.accept(MediaTypes.CT_APPLICATION_JSON);
assertEquals(expected, sendCommand.request);
Expand Down
8 changes: 3 additions & 5 deletions coap-core/src/jmh/java/microbenchmark/ServerBenchmark.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
package microbenchmark;

import static java.util.concurrent.CompletableFuture.completedFuture;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.mbed.coap.exception.CoapException;
Expand Down Expand Up @@ -66,10 +65,9 @@ public void setup() throws CoapException, IOException {
server = CoapServer.builder()
.transport(mockTransport)
.route(RouterService.builder()
.get("/path1/sub2/sub3", __ -> completedFuture(
CoapResponse.ok("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890")
.maxAge(requestCounter++)
))
.get("/path1/sub2/sub3", __ ->
CoapResponse.ok("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890").maxAge((int) requestCounter++).toFuture()
)
)
.build();
server.start();
Expand Down
10 changes: 9 additions & 1 deletion coap-core/src/main/java/com/mbed/coap/client/CoapClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,21 @@ public static CoapClient create(InetSocketAddress target, CoapServer server, Fun
}

public CompletableFuture<CoapResponse> send(CoapRequest request) {
return clientService.apply(request.address(destination));
return clientService.apply(request.withAddress(destination));
}

public CompletableFuture<CoapResponse> send(CoapRequest.Builder request) {
return send(request.build());
}

public CoapResponse sendSync(CoapRequest request) throws CoapException {
return await(send(request));
}

public CoapResponse sendSync(CoapRequest.Builder request) throws CoapException {
return sendSync(request.build());
}

private static CoapResponse await(CompletableFuture<CoapResponse> future) throws CoapException {
try {
return future.get(5, TimeUnit.MINUTES);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap)
/*
* Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap)
* Copyright (C) 2011-2018 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -16,6 +16,7 @@
*/
package com.mbed.coap.exception;

import static com.mbed.coap.packet.CoapResponse.coapResponse;
import com.mbed.coap.packet.CoapResponse;
import com.mbed.coap.packet.Code;

Expand Down Expand Up @@ -46,7 +47,7 @@ public Code getCode() {
return code;
}

public CoapResponse toResponse() {
return CoapResponse.of(code, getMessage());
public CoapResponse.Builder toResponse() {
return coapResponse(code).payload(getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (C) 2022 java-coap contributors (https://github.com/open-coap/java-coap)
/*
* Copyright (C) 2022-2023 java-coap contributors (https://github.com/open-coap/java-coap)
* Copyright (C) 2011-2018 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -38,14 +38,15 @@ public CoapRequestEntityTooLarge(BlockOption blockOptionHint, String message) {
}

@Override
public CoapResponse toResponse() {
CoapResponse resp = super.toResponse();
if (maxSize > 0) {
resp.options().setSize1(maxSize);
}
if (blockOptionHint != null) {
resp.options().setBlock1Req(blockOptionHint);
}
return resp;
public CoapResponse.Builder toResponse() {
return super.toResponse()
.options(o -> {
if (maxSize > 0) {
o.size1(maxSize);
}
if (blockOptionHint != null) {
o.block1Req(blockOptionHint);
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static CoapOptionsBuilder from(HeaderOptions options) {
return new CoapOptionsBuilder(options.duplicate());
}

CoapOptionsBuilder(HeaderOptions options) {
private CoapOptionsBuilder(HeaderOptions options) {
this.options = options;
}

Expand Down
Loading