org.eclipse.californium.core.server.resources.Resource Java Examples

The following examples show how to use org.eclipse.californium.core.server.resources.Resource. 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: ServerMessageDeliverer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void deliverRequest(final Exchange exchange) {
	Request request = exchange.getRequest();
	List<String> path = request.getOptions().getUriPath();
	final Resource resource = findResource(path);
	if (resource != null) {
		checkForObserveOption(exchange, resource);
		
		// Get the executor and let it process the request
		Executor executor = resource.getExecutor();
		if (executor != null) {
			exchange.setCustomExecutor();
			executor.execute(new Runnable() {
				public void run() {
					resource.handleRequest(exchange);
				} });
		} else {
			resource.handleRequest(exchange);
		}
	} else {
		LOGGER.info("Did not find resource " + path.toString() + " requested by " + request.getSource()+":"+request.getSourcePort());
		exchange.sendResponse(new Response(ResponseCode.NOT_FOUND));
	}
}
 
Example #2
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void serializeTree(Resource resource, List<String> queries, StringBuilder buffer) {
	// add the current resource to the buffer
	if (resource.isVisible()
			&& LinkFormat.matches(resource, queries)) {
		buffer.append(LinkFormat.serializeResource(resource));
	}
	
	// sort by resource name
	List<Resource> childs = new ArrayList<Resource>(resource.getChildren());
	Collections.sort(childs, new Comparator<Resource>() {
	    @Override
	    public int compare(Resource o1, Resource o2) {
	        return o1.getName().compareTo(o2.getName());
	    }
	});
	
	for (Resource child:childs) {
		serializeTree(child, queries, buffer);
	}
}
 
Example #3
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public synchronized void setName(String name) {
	if (name == null)
		throw new NullPointerException();
	String old = this.name;
	
	// adjust parent if in tree
	Resource parent = getParent();
	if (parent!=null) {
		synchronized (parent) {
			parent.delete(this);
			this.name = name;
			parent.add(this);
		}
	} else {
		this.name = name;
	}
	adjustChildrenPath();
	
	for (ResourceObserver obs:observers)
		obs.changedName(old);
}
 
Example #4
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void serializeTree(Resource resource, List<String> queries, StringBuilder buffer) {
	// add the current resource to the buffer
	if (resource.isVisible()
			&& LinkFormat.matches(resource, queries)) {
		buffer.append(LinkFormat.serializeResource(resource));
	}
	
	// sort by resource name
	List<Resource> childs = new ArrayList<Resource>(resource.getChildren());
	Collections.sort(childs, new Comparator<Resource>() {
	    @Override
	    public int compare(Resource o1, Resource o2) {
	        return o1.getName().compareTo(o2.getName());
	    }
	});
	
	for (Resource child:childs) {
		serializeTree(child, queries, buffer);
	}
}
 
Example #5
Source File: ServerMessageDeliverer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void deliverRequest(final Exchange exchange) {
	Request request = exchange.getRequest();
	List<String> path = request.getOptions().getUriPath();
	final Resource resource = findResource(path);
	if (resource != null) {
		checkForObserveOption(exchange, resource);
		
		// Get the executor and let it process the request
		Executor executor = resource.getExecutor();
		if (executor != null) {
			exchange.setCustomExecutor();
			executor.execute(new Runnable() {
				public void run() {
					resource.handleRequest(exchange);
				} });
		} else {
			resource.handleRequest(exchange);
		}
	} else {
		LOGGER.info("Did not find resource " + path.toString() + " requested by " + request.getSource()+":"+request.getSourcePort());
		exchange.sendResponse(new Response(ResponseCode.NOT_FOUND));
	}
}
 
Example #6
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter registers resources as part of the start-up process.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartRegistersResources(final VertxTestContext ctx) {

    // GIVEN an adapter
    final CoapServer server = getCoapServer(false);
    // and a set of resources
    final Resource resource = mock(Resource.class);

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

    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.succeeding(s -> {
        // THEN the resources have been registered with the server
        final ArgumentCaptor<VertxCoapResource> resourceCaptor = ArgumentCaptor.forClass(VertxCoapResource.class);
        ctx.verify(() -> {
            verify(server).add(resourceCaptor.capture());
            assertThat(resourceCaptor.getValue().getWrappedResource()).isEqualTo(resource);
        });
        ctx.completeNow();
    }));
    adapter.start(startupTracker);

}
 
