org.eclipse.californium.core.coap.Request Java Examples

The following examples show how to use org.eclipse.californium.core.coap.Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Formats a {@link Request} into a readable String representation. 
 * 
 * @param r the Request
 * @return the pretty print
 */
public static String prettyPrint(Request r) {

        StringBuilder sb = new StringBuilder();
        
        sb.append("##[ CoAP Request ]##############################################\n");
        sb.append(String.format("MID    : %d\n", r.getMID()));
        sb.append(String.format("Token  : %s\n", r.getTokenString()));
        sb.append(String.format("Type   : %s\n", r.getType().toString()));
        sb.append(String.format("Method : %s\n", r.getCode().toString()));
        sb.append(String.format("Options: %s\n", r.getOptions().toString()));
        sb.append(String.format("Payload: %d Bytes\n", r.getPayloadSize()));
        if (r.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(r.getOptions().getContentFormat())) {
        	sb.append("---------------------------------------------------------------");
        	sb.append(r.getPayloadString());
        }
        sb.append("############################################################");

        return sb.toString();
}
 
Example #2
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Formats a {@link Request} into a readable String representation. 
 * 
 * @param r the Request
 * @return the pretty print
 */
public static String prettyPrint(Request r) {

        StringBuilder sb = new StringBuilder();
        
        sb.append("##[ CoAP Request ]##############################################\n");
        sb.append(String.format("MID    : %d\n", r.getMID()));
        sb.append(String.format("Token  : %s\n", r.getTokenString()));
        sb.append(String.format("Type   : %s\n", r.getType().toString()));
        sb.append(String.format("Method : %s\n", r.getCode().toString()));
        sb.append(String.format("Options: %s\n", r.getOptions().toString()));
        sb.append(String.format("Payload: %d Bytes\n", r.getPayloadSize()));
        if (r.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(r.getOptions().getContentFormat())) {
        	sb.append("---------------------------------------------------------------");
        	sb.append(r.getPayloadString());
        }
        sb.append("############################################################");

        return sb.toString();
}
 
Example #3
Source File: CoapObserveRelation.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Refreshes the Observe relationship with a new GET request with same token
 * and options. The method also resets the notification orderer, since the
 * server might have rebooted and started the observe sequence number from
 * the beginning.
 */
public void reregister() {
	if (!request.isCanceled()) {
		Request refresh = Request.newGet();
		refresh.setDestination(request.getDestination());
		refresh.setDestinationPort(request.getDestinationPort());
		// use same Token
		refresh.setToken(request.getToken());
		// copy options, but set Observe to zero
		refresh.setOptions(request.getOptions());
		refresh.setObserve();
		
		// use same message observers
		for (MessageObserver mo : request.getMessageObservers()) {
			refresh.addMessageObserver(mo);
		}
		
		endpoint.sendRequest(refresh);
		
		// update request in observe handle for correct cancellation
		this.request = refresh;
		// reset orderer to accept any sequence number since server might have rebooted
		this.orderer = new ObserveNotificationOrderer();
	}
}
 
Example #4
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a number of messages uploaded to Hono's CoAP adapter
 * can be successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesAnonymously(final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapClient();
    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapRequest(Code.PUT, getPutResource(tenantId, deviceId), 0)),
            count -> {
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapRequest(Code.PUT, getPutResource(tenantId, deviceId), count);
                client.advanced(getHandler(result), request);
                return result.future();
            });
}
 
Example #5
Source File: CoapObserveRelation.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Refreshes the Observe relationship with a new GET request with same token
 * and options. The method also resets the notification orderer, since the
 * server might have rebooted and started the observe sequence number from
 * the beginning.
 */
public void reregister() {
	if (!request.isCanceled()) {
		Request refresh = Request.newGet();
		refresh.setDestination(request.getDestination());
		refresh.setDestinationPort(request.getDestinationPort());
		// use same Token
		refresh.setToken(request.getToken());
		// copy options, but set Observe to zero
		refresh.setOptions(request.getOptions());
		refresh.setObserve();
		
		// use same message observers
		for (MessageObserver mo : request.getMessageObservers()) {
			refresh.addMessageObserver(mo);
		}
		
		endpoint.sendRequest(refresh);
		
		// update request in observe handle for correct cancellation
		this.request = refresh;
		// reset orderer to accept any sequence number since server might have rebooted
		this.orderer = new ObserveNotificationOrderer();
	}
}
 
