Commit 460a2f14 authored by Björn Butzin's avatar Björn Butzin
Browse files

Refactoring

parent 7b80696a
......@@ -34,11 +34,11 @@ public class BasicCoapBlockClient implements CoapClient {
try {
clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT);
CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET);
this.clientChannel = this.channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT);
CoapRequest coapRequest = this.clientChannel.createRequest(true, CoapRequestCode.GET);
coapRequest.setUriPath("/large");
clientChannel.setMaxReceiveBlocksize(CoapBlockSize.BLOCK_64);
clientChannel.sendMessage(coapRequest);
this.clientChannel.setMaxReceiveBlocksize(CoapBlockSize.BLOCK_64);
this.clientChannel.sendMessage(coapRequest);
System.out.println("Sent Request");
} catch (UnknownHostException e) {
e.printStackTrace();
......
......@@ -47,7 +47,7 @@ public class BasicCoapClient implements CoapClient {
public boolean connect(){
try {
clientChannel = (BasicCoapClientChannel) channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT);
this.clientChannel = (BasicCoapClientChannel) this.channelManager.connect(this, InetAddress.getByName(this.SERVER_ADDRESS), this.PORT);
} catch( UnknownHostException e ){
e.printStackTrace();
return false;
......@@ -64,35 +64,35 @@ public class BasicCoapClient implements CoapClient {
public CoapRequest createRequest( boolean reliable, CoapRequestCode reqCode ) {
return clientChannel.createRequest( reliable, reqCode );
return this.clientChannel.createRequest( reliable, reqCode );
}
public void sendRequest( CoapRequest request ){
if( request.getRequestCode() == CoapRequestCode.PUT || request.getRequestCode() == CoapRequestCode.POST ){
if( ( clientChannel.getMaxSendBlocksize() != null || request.getBlock1() != null ) ) {
request = clientChannel.addBlockContext( request);
if( ( this.clientChannel.getMaxSendBlocksize() != null || request.getBlock1() != null ) ) {
request = this.clientChannel.addBlockContext( request);
}
} else if( request.getRequestCode() == CoapRequestCode.GET && ( request.getBlock2() == null && clientChannel.getMaxReceiveBlocksize() != null )) {
CoapBlockOption block2 = new CoapBlockOption( 0, false, clientChannel.getMaxReceiveBlocksize() );
} else if( request.getRequestCode() == CoapRequestCode.GET && ( request.getBlock2() == null && this.clientChannel.getMaxReceiveBlocksize() != null )) {
CoapBlockOption block2 = new CoapBlockOption( 0, false, this.clientChannel.getMaxReceiveBlocksize() );
request.setBlock2( block2 );
}
clientChannel.sendMessage(request);
this.clientChannel.sendMessage(request);
}
public void setReceiveBlockSize( CoapBlockSize size ){
if( clientChannel != null )
clientChannel.setMaxReceiveBlocksize( size );
if( this.clientChannel != null )
this.clientChannel.setMaxReceiveBlocksize( size );
}
public void setSendBlockSize( CoapBlockSize size ){
if( clientChannel != null )
clientChannel.setMaxSendBlocksize(size);
if( this.clientChannel != null )
this.clientChannel.setMaxSendBlocksize(size);
}
public byte[] generateRequestToken(int tokenLength ){
byte[] token = new byte[tokenLength];
tokenGen.nextBytes(token);
this.tokenGen.nextBytes(token);
return token;
}
......
/*
* Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work has been sponsored by Siemens Corporate Technology.
*
*/
package org.ws4d.coap.proxy;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.entity.ContentListener;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.nio.util.SimpleInputBuffer;
/**
* This class is used to consume an entity and get the entity-data as byte-array.
* The only other class which implements ContentListener is SkipContentListener.
* SkipContentListener is ignoring all content.
* Look at Apache HTTP Components Core NIO Framework -> Java-Documentation of SkipContentListener.
*/
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
* @author Andy Seidel <andy.seidel@uni-rostock.de>
*/
class ByteContentListener implements ContentListener {
final SimpleInputBuffer input = new SimpleInputBuffer(2048, new HeapByteBufferAllocator());
public void consumeContent(ContentDecoder decoder, IOControl ioctrl)
throws IOException {
input.consumeContent(decoder);
}
public void finish() {
input.reset();
}
byte[] getContent() throws IOException {
byte[] b = new byte[input.length()];
input.read(b);
return b;
}
@Override
public void contentAvailable(ContentDecoder decoder, IOControl arg1)
throws IOException {
input.consumeContent(decoder);
}
@Override
public void finished() {
input.reset();
}
}
/*
* Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work has been sponsored by Siemens Corporate Technology.
*
*/
package org.ws4d.coap.proxy;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.entity.ContentListener;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.nio.util.SimpleInputBuffer;
/**
* This class is used to consume an entity and get the entity-data as byte-array.
* The only other class which implements ContentListener is SkipContentListener.
* SkipContentListener is ignoring all content.
* Look at Apache HTTP Components Core NIO Framework -> Java-Documentation of SkipContentListener.
*/
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
* @author Andy Seidel <andy.seidel@uni-rostock.de>
*/
class ByteContentListener implements ContentListener {
final SimpleInputBuffer input = new SimpleInputBuffer(2048, new HeapByteBufferAllocator());
public void consumeContent(ContentDecoder decoder, IOControl ioctrl)
throws IOException {
this.input.consumeContent(decoder);
}
public void finish() {
this.input.reset();
}
byte[] getContent() throws IOException {
byte[] b = new byte[this.input.length()];
this.input.read(b);
return b;
}
@Override
public void contentAvailable(ContentDecoder decoder, IOControl arg1)
throws IOException {
this.input.consumeContent(decoder);
}
@Override
public void finished() {
this.input.reset();
}
}
/*
* Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work has been sponsored by Siemens Corporate Technology.
*
*/
package org.ws4d.coap.proxy;
import java.net.InetAddress;
import org.apache.log4j.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.interfaces.CoapClient;
import org.ws4d.coap.interfaces.CoapClientChannel;
import org.ws4d.coap.interfaces.CoapResponse;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
* @author Andy Seidel <andy.seidel@uni-rostock.de>
*/
public class CoapClientProxy implements CoapClient{
static Logger logger = Logger.getLogger(Proxy.class);
ProxyMapper mapper = ProxyMapper.getInstance();
static final boolean RELIABLE = true; //use CON as client (NON has no timeout!!!)
/* creates a client channel and stores it in the context*/
public void createChannel(ProxyMessageContext context){
// create channel
CoapClientChannel channel;
channel = BasicCoapChannelManager.getInstance().connect(this, context.getServerAddress(), context.getServerPort());
if (channel != null) {
channel.setTrigger(context);
context.setOutCoapClientChannel(channel);
} else {
throw new IllegalStateException("CoAP client connect() failed");
}
}
public void closeChannel(ProxyMessageContext context){
context.getOutCoapClientChannel().close();
}
public void sendRequest(ProxyMessageContext context) {
context.getOutCoapRequest().getChannel().sendMessage(context.getOutCoapRequest());
}
@Override
public void onResponse(CoapClientChannel channel, CoapResponse response) {
ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger();
channel.close();
if (context != null) {
context.setInCoapResponse(response);
mapper.handleCoapClientResponse(context);
}
}
@Override
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) {
ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger();
channel.close();
if (context != null) {
logger.warn("Coap client connection failed (e.g., timeout)!");
context.setInCoapResponse(null); // null indicates no response
mapper.handleCoapClientResponse(context);
}
}
@Override
public void onMCResponse(CoapClientChannel channel, CoapResponse response, InetAddress srcAddress, int srcPort) {
System.out.println("Received Response");
}
}
/*
* Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work has been sponsored by Siemens Corporate Technology.
*
*/
package org.ws4d.coap.proxy;
import java.net.InetAddress;
import org.apache.log4j.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.interfaces.CoapClient;
import org.ws4d.coap.interfaces.CoapClientChannel;
import org.ws4d.coap.interfaces.CoapResponse;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
* @author Andy Seidel <andy.seidel@uni-rostock.de>
*/
public class CoapClientProxy implements CoapClient{
static Logger logger = Logger.getLogger(Proxy.class);
ProxyMapper mapper = ProxyMapper.getInstance();
static final boolean RELIABLE = true; //use CON as client (NON has no timeout!!!)
/* creates a client channel and stores it in the context*/
public void createChannel(ProxyMessageContext context){
// create channel
CoapClientChannel channel;
channel = BasicCoapChannelManager.getInstance().connect(this, context.getServerAddress(), context.getServerPort());
if (channel != null) {
channel.setTrigger(context);
context.setOutCoapClientChannel(channel);
} else {
throw new IllegalStateException("CoAP client connect() failed");
}
}
public void closeChannel(ProxyMessageContext context){
context.getOutCoapClientChannel().close();
}
public void sendRequest(ProxyMessageContext context) {
context.getOutCoapRequest().getChannel().sendMessage(context.getOutCoapRequest());
}
@Override
public void onResponse(CoapClientChannel channel, CoapResponse response) {
ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger();
channel.close();
if (context != null) {
context.setInCoapResponse(response);
this.mapper.handleCoapClientResponse(context);
}
}
@Override
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) {
ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger();
channel.close();
if (context != null) {
logger.warn("Coap client connection failed (e.g., timeout)!");
context.setInCoapResponse(null); // null indicates no response
this.mapper.handleCoapClientResponse(context);
}
}
@Override
public void onMCResponse(CoapClientChannel channel, CoapResponse response, InetAddress srcAddress, int srcPort) {
System.out.println("Received Response");
}
}
/*
* Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work has been sponsored by Siemens Corporate Technology.
*
*/
package org.ws4d.coap.proxy;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.concurrent.ArrayBlockingQueue;
import org.apache.log4j.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapRequest;
import org.ws4d.coap.interfaces.CoapServer;
import org.ws4d.coap.interfaces.CoapServerChannel;
import org.ws4d.coap.messages.BasicCoapResponse;
import org.ws4d.coap.messages.CoapResponseCode;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
* @author Andy Seidel <andy.seidel@uni-rostock.de>
*/
public class CoapServerProxy implements CoapServer{
static Logger logger = Logger.getLogger(Proxy.class);
private static final int LOCAL_PORT = 5683; //port on which the server is listening
ProxyMapper mapper = ProxyMapper.getInstance();
//coapOUTq_ receives a coap-response from mapper in case of coap-http
CoapChannelManager channelManager;
//constructor of coapserver-class, initiates the jcoap-components and starts CoapSender
public CoapServerProxy() {
channelManager = BasicCoapChannelManager.getInstance();
channelManager.createServerListener(this, LOCAL_PORT);
}
//interface-function for the message-queue
public void sendResponse(ProxyMessageContext context) {
CoapServerChannel channel = (CoapServerChannel) context.getInCoapRequest().getChannel();
channel.sendMessage(context.getOutCoapResponse());
channel.close(); //TODO: implement strategy when to close a channel
}
@Override
public CoapServer onAccept(CoapRequest request) {
logger.info("new incomming CoAP connection");
/* accept every incoming connection */
return this;
}
@Override
public void onRequest(CoapServerChannel channel, CoapRequest request) {
/* draft-08:
* CoAP distinguishes between requests to an origin server and a request
made through a proxy. A proxy is a CoAP end-point that can be tasked
by CoAP clients to perform requests on their behalf. This may be
useful, for example, when the request could otherwise not be made, or
to service the response from a cache in order to reduce response time
and network bandwidth or energy consumption.
CoAP requests to a proxy are made as normal confirmable or non-
confirmable requests to the proxy end-point, but specify the request
URI in a different way: The request URI in a proxy request is
specified as a string in the Proxy-Uri Option (see Section 5.10.3),
while the request URI in a request to an origin server is split into
the Uri-Host, Uri-Port, Uri-Path and Uri-Query Options (see
Section 5.10.2).
*/
URI proxyUri = null;
/* we need to cast to allow an efficient header copy */
//create a prototype response, will be changed during the translation process
try {
BasicCoapResponse response = (BasicCoapResponse) channel.createResponse(request, CoapResponseCode.Internal_Server_Error_500);
try {
proxyUri = new URI(request.getProxyUri());
} catch (Exception e) {
proxyUri = null;
}
if (proxyUri == null) {
/* PROXY URI MUST BE AVAILABLE */
logger.warn("received CoAP request without Proxy-Uri option");
channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400));
channel.close();
return;
}
/* check scheme if we should translate */
boolean translate;
if (proxyUri.getScheme().compareToIgnoreCase("http") == 0) {
translate = true;
} else if (proxyUri.getScheme().compareToIgnoreCase("coap") == 0) {
translate = false;
} else {
/* unknown scheme */
logger.warn("invalid proxy uri scheme");
channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400));
channel.close();
return;
}
/* parse URL */
InetAddress serverAddress = InetAddress.getByName(proxyUri.getHost());
int serverPort = proxyUri.getPort();
if (serverPort == -1) {
if (translate) {
/* HTTP Server */
serverPort = 80; // FIXME: use constant for HTTP well known
// port
} else {
/* CoAP Server */
serverPort = org.ws4d.coap.Constants.COAP_DEFAULT_PORT;
}
}
/* generate context and forward message */
ProxyMessageContext context = new ProxyMessageContext(request, translate, proxyUri);
context.setServerAddress(serverAddress, serverPort);
context.setOutCoapResponse(response);
mapper.handleCoapServerRequest(context);
} catch (Exception e) {
logger.warn("invalid message");
channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400));
channel.close();
}
}
@Override
public void onSeparateResponseFailed(CoapServerChannel channel) {
// TODO Auto-generated method stub
}
@Override
public void onReset(CoapRequest lastRequest) {
System.out.println("Received RST message");
}
}
/*
* Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work has been sponsored by Siemens Corporate Technology.
*
*/
package org.ws4d.coap.proxy;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.concurrent.ArrayBlockingQueue;