Example #7
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public synchronized void setName(String name) {
	if (name == null)
		throw new NullPointerException();
	String old = this.name;
	
	// adjust parent if in tree
	Resource parent = getParent();
	if (parent!=null) {
		synchronized (parent) {
			parent.delete(this);
			this.name = name;
			parent.add(this);
		}
	} else {
		this.name = name;
	}
	adjustChildrenPath();
	
	for (ResourceObserver obs:observers)
		obs.changedName(old);
}
 
Example #8
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public synchronized void add(Resource child) {
	if (child.getName() == null)
		throw new NullPointerException("Child must have a name");
	if (child.getParent() != null)
		child.getParent().delete(child);
	children.put(child.getName(), child);
	child.setParent(this);
	for (ResourceObserver obs:observers)
		obs.addedChild(child);
}
 
Example #9
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static StringBuilder serializeResource(Resource resource) {
	StringBuilder buffer = new StringBuilder();
	buffer.append("<")
		.append(resource.getPath())
		.append(resource.getName())
		.append(">")
		.append(LinkFormat.serializeAttributes(resource.getAttributes()))
		.append(",");
	return buffer;
}
 
Example #10
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public synchronized boolean delete(Resource child) {
	Resource deleted = delete(child.getName());
	if (deleted == child) {
		child.setParent(null);
		child.setPath(null);
		for (ResourceObserver obs : observers)
			obs.removedChild(child);
		return true;
	}
	return false;
}
 
Example #11
Source File: CoapServer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Add a resource to the server.
 * @param resources the resource(s)
 * @return the server
 */
@Override
public CoapServer add(Resource... resources) {
	for (Resource r:resources)
		root.add(r);
	return this;
}
 
Example #12
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Delete this resource from its parents and notify all observing CoAP
 * clients that this resource is no longer accessible.
 */
public synchronized void delete() {
	Resource parent = getParent();
	if (parent != null) {
		parent.delete(this);
	}
	
	if (isObservable()) {
		clearAndNotifyObserveRelations(ResponseCode.NOT_FOUND);
	}
}
 
Example #13
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Delete this resource from its parents and notify all observing CoAP
 * clients that this resource is no longer accessible.
 */
public synchronized void delete() {
	Resource parent = getParent();
	if (parent != null) {
		parent.delete(this);
	}
	
	if (isObservable()) {
		clearAndNotifyObserveRelations(ResponseCode.NOT_FOUND);
	}
}
 
Example #14
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public synchronized boolean delete(Resource child) {
	Resource deleted = delete(child.getName());
	if (deleted == child) {
		child.setParent(null);
		child.setPath(null);
		for (ResourceObserver obs : observers)
			obs.removedChild(child);
		return true;
	}
	return false;
}
 
Example #15
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public synchronized void add(Resource child) {
	if (child.getName() == null)
		throw new NullPointerException("Child must have a name");
	if (child.getParent() != null)
		child.getParent().delete(child);
	children.put(child.getName(), child);
	child.setParent(this);
	for (ResourceObserver obs:observers)
		obs.addedChild(child);
}
 
Example #16
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new resource with the specified name and makes it visible to
 * clients if the flag is true.
 * 
 * @param name the name
 * @param visible if the resource is visible
 */
public CoapResource(String name, boolean visible) {
	this.name = name;
	this.path = "";
	this.visible = visible;
	this.attributes = new ResourceAttributes();
	this.children = new ConcurrentHashMap<String, Resource>();
	this.observers = new CopyOnWriteArrayList<ResourceObserver>();
	this.observeRelations = new ObserveRelationContainer();
	this.notificationOrderer = new ObserveNotificationOrderer();
}
 
Example #17
Source File: ObserveRelation.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new observe relation.
 * 
 * @param endpoint the observing endpoint
 * @param resource the observed resource
 * @param exchange the exchange that tries to establish the observe relation
 */
