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