Example #6
Source File: TracingSupportingHonoResourceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the resource uses the SpanContext extracted from a CoAP request
 * as the parent of the newly created Span.
 */
@Test
public void testHandleRequestExtractsParentTraceContext() {

    final SpanContext extractedContext = mock(SpanContext.class);
    when(tracer.extract(eq(Format.Builtin.BINARY), any(Binary.class))).thenReturn(extractedContext);

    final Request request = new Request(Code.POST);
    request.getOptions().addOption(new Option(CoapOptionInjectExtractAdapter.OPTION_TRACE_CONTEXT));
    final Exchange exchange = new Exchange(request, Origin.REMOTE, mock(Executor.class));
    resource.handleRequest(exchange);

    verify(tracer).buildSpan(eq(Code.POST.toString()));
    verify(spanBuilder).withTag(eq(Tags.SPAN_KIND.getKey()), eq(Tags.SPAN_KIND_SERVER.toString()));
    verify(spanBuilder).addReference(eq(References.CHILD_OF), eq(extractedContext));
}
 
Example #7
Source File: ReliabilityLayer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Schedules a retransmission for confirmable messages. 
 */
@Override
public void sendRequest(final Exchange exchange, final Request request) {

	LOGGER.finer("Send request, failed transmissions: "+exchange.getFailedTransmissionCount());
	
	if (request.getType() == null)
		request.setType(Type.CON);
	
	if (request.getType() == Type.CON) {
		prepareRetransmission(exchange, new RetransmissionTask(exchange, request) {
			public void retransmit() {
				sendRequest(exchange, request);
			}
		});
	}
	super.sendRequest(exchange, request);
}
 
Example #8
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Triggers the establishment of a downstream sender
 * for a tenant so that subsequent messages will be
 * more likely to be forwarded.
 *
 * @param client The CoAP client to use for sending the request.
 * @param request The request to send.
 * @return A succeeded future.
 */
protected final Future<Void> warmUp(final CoapClient client, final Request request) {

    logger.debug("sending request to trigger CoAP adapter's downstream message sender");
    final Promise<Void> result = Promise.promise();
    client.advanced(new CoapHandler() {

        @Override
        public void onLoad(final CoapResponse response) {
            waitForWarmUp();
        }

        @Override
        public void onError() {
            waitForWarmUp();
        }

        private void waitForWarmUp() {
            VERTX.setTimer(1000, tid -> result.complete());
        }
    }, request);
    return result.future();
}
 
Example #9
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a number of messages uploaded to Hono's CoAP adapter using TLS_PSK based authentication can be
 * successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesUsingPsk(final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);

    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapsRequest(Code.POST, getPostResource(), 0)),
            count -> {
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapsRequest(Code.POST, getPostResource(), count);
                client.advanced(getHandler(result), request);
                return result.future();
            });
}
 
