use of org.eclipse.californium.core.coap.CoAP.Code in project hono by eclipse.
the class CoapTestBase method testUploadMessageFailsForDisabledDevice.
/**
* Verifies that the CoAP adapter rejects messages from a disabled device.
*
* @param ctx The test context
*/
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledDevice(final VertxTestContext ctx) {
// GIVEN a disabled device
final Tenant tenant = new Tenant();
final Device deviceData = new Device();
deviceData.setEnabled(false);
helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, deviceData, SECRET).compose(ok -> {
// WHEN the device tries to upload a message
final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
final Promise<OptionSet> result = Promise.promise();
// THEN a NOT_FOUND response code is returned
client.advanced(getHandler(result, ResponseCode.NOT_FOUND), createCoapsRequest(Code.POST, getPostResource(), 0));
return result.future();
}).onComplete(ctx.succeedingThenComplete());
}
use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.
the class HonoClient method main.
/**
* Main entry point.
*
* @param args the arguments
* @throws IOException
* @throws ConnectorException
*/
public static void main(String[] args) throws IOException, ConnectorException {
// hono sandbox
TcpConfig.register();
final Config clientConfig = new Config();
clientConfig.setDefaultPskCredentials("sensor1@DEFAULT_TENANT", "hono-secret");
clientConfig.defaultUri = "coaps://" + DEFAULT_HONO + "/telemetry";
clientConfig.configurationHeader = CONFIG_HEADER;
clientConfig.customConfigurationDefaultsProvider = DEFAULTS;
clientConfig.configurationFile = CONFIG_FILE;
ClientInitializer.init(args, clientConfig);
if (clientConfig.helpRequested) {
System.exit(0);
}
Random rand = new Random();
CorrelationId id = new CorrelationId(rand);
if (clientConfig.identity == null) {
System.out.println("> " + clientConfig.uri);
} else {
System.out.println("> " + clientConfig.identity + ", " + clientConfig.uri);
}
CoapClient client = new CoapClient(clientConfig.uri);
CoAP.Code code = clientConfig.method == null ? Code.POST : clientConfig.method;
final Request request = new Request(code);
if (clientConfig.messageType != null) {
request.setConfirmable(clientConfig.messageType.con);
}
if (clientConfig.contentType == null) {
clientConfig.contentType = new ContentType();
clientConfig.contentType.contentType = MediaTypeRegistry.TEXT_PLAIN;
}
if (clientConfig.payload == null && request.isIntendedPayload()) {
applyPayload(clientConfig.mode, request);
clientConfig.payload = new Payload();
clientConfig.payload.text = request.getPayloadString();
clientConfig.payloadFormat = true;
clientConfig.contentType.contentType = request.getOptions().getContentFormat();
}
request.getOptions().setAccept(clientConfig.contentType.contentType);
request.getOptions().setContentFormat(clientConfig.contentType.contentType);
request.setPayload(formatPayload(clientConfig, rand.nextInt(100), id));
request.setURI(clientConfig.uri);
request.addMessageObserver(new EndpointContextTracer() {
@Override
public void onReadyToSend() {
System.out.println(Utils.prettyPrint(request));
System.out.println();
}
@Override
public void onAcknowledgement() {
System.out.println(">>> ACK <<<");
}
@Override
public void onDtlsRetransmission(int flight) {
System.out.println(">>> DTLS retransmission, flight " + flight);
}
@Override
protected void onContextChanged(EndpointContext endpointContext) {
System.out.println(Utils.prettyPrint(endpointContext));
}
});
long start = System.nanoTime();
List<Long> rtt = new ArrayList<Long>(clientConfig.requests);
CoapResponse coapResponse = exchange(clientConfig, client, request, true);
if (coapResponse != null && getCommand(coapResponse) == null) {
rtt.add(coapResponse.advanced().getApplicationRttNanos());
Request followUpRequests = null;
for (int index = 1; index < clientConfig.requests; ++index) {
followUpRequests = new Request(code);
followUpRequests.getOptions().setAccept(clientConfig.contentType.contentType);
followUpRequests.getOptions().setContentFormat(clientConfig.contentType.contentType);
id.next();
followUpRequests.setPayload(formatPayload(clientConfig, rand.nextInt(100), id));
followUpRequests.setURI(clientConfig.uri);
coapResponse = exchange(clientConfig, client, followUpRequests, true);
if (coapResponse == null) {
System.out.format("Stale at %d.%n", index);
break;
} else if (!coapResponse.isSuccess()) {
if (coapResponse.getCode() == ResponseCode.SERVICE_UNAVAILABLE) {
long age = coapResponse.advanced().getOptions().getMaxAge();
long delay = TimeUnit.SECONDS.toMillis(age < 2 ? 2 : age);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
}
rtt.add(coapResponse.advanced().getApplicationRttNanos());
}
start = System.nanoTime() - start;
if (followUpRequests != null && coapResponse != null) {
System.out.println();
System.out.println(Utils.prettyPrint(followUpRequests));
System.out.println();
System.out.println(Utils.prettyPrint(coapResponse));
}
int count = 0;
int overtimeCount = 0;
long average = 0;
long overtime = 0;
for (int index = 0; index < rtt.size(); ++index) {
Long time = rtt.get(index);
if (time != null) {
++count;
long millis = TimeUnit.NANOSECONDS.toMillis(time);
System.out.format("RTT[%d] : %d ms %n", index, millis);
if (500 < millis) {
++overtimeCount;
overtime += millis;
}
average += millis;
}
}
System.out.format("Overall time: %d [ms] %n", TimeUnit.NANOSECONDS.toMillis(start));
if (0 < count) {
System.out.format("Average time: %d [ms] %n", average / count);
if (0 < overtimeCount) {
System.out.format("Overtime : %d, %d [ms], avg %d [ms] %n", overtimeCount, overtime, overtime / overtimeCount);
}
}
}
}
use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.
the class OptionJuggleTest method testRealCodeRequest.
@Test
public void testRealCodeRequest() {
Request request = new Request(Code.POST);
request.setToken(token);
request.setMID(mid);
request.setType(type);
request.setPayload(payload);
request.setSourceContext(sourceContext);
request.setDestinationContext(destinationContext);
OptionSet options = new OptionSet();
options.setAccept(accept);
request.setOptions(options);
Code realCode = Code.PUT;
Request realed = OptionJuggle.setRealCodeRequest(request, realCode);
OptionSet realOptions = realed.getOptions();
assertEquals(realCode, realed.getCode());
assertEquals(token, realed.getToken());
assertEquals(mid, realed.getMID());
assertEquals(type, realed.getType());
assertEquals(payload, realed.getPayload());
assertEquals(sourceContext, realed.getSourceContext());
assertEquals(destinationContext, realed.getDestinationContext());
assertEquals(accept, realOptions.getAccept());
}
use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.
the class Utils method prettyPrint.
/**
* Formats a {@link Request} into a readable String representation.
*
* @param request the Request
* @return the pretty print
*/
public static String prettyPrint(Request request) {
String nl = StringUtil.lineSeparator();
StringBuilder sb = new StringBuilder();
sb.append("==[ CoAP Request ]=============================================").append(nl);
sb.append(String.format("MID : %d%n", request.getMID()));
sb.append(String.format("Token : %s%n", request.getTokenString()));
sb.append(String.format("Type : %s%n", request.getType()));
Code code = request.getCode();
if (code == null) {
sb.append("Method : 0.00 - PING").append(nl);
} else {
sb.append(String.format("Method : %s - %s%n", code.text, code.name()));
}
if (request.getOffloadMode() != null) {
sb.append("(offloaded)").append(nl);
} else {
sb.append(String.format("Options: %s%n", request.getOptions()));
sb.append(String.format("Payload: %d Bytes%n", request.getPayloadSize()));
if (request.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(request.getOptions().getContentFormat())) {
sb.append("---------------------------------------------------------------").append(nl);
sb.append(request.getPayloadString());
sb.append(nl);
}
}
sb.append("===============================================================");
return sb.toString();
}
use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.
the class CoapTest method testCode.
@Test
public void testCode() {
for (Code code : Code.values()) {
assertEquals(code, Code.valueOf(code.value));
assertTrue(MessageFormat.REQUEST_CODE_LOWER_BOUND <= code.value);
assertTrue(code.value <= MessageFormat.REQUEST_CODE_UPPER_BOUND);
}
}
Aggregations