public ObserveRelation(ObservingEndpoint endpoint, Resource resource, Exchange exchange) {
	if (endpoint == null)
		throw new NullPointerException();
	if (resource == null)
		throw new NullPointerException();
	if (exchange == null)
		throw new NullPointerException();
	this.endpoint = endpoint;
	this.resource = resource;
	this.exchange = exchange;
	this.established = false;
	
	this.key = getSource().toString() + "#" + exchange.getRequest().getTokenString();
}
 
Example #18
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new resource with the specified name and makes it visible to
 * clients if the flag is true.
 * 
 * @param name the name
 * @param visible if the resource is visible
 */
public CoapResource(String name, boolean visible) {
	this.name = name;
	this.path = "";
	this.visible = visible;
	this.attributes = new ResourceAttributes();
	this.children = new ConcurrentHashMap<String, Resource>();
	this.observers = new CopyOnWriteArrayList<ResourceObserver>();
	this.observeRelations = new ObserveRelationContainer();
	this.notificationOrderer = new ObserveNotificationOrderer();
}
 
Example #19
Source File: ObserveRelation.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new observe relation.
 * 
 * @param endpoint the observing endpoint
 * @param resource the observed resource
 * @param exchange the exchange that tries to establish the observe relation
 */
public ObserveRelation(ObservingEndpoint endpoint, Resource resource, Exchange exchange) {
	if (endpoint == null)
		throw new NullPointerException();
	if (resource == null)
		throw new NullPointerException();
	if (exchange == null)
		throw new NullPointerException();
	this.endpoint = endpoint;
	this.resource = resource;
	this.exchange = exchange;
	this.established = false;
	
	this.key = getSource().toString() + "#" + exchange.getRequest().getTokenString();
}
 
Example #20
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 #21
Source File: ServerMessageDeliverer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Searches in the resource tree for the specified path. A parent resource
 * may accept requests to subresources, e.g., to allow addresses with
 * wildcards like <code>coap://example.com:5683/devices/*</code>
 * 
 * @param list the path as list of resource names
 * @return the resource or null if not found
 */
private Resource findResource(List<String> list) {
	LinkedList<String> path = new LinkedList<String>(list);
	Resource current = root;
	
	while (!path.isEmpty() && current != null) {
		String name = path.removeFirst();
		current = current.getChild(name);
		if(current != null && current.isAllChildFilter()) {	
			break;
		}
	}
	
	return current;
}
 
Example #22
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String serializeTree(Resource resource) {
	StringBuilder buffer = new StringBuilder();
	List<String> noQueries = Collections.emptyList();
	
	// only include children, not the entry point itself
	for (Resource child:resource.getChildren()) {
		serializeTree(child, noQueries, buffer);
	}
	
	if (buffer.length()>1)
		buffer.delete(buffer.length()-1, buffer.length());
	return buffer.toString();
}
 
Example #23
Source File: ServerMessageDeliverer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Searches in the resource tree for the specified path. A parent resource
 * may accept requests to subresources, e.g., to allow addresses with
 * wildcards like <code>coap://example.com:5683/devices/*</code>
 * 
 * @param list the path as list of resource names
 * @return the resource or null if not found
 */
private Resource findResource(List<String> list) {
	LinkedList<String> path = new LinkedList<String>(list);
	Resource current = root;
	
	while (!path.isEmpty() && current != null) {
		String name = path.removeFirst();
		current = current.getChild(name);
		if(current != null && current.isAllChildFilter()) {	
			break;
		}
	}
	
	return current;
}
 
Example #24
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String serializeTree(Resource resource) {
	StringBuilder buffer = new StringBuilder();
	List<String> noQueries = Collections.emptyList();
	
	// only include children, not the entry point itself
	for (Resource child:resource.getChildren()) {
		serializeTree(child, noQueries, buffer);
	}
	
	if (buffer.length()>1)
		buffer.delete(buffer.length()-1, buffer.length());
	return buffer.toString();
}
 