Example #10
Source File: TelemetryCoapIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the upload of a telemetry message containing a payload that
 * exceeds the CoAP adapter's configured max payload size fails with a 4.13
 * response code.
 *
 * @param ctx The test context.
 * @throws IOException if the CoAP request cannot be sent to the adapter.
 * @throws ConnectorException  if the CoAP request cannot be sent to the adapter.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadFailsForLargePayload(final VertxTestContext ctx) throws ConnectorException, IOException {

    final Tenant tenant = new Tenant();

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .compose(ok -> {
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Request request = createCoapsRequest(Code.POST, Type.CON, getPostResource(), IntegrationTestSupport.getPayload(4096));
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.REQUEST_ENTITY_TOO_LARGE), request);
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #11
Source File: BlockwiseLayer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Request getNextRequestBlock(Request request, BlockwiseStatus status) {
	int num = status.getCurrentNum();
	int szx = status.getCurrentSzx();
	Request block = new Request(request.getCode());
	// do not enforce CON, since NON could make sense over SMS or similar transports
	block.setType(request.getType());
	block.setDestination(request.getDestination());
	block.setDestinationPort(request.getDestinationPort());
	// copy options
	block.setOptions(new OptionSet(request.getOptions()));
	
	int currentSize = 1 << (4 + szx);
	int from = num * currentSize;
	int to = Math.min((num + 1) * currentSize, request.getPayloadSize());
	int length = to - from;
	byte[] blockPayload = new byte[length];
	System.arraycopy(request.getPayload(), from, blockPayload, 0, length);
	block.setPayload(blockPayload);
	
	boolean m = (to < request.getPayloadSize());
	block.getOptions().setBlock1(szx, m, num);
	
	status.setComplete(!m);
	return block;
}
 
Example #12
Source File: ReliabilityLayer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Schedules a retransmission for confirmable messages. 
 */
@Override
public void sendRequest(final Exchange exchange, final Request request) {

	LOGGER.finer("Send request, failed transmissions: "+exchange.getFailedTransmissionCount());
	
	if (request.getType() == null)
		request.setType(Type.CON);
	
	if (request.getType() == Type.CON) {
		prepareRetransmission(exchange, new RetransmissionTask(exchange, request) {
			public void retransmit() {
				sendRequest(exchange, request);
			}
		});
	}
	super.sendRequest(exchange, request);
}
 
Example #13
Source File: CoapClient.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns the effective endpoint that the specified request is supposed to
 * be sent over. If an endpoint has explicitly been set to this CoapClient,
 * this endpoint will be used. If no endpoint has been set, the client will
 * effectively use a default endpoint of the {@link EndpointManager}.
 * 
 * @param request the request to be sent
 * @return the effective endpoint that the request is going o be sent over.
 */
protected Endpoint getEffectiveEndpoint(Request request) {
	Endpoint myEndpoint = getEndpoint();
	
	// custom endpoint
	if (myEndpoint != null) return myEndpoint;
	
	// default endpoints
	if (CoAP.COAP_SECURE_URI_SCHEME.equals(request.getScheme())) {
		// this is the case when secure coap is supposed to be used
		return EndpointManager.getEndpointManager().getDefaultSecureEndpoint();
	} else {
		// this is the normal case
		return EndpointManager.getEndpointManager().getDefaultEndpoint();
	}
}
 
Example #14
Source File: Matcher.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void sendRequest(Exchange exchange, Request request) {
	
	// ensure MID is set
	if (request.getMID() == Message.NONE) {
		request.setMID(currendMID.getAndIncrement()%(1<<16));
	}
	// request MID is from the local namespace -- use blank address
	KeyMID idByMID = new KeyMID(request.getMID(), null, 0);

	// ensure Token is set
	KeyToken idByToken;
	if (request.getToken() == null) {
		byte[] token;
		do {
			token = createNewToken();
			idByToken = new KeyToken(token);
		} while (exchangesByToken.get(idByToken) != null);
		
		request.setToken(token);
		
	} else {
		idByToken = new KeyToken(request.getToken());
		// ongoing requests may reuse token
		if (!(exchange.getFailedTransmissionCount()>0 || request.getOptions().hasBlock1() || request.getOptions().hasBlock2() || request.getOptions().hasObserve()) && exchangesByToken.get(idByToken) != null) {
			LOGGER.warning("Manual token overrides existing open request: "+idByToken);
		}
	}
	
	exchange.setObserver(exchangeObserver);
	
	if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Stored open request by "+idByMID+", "+idByToken);
	
	exchangesByMID.put(idByMID, exchange);
	exchangesByToken.put(idByToken, exchange);
}
 
Example #15
Source File: CoapTransportResource.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public static Optional<Integer> getRequestId(Request request) {
  List<String> uriPath = request.getOptions().getUriPath();
  try {
    if (uriPath.size() >= REQUEST_ID_POSITION) {
      return Optional.of(Integer.valueOf(uriPath.get(REQUEST_ID_POSITION - 1)));
    }
  } catch (RuntimeException e) {
    log.warn("Failed to decode feature type: {}", uriPath);
  }
  return Optional.empty();
}
 
Example #16
Source File: JsonCoapAdaptor.java    From Groza with Apache License 2.0 5 votes vote down vote up
private AttributesUpdateRequest convertToUpdateAttributesRequest(SessionContext ctx, Request inbound) throws AdaptorException {
    String payload = validatePayload(ctx, inbound);
    try {
        return JsonConverter.convertToAttributes(new JsonParser().parse(payload));
    } catch (IllegalStateException | JsonSyntaxException ex) {
        throw new AdaptorException(ex);
    }
}
 
Example #17
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the resources registered with the adapter are always
 * executed on the adapter's vert.x context.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testResourcesAreRunOnVertxContext(final VertxTestContext ctx) {

    // GIVEN an adapter
    final Context context = vertx.getOrCreateContext();
    final CoapServer server = getCoapServer(false);
    // with a resource
    final Promise<Void> resourceInvocation = Promise.promise();
    final Resource resource = new CoapResource("test") {

        @Override
        public void handleGET(final CoapExchange exchange) {
            ctx.verify(() -> assertThat(Vertx.currentContext()).isEqualTo(context));
            resourceInvocation.complete();
        }
    };

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, s -> {});
    adapter.setResources(Collections.singleton(resource));

    final Promise<Void> startupTracker = Promise.promise();
    adapter.init(vertx, context);
    adapter.start(startupTracker);

    startupTracker.future()
        .compose(ok -> {
            // WHEN the resource receives a GET request
            final Request request = new Request(Code.GET);
            final Exchange getExchange = new Exchange(request, Origin.REMOTE, mock(Executor.class));
            final ArgumentCaptor<VertxCoapResource> resourceCaptor = ArgumentCaptor.forClass(VertxCoapResource.class);
            verify(server).add(resourceCaptor.capture());
            resourceCaptor.getValue().handleRequest(getExchange);
            // THEN the resource's handler has been run on the adapter's vert.x event loop
            return resourceInvocation.future();
        })
        .onComplete(ctx.completing());
}
 
Example #18
Source File: CoapClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private CoapObserveRelation observe(Request request, CoapHandler handler) {
	Endpoint outEndpoint = getEffectiveEndpoint(request);
	CoapObserveRelation relation = new CoapObserveRelation(request, outEndpoint);
	request.addMessageObserver(new ObserveMessageObserverImpl(handler, relation));
	send(request, outEndpoint);
	return relation;
}
 
Example #19
Source File: CoapStack.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void receiveRequest(Exchange exchange, Request request) {
	// if there is no BlockwiseLayer we still have to set it
	if (exchange.getRequest() == null)
		exchange.setRequest(request);
	if (deliverer != null) {
		deliverer.deliverRequest(exchange);
	} else {
		LOGGER.severe("Top of CoAP stack has no deliverer to deliver request");
	}
}
 
Example #20
Source File: JsonCoapAdaptor.java    From Groza with Apache License 2.0 5 votes vote down vote up
private TelemetryUploadRequest convertToTelemetryUploadRequest(SessionContext ctx, Request inbound) throws AdaptorException {
    String payload = validatePayload(ctx, inbound);
    try {
        return JsonConverter.convertToTelemetry(new JsonParser().parse(payload));
    } catch (IllegalStateException | JsonSyntaxException ex) {
        throw new AdaptorException(ex);
    }
}
 
Example #21
Source File: CoapEndpoint.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void sendRequest(final Request request) {
	// always use endpoint executor
	runInProtocolStage(new Runnable() {
		public void run() {
			coapstack.sendRequest(request);
		}
	});
}
 
Example #22
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a CoAP request using the <em>coaps</em> scheme.
 *
 * @param endpointConfig The endpoint configuration.
 * @param requestDeviceId The identifier of the device to publish data for.
 * @param msgNo The message number.
 * @return The request to send.
 */