Example #25
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static StringBuilder serializeResource(Resource resource) {
	StringBuilder buffer = new StringBuilder();
	buffer.append("<")
		.append(resource.getPath())
		.append(resource.getName())
		.append(">")
		.append(LinkFormat.serializeAttributes(resource.getAttributes()))
		.append(",");
	return buffer;
}
 
Example #26
Source File: CoapServer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Add a resource to the server.
 * @param resources the resource(s)
 * @return the server
 */
@Override
public CoapServer add(Resource... resources) {
	for (Resource r:resources)
		root.add(r);
	return this;
}
 
Example #27
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static boolean matches(Resource resource, List<String> queries) {
	
	if (resource==null) return false;
	if (queries==null || queries.size()==0) return true;
	
	ResourceAttributes attributes = resource.getAttributes();
	String path = resource.getPath()+resource.getName();
	
	for (String s : queries) {
		int delim = s.indexOf("=");
		if (delim != -1) {
			
			// split name-value-pair
			String attrName = s.substring(0, delim);
			String expected = s.substring(delim+1);

			if (attrName.equals(LinkFormat.LINK)) {
				if (expected.endsWith("*")) {
					return path.startsWith(expected.substring(0, expected.length()-1));
				} else {
					return path.equals(expected);
				}
			} else if (attributes.containsAttribute(attrName)) {
				// lookup attribute value
				for (String actual : attributes.getAttributeValues(attrName)) {
				
					// get prefix length according to "*"
					int prefixLength = expected.indexOf('*');
					if (prefixLength >= 0 && prefixLength < actual.length()) {
				
						// reduce to prefixes
						expected = expected.substring(0, prefixLength);
						actual = actual.substring(0, prefixLength);
					}
					
					// handle case like rt=[Type1 Type2]
					if (actual.indexOf(" ") > -1) { // if contains white space
						String[] parts = actual.split(" ");
						for (String part : parts) { // check each part for match
							if (part.equals(expected)) {
								return true;
							}
						}
					}
					
					// compare strings
					if (expected.equals(actual)) {
						return true;
					}
				}
			}
		} else {
			// flag attribute
			if (attributes.getAttributeValues(s).size()>0) {
				return true;
			}
		}
	}
	return false;
}
 
Example #28
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setParent(Resource parent) {
	this.parent = parent;
	if (parent != null)
		this.path = parent.getPath()  + parent.getName() + "/";
	adjustChildrenPath();
}
 
Example #29
Source File: LinkFormat.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static boolean matches(Resource resource, List<String> queries) {
	
	if (resource==null) return false;
	if (queries==null || queries.size()==0) return true;
	
	ResourceAttributes attributes = resource.getAttributes();
	String path = resource.getPath()+resource.getName();
	
	for (String s : queries) {
		int delim = s.indexOf("=");
		if (delim != -1) {
			
			// split name-value-pair
			String attrName = s.substring(0, delim);
			String expected = s.substring(delim+1);

			if (attrName.equals(LinkFormat.LINK)) {
				if (expected.endsWith("*")) {
					return path.startsWith(expected.substring(0, expected.length()-1));
				} else {
					return path.equals(expected);
				}
			} else if (attributes.containsAttribute(attrName)) {
				// lookup attribute value
				for (String actual : attributes.getAttributeValues(attrName)) {
				
					// get prefix length according to "*"
					int prefixLength = expected.indexOf('*');
					if (prefixLength >= 0 && prefixLength < actual.length()) {
				
						// reduce to prefixes
						expected = expected.substring(0, prefixLength);
						actual = actual.substring(0, prefixLength);
					}
					
					// handle case like rt=[Type1 Type2]
					if (actual.indexOf(" ") > -1) { // if contains white space
						String[] parts = actual.split(" ");
						for (String part : parts) { // check each part for match
							if (part.equals(expected)) {
								return true;
							}
						}
					}
					
					// compare strings
					if (expected.equals(actual)) {
						return true;
					}
				}
			}
		} else {
			// flag attribute
			if (attributes.getAttributeValues(s).size()>0) {
				return true;
			}
		}
	}
	return false;
}
 
Example #30
Source File: CoapResource.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override // should be used for read-only
public Collection<Resource> getChildren() {
	return children.values();
}