protected Request createCoapsRequest(
        final CoapCommandEndpointConfiguration endpointConfig,
        final String requestDeviceId,
        final int msgNo) {

    if (endpointConfig.isSubscribeAsGatewayForSingleDevice()) {
        return createCoapsRequest(Code.PUT, getMessageType(), getPutResource(tenantId, requestDeviceId), msgNo);
    }
    return createCoapsRequest(Code.POST, getMessageType(), getPostResource(), msgNo);
}
 
Example #23
Source File: CoapClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private CoapObserveRelation observe(Request request, CoapHandler handler) {
	Endpoint outEndpoint = getEffectiveEndpoint(request);
	CoapObserveRelation relation = new CoapObserveRelation(request, outEndpoint);
	request.addMessageObserver(new ObserveMessageObserverImpl(handler, relation));
	send(request, outEndpoint);
	return relation;
}
 
Example #24
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a CoAP request using the <em>coaps</em> scheme.
 *
 * @param code The CoAP request code.
 * @param type The message type.
 * @param resource the resource path.
 * @param payload The payload to send in the request body.
 * @return The request to send.
 */
protected Request createCoapsRequest(
        final Code code,
        final Type type,
        final String resource,
        final byte[] payload) {
    final Request request = new Request(code, type);
    request.setURI(getCoapsRequestUri(resource));
    request.setPayload(payload);
    request.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    return request;
}
 
Example #25
Source File: CoapEndpoint.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void sendRequest(final Request request) {
	// always use endpoint executor
	runInProtocolStage(new Runnable() {
		public void run() {
			coapstack.sendRequest(request);
		}
	});
}
 
Example #26
Source File: CoapStack.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void receiveRequest(Exchange exchange, Request request) {
	// if there is no BlockwiseLayer we still have to set it
	if (exchange.getRequest() == null)
		exchange.setRequest(request);
	if (deliverer != null) {
		deliverer.deliverRequest(exchange);
	} else {
		LOGGER.severe("Top of CoAP stack has no deliverer to deliver request");
	}
}
 
Example #27
Source File: CoapTransportResource.java    From Groza with Apache License 2.0 5 votes vote down vote up
private Optional<FeatureType> getFeatureType(Request request) {
    List<String> uriPath = request.getOptions().getUriPath();
    try {
        if (uriPath.size() >= FEATURE_TYPE_POSITION) {
            return Optional.of(FeatureType.valueOf(uriPath.get(FEATURE_TYPE_POSITION - 1).toUpperCase()));
        }
    } catch (RuntimeException e) {
        log.warn("Failed to decode feature type: {}", uriPath);
    }
    return Optional.empty();
}
 
Example #28
Source File: CoapClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Sends the specified request over the specified endpoint.
 * 
 * @param request the request
 * @param outEndpoint the endpoint
 * @return the request
 */
protected Request send(Request request, Endpoint outEndpoint) {
	// use the specified message type
	request.setType(this.type);

	if (blockwise!=0) {
		request.getOptions().setBlock2(new BlockOption(BlockOption.size2Szx(this.blockwise), false, 0));
	}
	
	outEndpoint.sendRequest(request);
	return request;
}
 
Example #29
Source File: CoapTransportResource.java    From Groza with Apache License 2.0 5 votes vote down vote up
private Optional<DeviceCredentialsFilter> decodeCredentials(Request request) {
    List<String> uriPath = request.getOptions().getUriPath();
    DeviceCredentialsFilter credentials = null;
    if (uriPath.size() >= ACCESS_TOKEN_POSITION) {
        credentials = new DeviceTokenCredentials(uriPath.get(ACCESS_TOKEN_POSITION - 1));
    }
    return Optional.ofNullable(credentials);
}
 
Example #30
Source File: HCoapClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public boolean processAsyncRequest(ResponseListener listener, OneM2mRequest reqMessage) throws Exception {
//		try {
			this.listener = listener;
			Request request = CoapRequestCodec.encode(reqMessage);
			client.advanced(this, request);
			
			return true;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		
//		return false;
	}